Tangocrypto
Search
K

Tangocrypto SDK

The easiest way to connect your dApp to Cardano and get the power of Tangocrypto's infrastructure. Just download, write a few lines of code, and go.

Getting started

This guide assumes you already have a Tangocrypto account and access to our Dashboard.

Create an App

To use Tangocrypto's products, you need an API key to authenticate your requests.
You can create API keys from the dashboard, just click on Create App, name it and click create a new app:
Create App
Once the app is created, it will generate an APP ID and an API Key. With those values, you can start consuming the API with the SDK.
App details

Install the SDK

Check out the full Github repo here:
Install the SDK:
npm i @tango-crypto/tangocrypto-js
After installing the app, you can then import and use the SDK:
import { Tangocrypto, Network } from '@tango-crypto/tangocrypto-js';
// or CommonJS
// const { Tangocrypto, Network } = require('@tango-crypto/tangocrypto-js');
const client = new Tangocrypto({
apiKey: process.env.API_KEY, // your account id
appId: process.env.APP_ID, // your app id
network: Network.CARDANO_MAINNET, // Network to determine the base URL, default to https://cardano-mainnet.tangocrypto.com
version: process.env.VERSION, // API version, default to v1
maxAttempts: 5 // maximmum retry attemps when request fails and is retryable (e.g. status 429)
})
The Tangocrypto object returned provides access to the Tangocrypto API. You can use the config object to set your API key, change the network, or specify the max number of retries.

Config Options

  • apiKey: Your account Id (required).
  • appId: Your app Id (required).
  • network: Network to determine the base URL, default to https://cardano-mainnet.tangocrypto.com.To use the testnet set the network parameter to Network.CARDANO_TESTNET.
  • version: String for API version, default to v1.
  • maxAttempts: Number indicating the maximmum retry attemps when request fails and is retryable (e.g. status 429).

API Response

All API instances methods return an instance of ApiResponse<T> definde this way:
export interface ApiResponse<T> {
result: T;
$metadata: Metadata;
}
Where T corresponding to the data specific for each endpoint. More info about each endpoint request/response here. The field $metadata contains the attemps and totalRetryDelay were needed in order to perform the request. If the request was success in the first call $metadata will look like this:
{ attempts: 1, totalRetryDelay: 0 }

Error Handling

The errors throws by this sdk are instances of TangocryptoError with the same structure you get from the API.
{
"status_code": 404,
"message": "epoch: 63 not found",
"error": "Not Found"
}
Check here for all possible status_code and meaning.
TancryptoError extends built-in Error class, so you can catch it in your code and perform custom logic.
import { Tangocrypto, Network } from '@tango-crypto/tangocrypto-js';
const tangocrypto = new Tangocrypto({
apiKey: process.env.API_KEY,
appId: process.env.APP_ID,
network: Network.CARDANO_TESTNET,
version: process.env.VERSION
}).block()
// missing block number
const block = -1;
try {
const response = await tangocrypto.getBlock(block);
} catch (err) {
if (err instanceof TangocryptoError) {
// missing block number
console.log(err.toString()); // TangocryptoError: {"status_code":404,"message":"block number: -1 not found","error":"Not Found"}
} else {
// other errors
throw err;
}
}

Using the Tangocrypto SDK

The Tangocrypto SDK currently supports the following modules:
  • Addresses: Address methods
  • Assets: Assets methods
  • Blocks: Block methods
  • Epochs: Epoch methods.
  • Policies: Policy methods.
  • Pools: Pool methods.
  • Transactions: Transaction methods.
  • Wallets: Get access to a set of endpoints cardano stake address related.
  • Webhooks: Webhook methods.
  • Nfts: NFT methods.

Address

It also includes the majority of Tangocrypto APIs, including:
  • getAddressSummary(): Retrieves summarized information of an address.
  • listAddressAssets(): Returns a list of assets for a given address.
  • listAddressTransactions(): Returns a list of transactions for a given address.
  • listAddressUtxos(): Returns a list of UTXOs for a given address.

Assets

It also includes the majority of Tangocrypto APIs, including:
  • getAsset(): Retrieves information about an asset
  • getAssetByFingerprint(): Retrieves information about an asset
  • listAssetAddresses(): Returns a list of addresses and quantities for a given asset.
  • listAssetAddressesByFingerprint(): Returns a list of addresses and quantities holding the given asset.

Blocks:

  • getBlock(): Retrieves information about a block specified by block_no.
  • getBlockByHash(): Retrieves information about a block specified by hash.
  • listBlockTransactions(): Returns a list of transactions for a given block.
  • listBlockTransactionsByHash(hash): Returns a list of transactions for a given block.
  • getLatestBlock(): Retrieves the latest block available.

Epochs

  • getCurrentEpoch(): Retrieves the current epoch information
  • getEpochParameters(): Retrieves the protocol parameters for a given epoch.

Policies

  • getAssetsByPolicy(): Returns a list of assets with the given Policy ID.

Pools

  • listPoolDelegations(): Returns a list of delegations for a given stake pool.
  • getPoolMetadata(): Retrieve stake pool registration metadata specified by a pool_id.

Transactions

  • getTransaction(): Retrieves the information about a transaction requested specified by a transaction hash.
  • getTransactionMetadata(): Retrieve the transaction metadata specified by a transaction hash.
  • listTransactionUtxos(): List the UTXOs from a transaction specified by a transaction hash.
  • submitTransaction(): Submit an already serialized transaction to the network.
  • buildTransaction(): Build and serialize transaction with custom logic like swap, send, mint, burn etc.
  • signTransaction(): Sign transaction off-chain.

Wallets

  • getWalletSummary(): Retrieve wallet summary specified by stake_address.
  • listWalletAddresses(): Returns a list of addreses for a given wallet stake_address.

Webhooks

  • createWebhook(): Create Webhook
  • deleteWebhook(): Deletes a single Webhook based on the provided ID.
  • listWebhooks(): Returns a list of webhooks created in your Tangocrypto account.
  • getWebhook(): Get details for a single Webhook in your Tangocrypto account.
  • updateWebhook(): Updates the webbook without having to perform an upsert on the entire item. Just include include the fields you want to be updated in the request body.

NFTs

Collection
  • createCollection(): Create a new collection in your Tangocrypto account.
  • getCollection(): Get details for a single collection in your Tangocrypto account.
  • deleteCollection(): Delete an collection in your Tangocrypto account.
  • listNfts(): Returns a list of NFTs for a given collection.
  • listCollections(): Returns a list of collections in your Tangocrypto account.
  • updateCollection(): Updates the collection with the fields that were supplied, leaving the others alone.
Tokens
  • createNft(): Create NFT in a Collection
  • deleteNft(): Delete an NFT in your Tangocrypto account.
  • getNFT(): Returns details for a single NFT.
  • updateNFT(): Updates the NFT with the supplied parameters. The ones not provided remain with the same value.
Sale
  • createSale(): Create an sale. You can sell multiple tokens in a single sale.
  • cancelSale(): Cancel a sale for a given NFT. When you cancel a sale the status of the NFT will return back to FOR_SALE.
  • listSales(): Returns a list of Sales for a given collection.
  • getSale(): Returns details for a single sale. With this endpoint, you can check the remaining reservation time or if the sale is expired. Also, you can check if a customer has made a partial payment or if the total amount was paid. Once the payment is received, the NFT is minted and sent to the buyer's wallet address.
Sale phase
  • createSalePhase(): Create a sale phase for a given collection. You can add different phases to control how you will sell the collection. For example, you might have a total of 5000 NFTs, and you want to sell them in stages. You can create a pre-sale phase to sell 1000 NFTs to previous customers at a special price and within a specific time range. You can identify these customers with a condition; that would be an NFT with a certain policy id on their wallets. Then you create another sale phase for the public drop with the remaining 4000 NFTs and no conditions.
  • getSalePhase(): Returns details for a single sale phase.
  • listSalePhases(): Returns a list of sale phases for a given collection. The response is paginated. If truncated, the response includes a cursor that you use in a subsequent request to retrieve the next set of sale phases.
  • updateSalePhase(): Update sale phase
  • deleteAffiliate(): Delete affiliate.
  • createAffiliate(): Create affiliate.
  • updateAffiliate(): Update affiliate

Example

import { Tangocrypto, Network } from '@tango-crypto/tangocrypto-js';
const tangocrypto = new Tangocrypto({
apiKey: "<api-key>", // your api key
appId: "<app-id>" // your app id
}
async function getLatestBlock() {
const api = tangocrypto.block(); // get block API client instance
const block = await api.getLatestBlock();
console.log(block);
}
getLatestBlock();
Output
{
"hash": "7135250e403466c2163c6ba3aa8606f4dd6396e282c512486740aeaa220fbaf9",
"epoch_no": 229,
"slot_no": 68672434,
"epoch_slot_no": 114034,
"block_no": 3832866,
"previous_block": 3832865,
"slot_leader": "pool1l8kt8vn966ylkgysaj28ut34qu8z7nrjxyjj3n77v9ae6clyjfp",
"confirmations": 1,
"size": 4,
"time": "2022-09-13T04:00:50.000Z",
"tx_count": 0,
"vrf_key": "vrf_vk1cxcf73rmj7luakn0ykjtvsf3mzqj5akhh3j82hamch4srlvx37tsy2gg35",
"op_cert": "48a680a489fbf4d0035afec3596e42eb05c2d2d3ebfa4ca5f6210ddb74d7facc"
}

Minting a token

Mint a token
import { BuildTxRequest } from "../../src/api";
import { Tangocrypto, Network } from "../../src/clients";
import * as dotenv from "dotenv";
dotenv.config();
async function mint() {
const client = new Tangocrypto({
apiKey: process.env.API_KEY!,
appId: process.env.APP_ID!,
network: Network.CARDANO_TESTNET_STAGING,
version: process.env.VERSION
});
const txClient = client.transaction();
const addrClient = client.address();
// get address utxos (take into account any pagination here)
const inputs = (await addrClient.listAddressUtxos('addr_test1qpemm54tmynjhuyw0qhzdpnras29c3pc8gxvc4afpsa3uwglmrag6mlare663x64ugkkv8nqhqg3z6u78xa49fq6wmts55h5y9')).result.data;
// build tx
const request: BuildTxRequest = {
"inputs": inputs.map(i => ({ address: i.address, hash: i.hash, value: i.value, asset: i.assets })), // use address inputs here as spending utxos
"recipients": {
"addr_test1qzy4e509u7jtztnn0p3v6rypup5w48t63pgkhtsup6anumqrejvpmpdfe7zt662gdx98f3d5a0phjrh6hvxyjhecpe3q422hpz": [
{
"policy_id": "18ed282beda4bec13226c427d4744d2642ba2cef404470b62ae184d8",
"asset_name": "BuildTxTest#001",
"quantity": 1,
"metadata": {
"721": {
"cdf7a949cca0d57a27f862d525e4d4c734c1d503cbc7f04c1ac2350e": {
"BuildTxTest#001": {
"name": "BuildTxTest #001",
"image": "ipfs://QmbFhLR5C6BmTW7apgDMVmGozLuEUZwoezcgHQeULT59M5",
"description": "Little BuildTxTest description"
}
}
}
}
}
]
},
"minting_script": {
"type": "all",
"scripts": [
{
"type": "sig",
"keyHash": "1aabe8cdb1153e11c3363270fd11baef2ca758e56d9a0866e73f7dc5"
},
{
"type": "before",
"slot": 196536677
}
]
},
"change_address": "addr_test1qpemm54tmynjhuyw0qhzdpnras29c3pc8gxvc4afpsa3uwglmrag6mlare663x64ugkkv8nqhqg3z6u78xa49fq6wmts55h5y9"
}
const response = await txClient.buildTransaction(request);
const buildTx = response.result;
// sign tx
const keys = [
'xprv1gpn7d2h38j5ukpvmuz4mmrlgaprx6pcp53987ff8lkuqk2ztd4p2fdfpap4ev98hg3uj8kd36wzva3av8r776ke50dhhkm2ktpca83tj46xlscy6d7qga23ql4nn7z2hl9a4r3gqgpt6n7glv57nwkf80ypl5j63', // your spending/input keys
'xprv1zpetq5ux75u7gsryanjp7f4l39znck0x45myxrkwqh2qr8cxne9ndrt2g28kaqgc3s0er09haaxflwzljcgytmhklswtas42kd0ajsvz404dkvjje5j6wh3envwd25w728vzwzv46mlf9nzz0683ncju9y04jv8j' // minting script keys
];
const signed = await txClient.signTransaction({ keys, tx: buildTx.tx });
// submit tx
const txId = (await txClient.submitTransaction({ tx: signed })).result.tx_id;
return txId;
}
mint().then(txId => console.log('Tx id:', txId));