Swiftpack.co - blockfrost/blockfrost-swift as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
blockfrost/blockfrost-swift
Swift SDK for Blockfrost.io API
.package(url: "https://github.com/blockfrost/blockfrost-swift.git", from: "0.0.5")

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

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<R, Error>, 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+.

GitHub

link
Stars: 7
Last commit: 1 week ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Submit a free job ad (while I'm testing this). The analytics numbers for this website are here.

Release Notes

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics