Swift SDK for Blockfrost.io API

Overview

Swift5 API client for Blockfrost

CI badge


Swift 5 SDK for Blockfrost.io API.

InstallationUsageAPI Endpoints


Installation

Swift package manager

dependencies: [
    .package(url: "https://github.com/blockfrost/blockfrost-swift.git", from: "0.0.5"),
],

targets: [
    .executableTarget(
        name: "Example",
        dependencies: [
            .product(name: "BlockfrostSwiftSDK", package: "blockfrost-swift"),
        ]),
]

Carthage

Run carthage update

Cartfile

0.0.5 ">
github "blockfrost/blockfrost-swift" ~> 0.0.5

CocoaPods

Minimal pod version: 1.10+ Run pod install

Podfile:

pod 'BlockfrostSwiftSDK', '~> 0.0.5'

Or use GitHub, by tag:

pod 'BlockfrostSwiftSDK', :git => 'https://github.com/blockfrost/blockfrost-swift.git', :tag => '0.0.5'

or by branch:

pod 'BlockfrostSwiftSDK', :git => 'https://github.com/blockfrost/blockfrost-swift.git', :branch => 'master'

Usage

API uses a simple completion callbacks, returning Swift.Result , where R is defined by the particular API call.

// import the SDK on the beginning of the file
import BlockfrostSwiftSDK

// define project-wide settings
BlockfrostStaticConfig.basePath = "https://cardano-mainnet.blockfrost.io/api/v0"  // or leave default
BlockfrostStaticConfig.projectId = "your-project-id"
let api = CardanoAddressesAPI()

_ = api.getAddressDetails(address: "addr1q8zu4smzyf2r2mfqjd6tc6vxf2p8rccdfk82ye3eut2udkw9etpkygj5x4kjpym5h35cvj5zw83s6nvw5fnrnck4cmvshkfm4y") { resp in
    switch (resp) {
    case let .failure(err):
        // TODO: handle error here, `err` contains the error 
        break
    case let .success(r):
        // `r` contains result of the call, here, it is of type `AddressContentTotal`
        break
    }
}

Project ID can be loaded from env

BlockfrostStaticConfig.projectId = BlockfrostConfig.getEnvProjectId()  // BF_PROJECT_ID
BlockfrostStaticConfig.projectId = BlockfrostConfig.getEnvProjectIdMainnet()  // BF_MAINNET_PROJECT_ID
BlockfrostStaticConfig.projectId = BlockfrostConfig.getEnvProjectIdTestnet()  // BF_TESTNET_PROJECT_ID
BlockfrostStaticConfig.projectId = BlockfrostConfig.getEnvIpfsProjectId()  // BF_IPFS_PROJECT_ID

Default configuration for testnet, project ID is loaded from env var BF_TESTNET_PROJECT_ID

let apiAdd = CardanoAddressesAPI(config: BlockfrostConfig.testnetDefault())

Default configuration for IPFS, project ID is loaded from env var BF_IPFS_PROJECT_ID

let ipfsAdd = IPFSAddAPI(config: BlockfrostConfig.ipfsDefault())

You can also define API-specific configuration

let config = BlockfrostConfig()
config.basePath = BlockfrostConfig.URL_IPFS
config.projectId = BlockfrostConfig.getEnvIpfsProjectId()
config.retryPolicy = BlockfrostRetryPolicy(retryLimit: 10)    // specify custom retry policy

let ipfsAdd = apiAdd = IPFSAddAPI(config: cfg)

Check out Example application or integration tests for more usage examples.

Fetch All methods

Methods with paging parameters (count, page, order) have paging methods enabling to load all results, iterating over all pages in the background. The method returns list of all results once all pages have been downloaded.

let _ = api.getAssetHistoryAll(asset: "d894897411707efa755a76deb66d26dfd50593f2e70863e1661e98a07370616365636f696e73") { resp in
    switch (resp) {
    case let .failure(err):
        // TODO: handle error here, `err` contains the error 
        break
    case let .success(r):
        // `r` contains result of the call, here, it is of type `AddressContentTotal`
        break
    }
}

Advanced Fetch all

To use more advanced load-all-pages technique, you can use PageLoader class.

let loader = PageLoader<AssetHistory>(batchSize: 10)
loader.loadAll({ count, page, compl in
    // PageLoader uses lambda to load particular page
    _ = api.getAssetHistory(asset: asset, count: count, page: page, order: order, apiResponseQueue: apiResponseQueue, completion: compl)
}, completion: { compl in
    // Completion handler once all pages are loaded
    // TODO: handle the results
})

You can handle event handler to get new page results as they are loaded:

loader.progressHandler = { event in
    switch(event){
    case .started: break
    case let .pageLoaded(page):
        print(page)  // new page loaded, type: (Int, [T]) ~ page ID and list of results               
        break
    case .completed(_):
        break
    }
}

You can also cancel further loading:

DispatchQueue.global().async { loader.cancel() }

API Endpoints

Class Method HTTP request Description
CardanoAccountsAPI getAccountAddresses GET /accounts/{stake_address}/addresses Account associated addresses
CardanoAccountsAPI getAccountAssets GET /accounts/{stake_address}/addresses/assets Assets associated with the account addresses
CardanoAccountsAPI getAccountByStakeAddress GET /accounts/{stake_address} Specific account address
CardanoAccountsAPI getAccountDelegationHistory GET /accounts/{stake_address}/delegations Account delegation history
CardanoAccountsAPI getAccountHistory GET /accounts/{stake_address}/history Account history
CardanoAccountsAPI getAccountMirHistory GET /accounts/{stake_address}/mirs Account MIR history
CardanoAccountsAPI getAccountRegistrationHistory GET /accounts/{stake_address}/registrations Account registration history
CardanoAccountsAPI getAccountRewardHistory GET /accounts/{stake_address}/rewards Account reward history
CardanoAccountsAPI getAccountWithdrawalHistory GET /accounts/{stake_address}/withdrawals Account withdrawal history
CardanoAddressesAPI getAddress GET /addresses/{address} Specific address
CardanoAddressesAPI getAddressDetails GET /addresses/{address}/total Address details
CardanoAddressesAPI getAddressTransactions GET /addresses/{address}/transactions Address transactions
CardanoAddressesAPI getAddressTxs GET /addresses/{address}/txs Address transactions
CardanoAddressesAPI getAddressUtxos GET /addresses/{address}/utxos Address UTXOs
CardanoAssetsAPI getAsset GET /assets/{asset} Specific asset
CardanoAssetsAPI getAssetAddresses GET /assets/{asset}/addresses Asset addresses
CardanoAssetsAPI getAssetHistory GET /assets/{asset}/history Asset history
CardanoAssetsAPI getAssetTransactions GET /assets/{asset}/transactions Asset transactions
CardanoAssetsAPI getAssetTxs GET /assets/{asset}/txs Asset transactions
CardanoAssetsAPI getAssets GET /assets Assets
CardanoAssetsAPI getPolicyAssets GET /assets/policy/{policy_id} Assets of a specific policy
CardanoBlocksAPI getBlock GET /blocks/{hash_or_number} Specific block
CardanoBlocksAPI getBlockInEpochInSlot GET /blocks/epoch/{epoch_number}/slot/{slot_number} Specific block in a slot in an epoch
CardanoBlocksAPI getBlockInSlot GET /blocks/slot/{slot_number} Specific block in a slot
CardanoBlocksAPI getBlockTransactions GET /blocks/{hash_or_number}/txs Block transactions
CardanoBlocksAPI getLatestBlock GET /blocks/latest Latest block
CardanoBlocksAPI getNextBlocks GET /blocks/{hash_or_number}/next Listing of next blocks
CardanoBlocksAPI getPreviousBlocks GET /blocks/{hash_or_number}/previous Listing of previous blocks
CardanoBlocksAPI getTransactionsInLatestBlock GET /blocks/latest/txs Latest block transactions
CardanoEpochsAPI getActiveStakesForEpoch GET /epochs/{number}/stakes Stake distribution
CardanoEpochsAPI getActiveStakesForEpochAndPool GET /epochs/{number}/stakes/{pool_id} Stake distribution by pool
CardanoEpochsAPI getBlocksForEpoch GET /epochs/{number}/blocks Block distribution
CardanoEpochsAPI getBlocksForEpochAndPool GET /epochs/{number}/blocks/{pool_id} Block distribution by pool
CardanoEpochsAPI getEpoch GET /epochs/{number} Specific epoch
CardanoEpochsAPI getEpochParam GET /epochs/{number}/parameters Protocol parameters
CardanoEpochsAPI getLatestEpoch GET /epochs/latest Latest epoch
CardanoEpochsAPI getLatestEpochParam GET /epochs/latest/parameters Latest epoch protocol parameters
CardanoEpochsAPI getNextEpochs GET /epochs/{number}/next Listing of next epochs
CardanoEpochsAPI getPreviousEpochs GET /epochs/{number}/previous Listing of previous epochs
CardanoLedgerAPI getGenesis GET /genesis Blockchain genesis
CardanoMetadataAPI getTransactionMetadataCborForLabel GET /metadata/txs/labels/{label}/cbor Transaction metadata content in CBOR
CardanoMetadataAPI getTransactionMetadataJsonForLabel GET /metadata/txs/labels/{label} Transaction metadata content in JSON
CardanoMetadataAPI getTransactionMetadataLabels GET /metadata/txs/labels Transaction metadata labels
CardanoNetworkAPI getNetwork GET /network Network information
CardanoPoolsAPI getPool GET /pools/{pool_id} Specific stake pool
CardanoPoolsAPI getPoolBlocks GET /pools/{pool_id}/blocks Stake pool blocks
CardanoPoolsAPI getPoolDelegators GET /pools/{pool_id}/delegators Stake pool delegators
CardanoPoolsAPI getPoolHistory GET /pools/{pool_id}/history Stake pool history
CardanoPoolsAPI getPoolMetadata GET /pools/{pool_id}/metadata Stake pool metadata
CardanoPoolsAPI getPoolRelays GET /pools/{pool_id}/relays Stake pool relays
CardanoPoolsAPI getPoolUpdates GET /pools/{pool_id}/updates Stake pool updates
CardanoPoolsAPI getPools GET /pools List of stake pools
CardanoPoolsAPI getRetiredPools GET /pools/retired List of retired stake pools
CardanoPoolsAPI getRetiringPools GET /pools/retiring List of retiring stake pools
CardanoScriptsAPI getScript GET /scripts/{script_hash} Specific script
CardanoScriptsAPI getScriptRedeemers GET /scripts/{script_hash}/redeemers Redeemers of a specific script
CardanoScriptsAPI getScripts GET /scripts Scripts
CardanoTransactionsAPI getTransaction GET /txs/{hash} Specific transaction
CardanoTransactionsAPI getTransactionDelegations GET /txs/{hash}/delegations Transaction delegation certificates
CardanoTransactionsAPI getTransactionMetadata GET /txs/{hash}/metadata Transaction metadata
CardanoTransactionsAPI getTransactionMetadataCbor GET /txs/{hash}/metadata/cbor Transaction metadata in CBOR
CardanoTransactionsAPI getTransactionMirs GET /txs/{hash}/mirs Transaction MIRs
CardanoTransactionsAPI getTransactionPoolRetires GET /txs/{hash}/pool_retires Transaction stake pool retirement certificates
CardanoTransactionsAPI getTransactionPoolUpdates GET /txs/{hash}/pool_updates Transaction stake pool registration and update certificates
CardanoTransactionsAPI getTransactionRedeemers GET /txs/{hash}/redeemers Transaction redeemers
CardanoTransactionsAPI getTransactionStakes GET /txs/{hash}/stakes Transaction stake addresses certificates
CardanoTransactionsAPI getTransactionUtxos GET /txs/{hash}/utxos Transaction UTXOs
CardanoTransactionsAPI getTransactionWithdrawals GET /txs/{hash}/withdrawals Transaction withdrawal
CardanoTransactionsAPI submitTransaction POST /tx/submit Submit a transaction
HealthAPI getApiRoot GET / Root endpoint
HealthAPI getCurrentBackendTime GET /health/clock Current backend time
HealthAPI getHealth GET /health Backend health status
IPFSAddAPI add POST /ipfs/add Add a file to IPFS
IPFSGatewayAPI callGet GET /ipfs/gateway/{IPFS_path} Relay to an IPFS gateway
IPFSPinsAPI getPinList GET /ipfs/pin/list/ List pinned objects
IPFSPinsAPI getPinListByIpfsPath GET /ipfs/pin/list/{IPFS_path} Get details about pinned object
IPFSPinsAPI pinAdd POST /ipfs/pin/add/{IPFS_path} Pin an object
IPFSPinsAPI removePin POST /ipfs/pin/remove/{IPFS_path}
MetricsAPI getMetrics GET /metrics/ Blockfrost usage metrics
MetricsAPI getMetricsEndpoints GET /metrics/endpoints Blockfrost endpoint usage metrics
NutLinkAPI getAddress GET /nutlink/{address}
NutLinkAPI getAddressTickers GET /nutlink/{address}/tickers
NutLinkAPI getTickerRecordsByAddressAndTicker GET /nutlink/{address}/tickers/{ticker}
NutLinkAPI getTickerRecordsByTicker GET /nutlink/tickers/{ticker}

Documentation For Models

Pod development

Lint before publishing:

pod spec lint --no-clean --verbose --use-modular-headers --allow-warnings

# or alternatively: (use_frameworks!)
pod spec lint --no-clean --verbose --use-modular-headers --use-libraries --allow-warnings 

Publishing new version:

pod trunk push BlockfrostSwiftSDK.podspec --verbose --allow-warnings 

Note that this pod requires CocoaPod 1.10+.

Comments
  • Add async/await api compatible with Swift 5.5

    Add async/await api compatible with Swift 5.5

    Hi,

    With Swift 5.5 Apple has introduced a new concurrency paradigm: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html

    I propose adding an additional api to this library that would add async/await support.

    opened by pgorzelany 6
  • Change url in Podspec to HTTPS one.

    Change url in Podspec to HTTPS one.

    Hello.

    Currently, in Podspec we have an SSH URL for sources. It breaks build on CI systems (sources can't be downloaded anonymously through SSH on GitHub).

    Can you, please, change it to HTTPS one and upload the new version of the library?

    I think s.source line in Podspec can be changed to:

    s.source = { :git => 'https://github.com/blockfrost/blockfrost-swift.git', :tag => s.version.to_s }
    

    Thanks.

    opened by ypopovych 2
  • Invalid project token on Query 2

    Invalid project token on Query 2

    The address data is good. print("Address data: \(r), \(r.address), \(r.txCount), \(r.sentSum)").

    Since the first query passes, I'm guessing that the environment variable for my project id (API Key) is set correctly in the target's scheme. However, during Query 2 I get:

    Error getting an address: errorStatus(403, BlockfrostSwiftSDK.Status(statusCode: Optional(403), error: Optional("Forbidden"), message: Optional("Invalid project token."))

    Just to be clear, in the Blockfrost SDK docs the API Key and product id are the same string value correct? Docs say, "project_id token is automatically generated for each project."

    Also, I'm using the address given in the sample. "addr1q8zu4smzyf2r2mfqjd6tc6vxf2p8rccdfk82ye3eut2udkw9etpkygj5x4kjpym5h35cvj5zw83s6nvw5fnrnck4cmvshkfm4y"

    If I want to switch to a testnet I only need to change:

    • The project id (API Key)
    • The address to a testnet address i.e. [addr_test1vz95zjvtwm..]
    • The configuration to BlockfrostConfig.testnetDefault()

    Is that correct?

    Do you have a list of demo mainnet and testnet address we can use? I know we can just use an explorer to use any live mainnet address but what about testnet addresses? These two where in your docs. "addr1q8zu4smzyf2r2mfqjd6tc6vxf2p8rccdfk82ye3eut2udkw9etpkygj5x4kjpym5h35cvj5zw83s6nvw5fnrnck4cmvshkfm4y"

    "addr_test1vz95zjvtwm9u9mc83uzsfj55tzwf99fgeyt3gmwm9gdw2xgwrvsa5"

     let api = CardanoAddressesAPI()
        _ = api.getAddressDetails(address: exampleAddr) { resp in
            switch (resp) {
            case let .failure(err):
                print("Error getting an address: \(self.exampleAddr): \(err)")
                break
            case let .success(r):
                print("Address data: \(r), \(r.address), \(r.txCount), \(r.sentSum)")
                print("JSON-encoded: \(String(data: (try? CodableHelper.encode(r).get()) ?? Data(), encoding: .utf8) ?? "-")")
                break
            }
            group.leave()
        }
    
        // Wait for async to complete
        group.wait()
    
        // Explicit configuration
        let config = BlockfrostConfig.mainnetDefault().clone()
        
        // Project id (API Key) here
        config.projectId = "BF_MAINNET_PROJECT_ID"
        config.apiResponseQueue = .global()
        group.enter()
    
        print("\n\nQuery 2: invalid project ID")
        let api2 = CardanoAddressesAPI(config: config)
        _ = api2.getAddressDetails(address: exampleAddr) { resp in
            switch (resp) {
            case let .failure(err):
                print("Error getting an address: \(err)")
                break
            case let .success(r):
                print("Address data: \(r)")
                break
            }
            group.leave()
        }
    
    opened by tysun 1
  • Possible bug in

    Possible bug in "submitTransaction" method

    Hi

    Seems as CardanoTransactionsAPI.submitTransactionWithRequestBuilder method misses the config parameter in RequestBuilder initialization because it can't be used with custom config, only with shared one

    Thanks, Yehor

    opened by ypopovych 1
  • feat(async): add support for async-await calls

    feat(async): add support for async-await calls

    • swift 5.7 is required
    • implements / fixes #1
    • auto-generated with openapi-generator, extended with custom modifications
    • added new improvements from the newest openapi-generator to underlying request classes
    opened by ph4r05 0
Releases(1.0.1)
  • 1.0.1(Jun 20, 2022)

    What's Changed

    • feat(async): add support for async-await calls by @ph4r05 in https://github.com/blockfrost/blockfrost-swift/pull/6

    New Contributors

    • @ph4r05 made their first contribution in https://github.com/blockfrost/blockfrost-swift/pull/6

    Full Changelog: https://github.com/blockfrost/blockfrost-swift/compare/0.0.7...1.0.1

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Jun 19, 2022)

    What's Changed

    • feat(async): add support for async-await calls by @ph4r05 in https://github.com/blockfrost/blockfrost-swift/pull/6

    New Contributors

    • @ph4r05 made their first contribution in https://github.com/blockfrost/blockfrost-swift/pull/6

    Full Changelog: https://github.com/blockfrost/blockfrost-swift/compare/0.0.7...1.0.0

    Source code(tar.gz)
    Source code(zip)
  • 0.0.7(Jun 16, 2022)

  • 0.0.6(Jan 19, 2022)

    • Fixes bug with missing config from sendTransaction, fixes #2 Full Changelog: https://github.com/blockfrost/blockfrost-swift/compare/0.0.5...0.0.6
    Source code(tar.gz)
    Source code(zip)
  • 0.0.5(Oct 8, 2021)

  • 0.0.4(Oct 8, 2021)

  • 0.0.1(Sep 23, 2021)

Owner
blockfrost.io
Cardano API-as-a-Service
blockfrost.io
Alter SDK is a cross-platform SDK consisting of a real-time 3D avatar system, facial motion capture, and an Avatar Designer component built from scratch for web3 interoperability and the open metaverse.

Alter SDK is a cross-platform SDK consisting of a real-time 3D avatar system, facial motion capture, and an Avatar Designer component built from scratch for web3 interoperability and the open metaverse.

Alter 45 Nov 29, 2022
RadioTimeKit - The Swift SDK for TuneIn RadioTimeKit is a Swift package to use the TuneIn API.

RadioTimeKit - The Swift SDK for TuneIn RadioTimeKit is a Swift package to use the TuneIn API. The goal for development was to have a Swift SDK to get

Frank Gregor 2 Jun 20, 2022
MpesaSDK - Swift SDK for the M-Pesa API (Mozambique)

M-Pesa SDK Swift package for M-Pesa API (Mozambique) Ready Methods/APIs C2B B2B

Algy Ali 16 Jul 29, 2022
Unofficial Notion API SDK for iOS & macOS

NotionSwift Unofficial Notion SDK for iOS & macOS. This is still work in progress version, the module interface might change. API Documentation This l

Wojciech Chojnacki 59 Jan 8, 2023
150,000+ stickers API & SDK for iOS Apps.

English | 한국어 Stipop UI SDK for iOS Stipop SDK provides over 150,000 .png and .gif stickers that can be easily integrated into mobile app chats, comme

Stipop, Inc. 19 Dec 20, 2022
iOS SDK for the Box Content API

Box iOS SDK Getting Started Docs: https://developer.box.com/guides/mobile/ios/quick-start/ NOTE: The Box iOS SDK in Objective-C (prior to v3.0.0) has

Box 112 Dec 19, 2022
iOS SDK for access the OpenCage Geocoding API

OpenCageSDK Requirements OpenCageSDK works on iOS 9+ and requires ARC to build. It depends on the following Apple frameworks, which should already be

OpenCage GmbH 1 Jun 30, 2020
Business-API - Business App an Application that show list business using the Yelp API

business-API Business App an Application that show list business using the Yelp

Edwin Niwarlangga 0 Jan 21, 2022
This is swift project example to connect VNPTSmartCA SDK using Swift Language.

Example source code to integrate with VNPTSmartCA iOS SDK To run the example project, clone repository, and run pod install Requirements Installation

null 1 Feb 14, 2022
Home-assistant-swift-sdk - Used to integrate the Home Assistant APIs with your Swift-based apps.

home-assistant-swift-sdk This open-source library allows you to interact with a Home Assistant instance in your Swift-based (e.g., iOS, macOS, etc.) a

Alexander Golden 0 Dec 31, 2021
Official Appwrite Swift SDK 🦅🍎

Appwrite Swift SDK This SDK is compatible with Appwrite server version 0.11.x. For older versions, please check previous releases. This is the Swift S

Appwrite 27 Dec 25, 2022
WalletConnect Swift SDK v2

Wallet Connect v.2 - Swift Swift implementation of WalletConnect v.2 protocol for native iOS applications. Requirements iOS 13 XCode 13 Swift 5 Usage

WalletConnect Labs 16 Mar 30, 2022
MbientLab 2 Feb 5, 2022
Federal Data SDK built in the Swift programming language. Follow the link for the documentation:

Swift-Federal-Data-SDK Federal Data SDK built in the Swift programming language Until the Swift language becomes more stable, consider this a beta rel

null 65 May 28, 2022
Swift SDK for Apache Kafka

SwiftKafka A swift implementation of Kafka for producing and consuming from event streams. This works by wrapping the librdkafka C library. Swift vers

Kitura 55 Dec 27, 2022
A simple to use iOS/tvOS/watchOS SDK to help get you off the ground quickly and efficiently with your Elastic Path Commerce Cloud written in Swift.

Elastic Path Commerce Cloud iOS Swift SDK A simple to use iOS/tvOS/watchOS SDK to help get you off the ground quickly and efficiently with your Elasti

Moltin 36 Aug 1, 2022
Sample project with local swift package linked NDI SDK.

NDISwiftPackage Sample project with local swift package linked NDI SDK. Preparation Install NDA SDK on your mac. Software Developer Kit Make package c

Naruki Chigira 4 Dec 20, 2022
Stacksift App SDK

Stacksift SDK Capture and submit crashes to Stacksift. This library ties together Wells and Impact to provide a full crash capturing and submission sy

Stacksift 44 Aug 18, 2022
TelegramStickersImport — Telegram stickers importing SDK for iOS

TelegramStickersImport — Telegram stickers importing SDK for iOS TelegramStickersImport helps your users import third-party programaticaly created sti

null 35 Oct 26, 2022