Skip to main content

Contracts and NFTs

This page covers the ABI-driven API in @amadeus-protocol/sdk 1.8.0 and the built-in Lockup, LockupPrime and Nft contracts. For how transactions are built, signed and submitted in general, start with Transaction Building.

Where each contract runs​

Built-in contracts are addressed by name. The node (1.6.5) does not enable all of them on both networks:

ContractFunctionsMainnetTestnetIn the SDK
Cointransferyesyesbuilder.transfer, buildCoinTransfer
LockupVaultcreate, unlock, set_validator, ...yes, but create fails with vault_creation_disabledyesread-only, through sdk.staking (Staking)
Lockuplock, unlocknoyesLOCKUP_ABI and lockupUnlock (unlock only)
LockupPrimelock, unlock, daily_checkinnoyesLOCKUP_PRIME_ABI, lockupPrime*
Nfttransfer, create_collection, mint, update_permissionnoyesNFT_ABI, buildNft*, nft*

A mainnet call to a testnet-only contract is still included in a block, but its receipt has success: false and result: 'invalid_bic_action'. Recent mainnet LockupPrime.lock, Nft.create_collection and Nft.mint transactions all failed this way.

So sign calls to these contracts for testnet. new TransactionBuilder(privateKey, { network: NetworkType.TESTNET }), createContract(abi).connect(privateKey, NetworkType.TESTNET) and signContractCall(privateKey, call, NetworkType.TESTNET) all do this; without a network they sign for mainnet. See Networks and testnet for testnet endpoints and the faucet.

Contract ABIs​

The SDK ships as const ABI objects for three built-in contracts:

ExportcontractNameFunctions
LOCKUP_ABILockupunlock(vaultIndex)
LOCKUP_PRIME_ABILockupPrimelock(amount, tier), unlock(vaultIndex), daily_checkin(vaultIndex)
NFT_ABINfttransfer(receiver, amount, collection, token), create_collection(collection, soulbound), mint(receiver, amount, collection, token) (see the note below on create_collection and mint)

Each ABI is an AbiDefinition with contractName, contractVersion, an abi array of functions (name, inputs, description, requirements), plus storage and errors. Type helpers read names and params from an ABI at compile time:

import { LOCKUP_PRIME_ABI, NFT_ABI, type ExtractFunctionNames, type FunctionParams } from '@amadeus-protocol/sdk'

console.log(LOCKUP_PRIME_ABI.contractName) // 'LockupPrime'
console.log(NFT_ABI.abi.map((entry) => entry.name)) // ['transfer', 'create_collection', 'mint']

type LockupPrimeFunction = ExtractFunctionNames<typeof LOCKUP_PRIME_ABI> // 'lock' | 'unlock' | 'daily_checkin'
type LockParams = FunctionParams<typeof LOCKUP_PRIME_ABI, 'lock'> // { amount: string; tier: string }

Calls from an ABI​

createContract(abi) turns every ABI function into a method that returns a ContractCall ({ contract, method, args }). buildContractCall(abi, name, params) does the same for one function:

import { LOCKUP_PRIME_ABI, buildContractCall, createContract } from '@amadeus-protocol/sdk'

const lockupPrime = createContract(LOCKUP_PRIME_ABI)
const checkin = lockupPrime.daily_checkin({ vaultIndex: '7' })
// { contract: 'LockupPrime', method: 'daily_checkin', args: ['7'] }

// Same result without the factory
const sameCheckin = buildContractCall(LOCKUP_PRIME_ABI, 'daily_checkin', { vaultIndex: '7' })

try {
lockupPrime.lock({ amount: '5000000000', tier: '14d' })
} catch (error) {
console.error((error as Error).message)
// Invalid value "14d" for parameter "tier". Expected one of: 7d, 30d, 90d, 180d, 365d
}

Before it builds the call, the SDK throws on an unknown function, a missing param, or a value outside an input's enum. It does not check types or ranges. That is left to the contract when it runs.

Every param is a string and goes to the contract unchanged, in the order of the ABI's inputs. This fits Lockup and LockupPrime, whose arguments are all text. It does not fit inputs that must be raw bytes: createContract(NFT_ABI).transfer({ receiver }) sends the Base58 text of the address, and the node rejects it with invalid_receiver_pk. create_collection and mint from NFT_ABI send separate arguments, but the node takes one map argument for those two and rejects them with invalid_args. Use the NFT builders instead: buildNftTransfer decodes the address to 48 bytes, and since 1.8.0 buildNftCreateCollection and buildNftMint send the map (see NFTs).

To sign a call for testnet and submit it:

import {
AmadeusSDK,
LOCKUP_PRIME_ABI,
NetworkType,
createContract,
signContractCall,
toAtomicAma
} from '@amadeus-protocol/sdk'

const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })

const call = createContract(LOCKUP_PRIME_ABI).lock({
amount: toAtomicAma(100).toString(), // atomic units, as a string
tier: '30d'
})
const { txPacked } = signContractCall(privateKey, call, NetworkType.TESTNET)

const { receipt } = await testnet.transaction.submitAndWait(txPacked)
console.log(receipt.success, receipt.result)

Signer-bound versions build and sign in one step and return { txHash, txPacked }: createContract(abi).connect(privateKey, network?).fn(params) signs for network (mainnet by default), and new TransactionBuilder(privateKey, { network }).contract(abi).fn(params) for the builder's network.

Lockup and LockupPrime​

LockupPrime locks AMA for a tier and pays PRIME points when you unlock. Its arguments, checked against the node source:

  • lock(amount, tier): amount is in atomic units and must be more than 1 AMA (lockup_amount_insufficient). tier is one of 7d, 30d, 90d, 180d or 365d (invalid_tier).
  • unlock(vaultIndex): on or after the vault's unlock epoch, returns the AMA and mints amount × multiplier PRIME. Before that, 25% of the amount goes to the treasury and the other 75% is locked in a Lockup vault for 5 epochs.
  • daily_checkin(vaultIndex): the node ignores vaultIndex and uses all your LockupPrime vaults. Your first check-in counts. A check-in that counts mints 1% of their total locked amount as PRIME, and the next window opens 2 epochs later. Checking in during the epoch the window opens, or the one after, keeps your streak, and every 30th check-in in the streak mints 30 times the daily amount on top. Checking in 3 or more epochs after the window opens still pays but resets the streak to 1. A check-in before the window opens, or exactly 2 epochs after it opens, succeeds but does nothing. If you have no vault, the call fails with no_vaults_found.

Lockup.unlock(vaultIndex) releases a Lockup vault once its unlock height is reached (vault_is_locked before then).

Tier lengths depend on the network. LockupPrime.getAvailableTiers(network) returns them:

import { LockupPrime, NetworkType } from '@amadeus-protocol/sdk'

const tiers = LockupPrime.getAvailableTiers(NetworkType.TESTNET)
console.log(tiers.map((tier) => [tier.tier, tier.epochs, tier.multiplier]))
// [['7d', 1, 13], ['30d', 3, 17], ['90d', 9, 27], ['180d', 18, 35], ['365d', 36, 54]]
TierMultiplierMainnet epochsTestnet epochs
7d13101
30d17453
90d271359
180d3527018
365d5454736

TransactionBuilder also has shortcuts. They sign for the builder's network, so create it for testnet, where these contracts run (see Where each contract runs):

import { NetworkType, TransactionBuilder } from '@amadeus-protocol/sdk'

const builder = new TransactionBuilder(privateKey, { network: NetworkType.TESTNET })

const locked = builder.lockupPrimeLock({ amount: 100, tier: '30d' }) // AMA, converted for you
const unlocked = builder.lockupPrimeUnlock({ vaultIndex: 3 })
const checkedIn = builder.lockupPrimeDailyCheckin({ vaultIndex: 3 })
const released = builder.lockupUnlock({ vaultIndex: 5 })

const staticLocked = TransactionBuilder.buildSignedLockupPrimeLock(
{ senderPrivkey: privateKey, amount: 100, tier: '30d' },
NetworkType.TESTNET
)

lockupPrimeLock takes amount in AMA and converts it. ABI calls take atomic units. The static versions are buildSignedLockupPrimeLock, buildSignedLockupPrimeUnlock, buildSignedLockupPrimeDailyCheckin and buildSignedLockupUnlock. Each takes the same input plus senderPrivkey, and an optional network as its last argument.

Staking uses a different contract, LockupVault. See Staking.

NFTs​

The built-in Nft contract holds collections of tokens. A collection is created by one account and identified by its name. Each token id in it can have any supply.

  • Names: collection names and token ids are 1 to 32 ASCII letters or digits. Collection names that start with AMA or W (in any letter case), names on the node's reserved list and names already used by a coin are refused.
  • Amounts: whole token counts as strings ('1', '10'), not atomic units. The SDK helpers accept a positive integer number, a bigint or a string, and throw invalid_amount: 1.5 for a fractional number.
  • Minting: only accounts on the collection's permission list can mint. The creator is on it from the start, and Nft.update_permission changes it. The SDK has no helper for update_permission.
  • Soulbound: a soulbound collection, or a soulbound token minted with soulbound: true, cannot be transferred (soulbound). Holders can still send it to the burn address (48 zero bytes), which lowers its supply. A token's soulbound flag is fixed at its first mint (token_soulbound_immutable).
  • Non-fungible collections: created with nonfungible: true, each token id can be minted once, with amount 1.
  • Balances are stored under the contract-state key account:{pk}:nft:{collection}:{token}, with pk as raw bytes, as an integer string. See Contract state for reading keys.

Transfer​

buildNftTransfer matches the node's transfer(receiver, amount, collection, token):

import { AmadeusSDK, NetworkType, buildNftTransfer, signContractCall } from '@amadeus-protocol/sdk'

const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })

// Returns a ContractCall; the amount is a whole token count
const transferCall = buildNftTransfer({ recipient: recipientAddress, amount: 1, collection: 'AGENTIC', token: '1' })

const { txPacked } = signContractCall(privateKey, transferCall, NetworkType.TESTNET)
const { receipt } = await testnet.transaction.submitAndWait(txPacked)
console.log(receipt.success, receipt.result)

Create a collection and mint​

The node's create_collection and mint take one argument: a VecPak map with every field as a string or raw bytes. Since 1.8.0, buildNftCreateCollection and buildNftMint build that map for you. (In 1.7.0 and earlier they sent separate arguments, which the node rejected with invalid_args.)

BuilderParamsMap it sends
buildNftCreateCollectioncollection, optional soulbound and nonfungible (booleans, default false){ collection, soulbound, nonfungible }
buildNftMintrecipient (Base58), amount, collection, token, optional soulbound (default false){ receiver, amount, collection, token, soulbound }

The builders turn recipient into the 48 raw key bytes, amount into an integer string and the flags into 'true' or 'false'.

import { AmadeusSDK, NetworkType, TransactionBuilder } from '@amadeus-protocol/sdk'

const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })
const builder = new TransactionBuilder(privateKey, { network: NetworkType.TESTNET })

const created = builder.nftCreateCollection({ collection: 'AGENTIC', nonfungible: false })
const createResult = await testnet.transaction.submitAndWait(created.txPacked)
console.log('create_collection:', createResult.receipt.success, createResult.receipt.result)

// Sign the mint only after the create returns, so the two nonces differ
const minted = builder.nftMint({ recipient: recipientAddress, amount: 10, collection: 'AGENTIC', token: '1' })
const mintResult = await testnet.transaction.submitAndWait(minted.txPacked)
console.log('mint:', mintResult.receipt.success, mintResult.receipt.result)

To sign the calls elsewhere, build them with buildNftCreateCollection(params) and buildNftMint(params) and sign them with signContractCall(privateKey, call, NetworkType.TESTNET).

If you build the map yourself with encode, it must have exactly these keys. A missing or duplicate key gives invalid_args, and an extra key gives unknown_arg. Every value must be a string or raw bytes: a boolean false gives invalid_args. Flags must be the strings 'true' or 'false', and any other string gives invalid_soulbound or invalid_nonfungible.

Builder methods​

TransactionBuilder has NFT methods with the same params as the helpers. They sign for the builder's network, so create it for testnet. Each call signs with a fresh clock nonce, so submit one and wait for it before you sign the next (see Nonces):

import { AmadeusSDK, NetworkType, TransactionBuilder, derivePublicKeyFromSeedBase58 } from '@amadeus-protocol/sdk'

const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })
const builder = new TransactionBuilder(privateKey, { network: NetworkType.TESTNET })
const senderAddress = derivePublicKeyFromSeedBase58(privateKey)

const created = builder.nftCreateCollection({ collection: 'BADGES' })
const createResult = await testnet.transaction.submitAndWait(created.txPacked)
console.log('create_collection:', createResult.receipt.success, createResult.receipt.result)

// Mint to yourself: a transfer moves tokens the signer holds
const minted = builder.nftMint({ recipient: senderAddress, amount: 2, collection: 'BADGES', token: '1' })
const mintResult = await testnet.transaction.submitAndWait(minted.txPacked)
console.log('mint:', mintResult.receipt.success, mintResult.receipt.result)

const sent = builder.nftTransfer({ recipient: recipientAddress, amount: 1, collection: 'BADGES', token: '1' })
const transferResult = await testnet.transaction.submitAndWait(sent.txPacked)
console.log('transfer:', transferResult.receipt.success, transferResult.receipt.result)

The static versions are buildSignedNftTransfer, buildSignedNftMint and buildSignedNftCreateCollection. Each takes the same params plus senderPrivkey, and an optional network as its last argument:

const staticSent = TransactionBuilder.buildSignedNftTransfer(
{ senderPrivkey: privateKey, recipient: recipientAddress, amount: 1, collection: 'BADGES', token: '1' },
NetworkType.TESTNET
)

NFT error codes​

These codes appear in receipt.result when an Nft call fails (from the node's nft.rs):

CodeFunctionMeaning
invalid_bic_actionanyNft is not enabled on this network (mainnet)
invalid_argsanyWrong number or shape of arguments
unknown_argcreate_collection, mintThe map has a key the function does not take
invalid_amounttransfer, mintAmount is not an integer, or is 0 or less
invalid_receiver_pktransfer, mintReceiver is not a valid 48-byte public key (or the burn address, for transfers)
collection_doesnt_existtransfer, mintNo collection with that name
token_doesnt_existtransferToken id was never minted in that collection
insufficient_tokenstransferSender holds fewer than amount
soulboundtransferCollection or token is soulbound (burning is still allowed)
invalid_collection, collection_too_short, collection_too_longcreate_collection, mintName is not 1 to 32 ASCII letters or digits
invalid_token, token_too_short, token_too_longmintToken id is not 1 to 32 ASCII letters or digits
collection_reservedcreate_collectionName is reserved
collection_conflicts_with_coincreate_collectionA coin already uses that name
collection_existscreate_collectionCollection already exists
invalid_soulbound, invalid_nonfungiblecreate_collection, mintFlag is not 'true' or 'false'
no_permissionsmintCaller is not on the collection's permission list
nonfungible_amount_must_be_onemintNon-fungible collections mint 1 at a time
nonfungible_token_already_mintedmintThat non-fungible token id already exists
token_soulbound_immutablemintsoulbound differs from the token's first mint

getExecutionErrorMessage(code) has readable text for the codes in the SDK's TransactionExecutionError enum (soulbound, insufficient_tokens, invalid_collection, collection_exists, collection_doesnt_exist and others). For the rest it returns Transaction execution failed: <code>:

import { TransactionExecutionError, getExecutionErrorMessage } from '@amadeus-protocol/sdk'

console.log(getExecutionErrorMessage(TransactionExecutionError.SOULBOUND))
// 'Token is soulbound and cannot be transferred'
console.log(getExecutionErrorMessage('token_doesnt_exist'))
// 'Transaction execution failed: token_doesnt_exist'

Next steps​