Skip to main content

Staking

Read LockupVault staking positions with @amadeus-protocol/sdk 1.8.0: vaults, totals, APY, commissions and the helpers behind them.

Staking on Amadeus is the LockupVault contract. An account locks AMA in a vault for a tier's duration and backs a validator with it. The vault earns the APY fixed at creation, but only in epochs where its validator is in the validator set. sdk.staking reads these vaults and rolls them up into one position. Samples assume the sdk instance from API Modules.

sdk.staking only reads. TransactionBuilder in SDK 1.8.0 has no LockupVault helper methods.

LockupVault, Lockup and LockupPrime​

Three contracts lock AMA. Only LockupVault is staking, and sdk.staking reads only LockupVault.

ContractState prefixWhat it isSDK
LockupVaultbic:lockup_vault:Staking: locked AMA that earns APY and can back a validator.sdk.staking, buildOwnerVaultsKeyPrefix and the helpers on this page
Lockupbic:lockup:Vesting lockup.LOCKUP_ABI, buildLockupVaultKeyPrefix
LockupPrimebic:lockup_prime:Points-based locking.LOCKUP_PRIME_ABI, buildLockupPrimeVaultKeyPrefix

In node 1.6.5, the node accepts Lockup and LockupPrime calls on testnet only. On mainnet they fail with invalid_bic_action.

warning

buildLockupVaultKeyPrefix belongs to the Lockup (vesting) module and builds bic:lockup:vault:{account}:. It does not find staking vaults. For staking, use buildOwnerVaultsKeyPrefix.

Vault rules​

These values come from the node's lockup_vault.rs and are exported by the SDK.

RuleValue
Minimum vault1,000 AMA (MIN_VAULT_AMOUNT_FLAT)
Tier og0% APY, no lock by default. The creator may request a lock of up to 1,200 months (MAX_LOCK_MONTHS).
Tier 3m5% APY, locked 156 epochs (3 × 30 days)
Tier 6m10% APY, locked 312 epochs (6 × 30 days)
Tier 12m15% APY, locked 623 epochs (12 × 30 days), plus 5% for vaults created before epoch 1150 (BONUS_RATE_BPS, BONUS_END_EPOCH)
Unlock period21 days (37 epochs, UNLOCK_PERIOD_EPOCHS) after unlock is called on a matured vault
Validator changeTakes effect 2 epochs later (VALIDATOR_CHANGE_QUEUE_EPOCHS)
Commission raiseTakes effect 3 epochs later (COMMISSION_RAISE_QUEUE_EPOCHS). Cuts apply at once.
Validator stake thresholdA validator backed by at least 1,000,000 AMA of vault stake joins the next epoch's validator set (VALIDATOR_MIN_STAKE_FLAT)

Each epoch, a vault whose validator is in the validator set earns yield. It compounds into the vault, unless the vault has a payout address, in which case it is paid there. A vault with no validator, or whose validator is not in the set, earns nothing that epoch.

note

In node 1.6.5, creating a vault is enabled on testnet only. On mainnet, LockupVault.create fails with vault_creation_disabled. Reading vaults works on both networks. For testnet setup, see Networks and testnet.

Read a position​

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

const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const currentEpoch = await sdk.staking.getCurrentEpoch()

const position = await sdk.staking.getPosition('5Kd3N...', { currentEpoch })

console.log(`Staked: ${position.totalStaked} AMA in ${position.vaultCount} vaults`)
console.log(`Accrued: ${position.totalAccrued} AMA, APY ${position.weightedApyPercent}%`)
console.log('Next maturity epoch:', position.nextMatureEpoch ?? 'none')

for (const vault of position.vaults) {
const state = vault.isUnlocking
? `unlocking, ${vault.epochsUntilRelease} epochs to release`
: vault.isMatured
? 'matured, unlock available'
: `locked, ${vault.epochsUntilMature} epochs to maturity`
console.log(`#${vault.index} ${vault.tier} ${flatToAma(vault.totalFlat)} AMA, ${state}`)
}

totalStaked is the figure to show as "staked": principal plus the yield already compounded into the vaults. Matured and unlocking vaults still count, because they keep backing their validator and earning until their funds are released.

sdk.staking methods​

MethodReturnsDescription
getPosition(publicKey, options?)Promise<StakingPosition>The account's vaults plus their totals.
getVaults(publicKey, options?)Promise<LockupVaultEntry[]>The account's vaults, ordered by index.
getAllVaults(options?)Promise<LockupVaultEntry[]>Every vault on the chain. Reads far more than getVaults.
getValidatorCommissions(options?)Promise<Record<string, ValidatorCommission>>Every validator's commission, keyed by Base58 public key.
getCurrentEpoch()Promise<number>epochFromHeight(stats.height) from chain.getStats().

publicKey is a Base58 string or the 48 raw bytes. options is { currentEpoch?: number }. Without it, each call fetches the tip first. Fetch the epoch once and pass it to every call so they all resolve against the same epoch and skip that request.

The vault reads use contract.getPrefixEntries, so they follow every page of the answer. A vault record that does not decode is skipped, not thrown.

StakingPosition and StakingSummary​

getPosition returns a StakingPosition: every StakingSummary field plus vaults (LockupVaultEntry[]) and epoch (the epoch used).

FieldTypeDescription
totalStakedFlat, totalStakedbigint, numberSum of principal plus accrued across vaults.
totalPrincipalFlat, totalPrincipalbigint, numberSum of principal.
totalAccruedFlat, totalAccruedbigint, numberYield compounded into the vaults so far.
vaultCountnumberNumber of vaults.
lockedCountnumberVaults not yet matured.
maturedCountnumberVaults matured but not unlocking.
unlockingCountnumberVaults where unlock was called, including releasable ones.
releasableCountnumberVaults whose unlock window has ended.
weightedApyBps, weightedApyPercentnumberStake-weighted APY, in basis points and percent. 0 when nothing is staked.
epochYieldFlatbigintEstimated yield per epoch across vaults.
annualYieldFlat, annualYieldbigint, numberEstimated yield per year.
nextMatureEpochnumber | nullEarliest maturity among locked vaults.
stakeByValidatorRecord<string, bigint>Staked amount per backing validator (Base58 key, atomic units).

Yield figures are gross estimates. The amount credited can be lower: validators take their commission, from epoch 1150 low solver participation scales vault yield down, and when the epoch's budget cannot cover every vault it is shared pro rata. A vault earns nothing in an epoch where its validator is not in the validator set.

LockupVaultEntry​

FieldTypeDescription
indexnumberVault index, unique across the chain.
ownerstring | nullOwner's Base58 public key. Set by getAllVaults, and by getVaults/getPosition when you pass a Base58 key.
tierstring'og', '3m', '6m' or '12m'. Unknown tiers are kept as stored.
principalFlat, accruedFlat, totalFlatbigintPrincipal, compounded yield, and their sum.
rateBpsnumberAPY in basis points, fixed at creation.
createdEpoch, matureEpochnumberCreation epoch, and the epoch from which unlock can be called.
lockEpochs, lockMonthsnumberLock length in epochs, and rounded to 30-day months.
payoutAddressstring | nullWhere yield is paid. null means it compounds.
compoundsbooleantrue when there is no payout address.
validatorstring | nullValidator the vault backs at the reference epoch.
pendingValidator, pendingValidatorEpochstring | null, number | nullA queued validator change and the epoch it takes effect.
unlockStartEpoch, unlockAtEpochnumber | nullWhen unlock was called, and when the funds are released.
isMaturedbooleanThe lock has expired.
isUnlockingbooleanunlock was called.
isReleasablebooleanThe unlock window has ended; the chain releases the funds.
epochsUntilMaturenumber0 once matured.
epochsUntilReleasenumber | nullnull when not unlocking.
epochYieldFlatbigintEstimated yield per epoch at rateBps.

Every field that depends on the epoch (validator, isMatured and the rest) is computed against the currentEpoch you pass, or the tip epoch.

ValidatorCommission​

FieldTypeDescription
validatorstringValidator's Base58 public key.
bpsnumberCommission in effect at the reference epoch, in basis points.
pendingBps, pendingEpochnumber | nullA queued raise and the epoch it applies.

Commission is taken from the yield of the vaults backing the validator.

const commissions = await sdk.staking.getValidatorCommissions()
const position = await sdk.staking.getPosition('5Kd3N...')

for (const [validator, stakeFlat] of Object.entries(position.stakeByValidator)) {
const commission = commissions[validator]
console.log(validator, stakeFlat, commission ? `${commission.bps / 100}%` : 'no record')
}

chain.getStats() also reports commission per validator in stats.validators[publicKey].commission_bps, and the chain-wide staked total in stats.total_locked.

Amounts are bigint​

Every *Flat field is a bigint in atomic units (1 AMA = 1,000,000,000). Real positions exceed 2^53 atomic units, the largest integer a JavaScript number holds exactly, so Number(flat) / 1e9 gives wrong digits above about 9 million AMA.

Convert with flatToAma, which splits the whole and fractional parts before converting, or use the number fields (totalStaked, totalPrincipal, totalAccrued, annualYield) that summarizeLockupVaults computes with it.

import { flatToAma } from '@amadeus-protocol/sdk'

flatToAma(1_500_000_000n) // 1.5
flatToAma(12_345_678_901_234_567_891n) // 12345678901.234568

Keep bigint for sums and comparisons, and convert only to display. JSON.stringify throws on bigint, so convert before you serialize a position.

Epoch helpers and constants​

ExportValue or signature
EPOCH_INTERVAL100_000 blocks per epoch
BLOCKS_PER_DAY172_800 (one block every 500 ms)
EPOCHS_PER_DAY1.728
EPOCHS_PER_YEAR630.72
DAYS_PER_MONTH30
epochFromHeight(height)Math.floor(height / EPOCH_INTERVAL)
daysToEpochs(days)Days to epochs, rounded up like the node
monthsToEpochs(months)30-day months to epochs
epochsToDays(epochs)Approximate days in a span of epochs
UNLOCK_PERIOD_EPOCHS37 (21 days)
MIN_VAULT_AMOUNT_FLAT1_000_000_000_000n (1,000 AMA)
VALIDATOR_MIN_STAKE_FLAT1_000_000_000_000_000n (1,000,000 AMA)
MAX_LOCK_MONTHS1200
BONUS_RATE_BPS, BONUS_END_EPOCH500, 1150
VALIDATOR_CHANGE_QUEUE_EPOCHS, COMMISSION_RAISE_QUEUE_EPOCHS2, 3
APY_EPOCH_DENOM6_307_200n (10,000 bps × 630.72 epochs)
BPS_DENOM10_000
LOCKUP_VAULT_CONTRACT'LockupVault'
LOCKUP_VAULT_KEY_PREFIX'bic:lockup_vault:vault:'
LOCKUP_VAULT_COMMISSION_KEY_PREFIX'bic:lockup_vault:validator_commission:'
LOCKUP_VAULT_TIERS, isLockupVaultTier(value)['og', '3m', '6m', '12m'] and its type guard
import { epochFromHeight, epochsToDays, monthsToEpochs } from '@amadeus-protocol/sdk'

const { stats } = await sdk.chain.getStats()
const epoch = epochFromHeight(stats.height)

monthsToEpochs(3) // 156
epochsToDays(37) // about 21.4

Reading vaults without sdk.staking​

If you run your own HTTP layer, the same steps are exported. sdk.staking.getVaults does exactly this:

import {
AmadeusSDK,
buildOwnerVaultsKeyPrefix,
epochFromHeight,
parseLockupVaultEntries,
summarizeLockupVaults
} from '@amadeus-protocol/sdk'

const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const owner = '5Kd3N...'

const { stats } = await sdk.chain.getStats()
const currentEpoch = epochFromHeight(stats.height)

const entries = await sdk.contract.getPrefixEntries(buildOwnerVaultsKeyPrefix(owner))
const vaults = parseLockupVaultEntries(entries, { currentEpoch }, owner)
const summary = summarizeLockupVaults(vaults)

console.log(summary.totalStaked, summary.vaultCount)
FunctionDescription
buildOwnerVaultsKeyPrefix(publicKey)bic:lockup_vault:vault:{owner}:. Keys returned under it are the vault index alone.
buildAllVaultsKeyPrefix()bic:lockup_vault:vault:. Keys returned are {owner}:{index}.
buildVaultKey(publicKey, index)The full key of one vault.
buildAllValidatorCommissionsKeyPrefix(), buildValidatorCommissionKey(publicKey)Commission record prefix and key.
parseLockupVaultEntries(entries, { currentEpoch }, owner?)Decodes [key, value] pairs into LockupVaultEntry[], sorted by index. Skips records that do not decode.
parseLockupVaultEntry(entry, { currentEpoch }, owner?)Decodes one pair. Throws on a bad record.
decodeLockupVaultRecord(value)The raw stored fields (RawLockupVaultRecord).
parseValidatorCommissions(entries, { currentEpoch })Commission records keyed by validator.
summarizeLockupVaults(vaults)Rolls vaults up into a StakingSummary.
estimateEpochYieldFlat(totalFlat, rateBps)Gross yield per epoch, with the node's integer division.
estimateYieldOverEpochs(totalFlat, rateBps, epochs)Gross yield over a span of whole epochs.

Public keys inside these prefixes are raw bytes. The builders accept a Base58 string or 48 bytes and throw on any other length. For prefix reads in general, see Contract state.