Migration guide
What changed in @amadeus-protocol/sdk from 1.0.x through 1.8.0, and what to change in your code.
Overview
Most releases after 1.0 are drop-in. Five need attention:
- 1.1.2 corrected the types to match what the node really returns. Code that read fields that never existed now fails to compile.
- 1.3.0 made signing network-aware. Testnet transactions must be signed for testnet.
- 1.4.0 changed which account a recovery phrase opens. This is the only change in runtime behavior that can strand a user on an empty address.
- 1.7.0 fixed parallel requests and staking reads. If you work around either, you can remove the workaround.
- 1.8.0 lets
TransactionBuildersign for testnet, fixes the NFT mint and create-collection calls,contract.viewon deployed contracts and account history paging, and corrects some response types. Code that read the old types can fail to compile.
To upgrade:
npm install @amadeus-protocol/sdk@latest
Then check the installed version with AmadeusSDK.getVersion(). It returns 1.8.0; on 1.3.0 to 1.5.0 it wrongly reported 1.2.0.
| Version | Change | Action |
|---|---|---|
| 1.0.4 | Default API URL is https://mainnet-rpc.ama.one/api | Replace any hard-coded older URL |
| 1.1.0 | ESM imports fixed under plain Node.js; contract.view, chain.getByFilter, chain.getKpi, proof.getContractStateProof, submitAndWait(tx, { finalized }), NFT builders | None; drop tsx or bundler workarounds for ERR_MODULE_NOT_FOUND |
| 1.1.2 | Types corrected (entry.header, ChainStats, submit responses, richlist, balances) | Fix the field names below |
| 1.2.0 | sdk.staking, contract.getPrefixEntries, ChainStats additions, empty-prefix fix | Replace getPrefix with getPrefixEntries |
| 1.3.0 | Network-aware signing, MetricsAPI, chain.getMetricsBlock | Sign testnet transactions with NetworkType.TESTNET |
| 1.4.0 | Breaking: mnemonicToSeedBase58 derives the EIP-2333 account | Recover legacy accounts on import |
| 1.5.0 | mnemonicToCandidateKeypairs, secretKeyToSeedBase58 | None |
| 1.6.0 | resolveMnemonicImport, resolveCandidateForAddress, derivationForSeed, normalizeMnemonic | Use them for phrase import |
| 1.7.0 | Parallel requests no longer cancel each other; paged get_prefix decoded | None; remove serialization workarounds |
| 1.8.0 | TransactionBuilder network option; NFT map args; contract.view on deployed contracts; getTransactionEventsByAccount, ContractStateProof and getANRByPk types; new proof methods; four deprecations | Drop testnet and NFT workarounds; fix the type changes below |
1.0.4: Default API URL
The default baseUrl became https://mainnet-rpc.ama.one/api. If you pass a URL, use that one:
- const sdk = new AmadeusSDK({ baseUrl: 'https://nodes.amadeus.bot/api' })
+ const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
1.1.0: ESM Fix and New Read APIs
1.0.x shipped ESM without .js extensions on its relative imports, so plain node failed with ERR_MODULE_NOT_FOUND. 1.1.0 fixed the build; no code change is needed. The package stays ESM only (see Troubleshooting).
1.1.0 also added, without breaking anything:
sdk.contract.view({ contract, function, args, pk })sdk.chain.getByFilter({ signer, arg0, contract, function, limit, sort, cursor })sdk.chain.getKpi()sdk.proof.getContractStateProof(key, value?). On node 1.6.5 it resolves with{ root_contractstate, entry_hash, entry_height, proofs }, which matches itsContractStateProoftype only since 1.8.0. Passingvaluerequests a path the node does not serve (HTTP 520throughmainnet-rpc.ama.one); 1.8.0 deprecates itsdk.transaction.submitAndWait(txPacked, { finalized: true })- NFT support:
NFT_ABI,buildNftTransfer,buildNftMint,buildNftCreateCollectionand the matchingTransactionBuildermethods (see Contracts and NFTs)
1.1.2: Type Corrections
1.1.2 audited every public type against live mainnet responses. The runtime did not change, but fields that never existed were removed, so TypeScript now flags code that read them. That code was already getting undefined at runtime.
Chain entries and stats
Header fields live under entry.header. ChainStats never had total_entries or total_transactions.
- console.log(tip.entry.height, tip.entry.timestamp)
+ console.log(tip.entry.header.height, tip.entry.header.slot)
- console.log(stats.stats.total_entries, stats.stats.total_transactions)
+ console.log(stats.stats.height, stats.stats.rooted_height, stats.stats.tx_pool_size)
entry.timestamp, entry.mutations_hash and entry.header_unpacked never existed. For a transaction count, sdk.chain.getKpi() returns kpi.total_tx.
Submit responses: no more error === 'ok'
The SDK removes the node's error: 'ok' from successful responses and throws AmadeusSDKError on failure. A check for result.error === 'ok' is never true, so the success branch never ran.
Before:
- const result = await sdk.transaction.submit(txPacked)
- if (result.error === 'ok') {
- console.log('Submitted:', result.hash)
- } else {
- console.error('Error:', result.error)
- }
After:
import { AmadeusSDK, AmadeusSDKError } from '@amadeus-protocol/sdk'
declare const txPacked: Uint8Array
const sdk = new AmadeusSDK()
try {
const { hash } = await sdk.transaction.submit(txPacked)
console.log('Submitted:', hash)
} catch (error) {
console.error('Error:', error instanceof AmadeusSDKError ? error.message : error)
}
The same applies to submitAndWait, which now resolves with { hash, metadata, receipt }, all present. An included transaction can still fail to execute: check receipt.success (see Two Kinds of Transaction Errors).
Richlist and balances
Richlist entries are { pk, symbol, flat, float }, and getAllBalances returns an array.
- richlist.forEach((entry) => console.log(entry.rank, entry.address, entry.balance))
+ richlist.forEach((entry, index) => console.log(index + 1, entry.pk, entry.float))
- Object.entries(allBalances.balances).forEach(([symbol, balance]) => console.log(symbol, balance.float))
+ allBalances.balances.forEach(({ symbol, float }) => console.log(symbol, float))
Epoch responses
sdk.epoch.getScore(publicKey)resolves with{ score }; without a key it returns[publicKey, score]pairs.sdk.epoch.getEmissionAddress(publicKey)resolves with{ emission_address }, which isnullwhen none is set.sdk.epoch.getSolInEpoch(...)resolves with an empty object and throws forinvalid_epochorsol_not_found.
- if (result.error === 'ok') return result.score
+ const { score } = await sdk.epoch.getScore(publicKey)
1.2.0: Binary Contract Reads and Staking
/api/contract/get_prefix answers with a binary VecPack body. contract.getPrefix() parses it as text and cannot represent it. Use contract.getPrefixEntries(), which returns [key, value] byte pairs:
- const items = await sdk.contract.getPrefix(prefix)
- items.forEach((item) => console.log(item.key, item.value))
+ const entries = await sdk.contract.getPrefixEntries(prefix)
+ entries.forEach(([key, value]) => console.log(key, value))
Prefixes are raw bytes (bic:lockup_vault:vault: and so on), not Base58; a string argument is sent as UTF-8. Keys come back with the prefix stripped.
1.2.0 also added:
sdk.staking.getPosition,getVaults,getAllVaults,getValidatorCommissionsandgetCurrentEpochfor LockupVault staking. Amounts are atomicbigint(*Flat); convert them withflatToAma. See Staking.client.postBinary(endpoint, data)for binary endpoints.ChainStatsfieldstotal_locked,total_supply,supply_computed_at_heightandvalidators.- A fix for
decodeContractState, which threwExpected MAP type, got objectfor a prefix with no matches.
1.3.0: Network-Aware Signing
Testnet verifies transactions under its own signing domain (..._TX_TESTNET_), so a transaction signed for one network cannot be replayed on the other. signUnsigned, buildAndSignRaw and signContractCall take an optional network; the default is mainnet, so mainnet code is unchanged.
From 1.3.0 to 1.7.x, TransactionBuilder had no network option and always signed for mainnet, so its output was rejected on testnet with invalid_signature. On those versions, sign testnet calls with signContractCall. 1.8.0 adds the option; see Testnet signing in TransactionBuilder.
- const builder = new TransactionBuilder(seed)
- const { txPacked } = builder.transfer({ recipient, amount: 1, symbol: 'AMA' })
+ const call = buildCoinTransfer({ recipient, amount: 1, symbol: 'AMA' })
+ const { txPacked } = signContractCall(seed, call, NetworkType.TESTNET)
In full:
import {
AmadeusSDK,
NETWORK_URLS,
NetworkType,
buildCoinTransfer,
signContractCall,
txDstForNetwork
} from '@amadeus-protocol/sdk'
declare const seed: string
declare const recipient: string
const testnet = new AmadeusSDK({ baseUrl: `${NETWORK_URLS[NetworkType.TESTNET]}/api` })
const call = buildCoinTransfer({ recipient, amount: 1, symbol: 'AMA' })
const { txPacked } = signContractCall(seed, call, NetworkType.TESTNET)
await testnet.transaction.submitAndWait(txPacked)
// the tag each network verifies against
console.log(txDstForNetwork(NetworkType.TESTNET))
1.3.0 also exported the signing primitives (buildUnsigned, signUnsigned, buildAndSignRaw, buildUnsignedFromCall, signContractCall, normalizeSignerSk, txDstForNetwork) from the package root, and added MetricsAPI and chain.getMetricsBlock(height). Node 1.6.5 does not serve the /api/chain/metrics/block endpoint that getMetricsBlock calls, so on mainnet it throws with status 404; 1.8.0 deprecates it. See Networks and testnet.
1.4.0: Recovery Phrases Open a Different Account
mnemonicToSeedBase58(mnemonic) kept its name and signature but returns a different seed, and so a different address, for the same phrase:
| Derivation | Produced by | |
|---|---|---|
1.3.0 and earlier (legacy) | The raw 64-byte BIP39 seed, used as the Amadeus seed | Wallets built on those SDK versions |
1.4.0 and later (eip2333) | EIP-2333 BLS12-381 along m/12381'/36969'/0'/0'/0' | The SDK, hub, Prime Hub and cli-wallet |
Seeds already stored in a vault are not affected: only deriving from the phrase again changes the result. If your app restores phrases, a user who created a wallet with 1.3.0 or earlier gets an empty account unless you look for the legacy one.
Before:
- const seed = mnemonicToSeedBase58(mnemonic)
- const address = derivePublicKeyFromSeedBase58(seed)
After (1.6.0+):
import {
addressHasActivity,
resolveCandidateForAddress,
resolveMnemonicImport,
validateMnemonic
} from '@amadeus-protocol/sdk'
declare const mnemonic: string
declare const knownAddress: string | undefined
if (!validateMnemonic(mnemonic)) throw new Error('Invalid recovery phrase')
if (knownAddress) {
// the address is known: pick the derivation that opens it
const candidate = resolveCandidateForAddress(mnemonic, knownAddress)
console.log(candidate?.derivation, candidate?.seed)
} else {
// otherwise check both accounts for history
const result = await resolveMnemonicImport(mnemonic, (address) =>
addressHasActivity('https://mainnet-rpc.ama.one/api', address)
)
console.log(result.reason, result.needsChoice, result.chosen?.publicKey)
}
resolveMnemonicImport opens one account only when the answer is clear: single-active (one has history, the other is confirmed empty) or none-active (both empty, so the standard account). For both-active and check-failed it sets needsChoice and leaves chosen as null, and the user picks. Always show the other address too. On 1.5.0 you can derive both candidates yourself with mnemonicToCandidateKeypairs(mnemonic). See Recovery phrases.
1.5.0 and 1.6.0: Import Helpers
These releases only add functions:
- 1.5.0:
mnemonicToCandidateKeypairs(mnemonic)returns both candidates, standard first, as{ derivation, seed, publicKey }.secretKeyToSeedBase58(secretKey)wraps a raw 32-byte BLS secret key (for example a hub export) into a 64-byte Amadeus seed. - 1.6.0:
resolveMnemonicImport,addressHasActivity,resolveCandidateForAddress,derivationForSeedandnormalizeMnemonic.
Since 1.6.0, validateMnemonic, mnemonicToSeedBase58 and mnemonicToCandidateKeypairs collapse extra spaces and line breaks in a phrase. Single-spaced phrases derive exactly the same keys as before.
1.7.0: Concurrency and Paged Prefix Reads
Parallel requests
Before 1.7.0, AmadeusClient aborted the request in flight whenever a new one started on the same client, and reported it as a timeout. If you serialized calls or created one AmadeusSDK per request to avoid this, you can now share one instance:
import { AmadeusSDK } from '@amadeus-protocol/sdk'
declare const addresses: string[]
const sdk = new AmadeusSDK()
const balances = await Promise.all(
addresses.map((address) => sdk.wallet.getBalance(address, 'AMA'))
)
sdk.cancel() now aborts every request in flight; each aborted call throws Request cancelled with status 0.
Paged get_prefix
Since node commit 78b5e9c, /api/contract/get_prefix answers in pages of {rows, cursor} (at most 1,000 rows or 1 MiB each). On older SDKs decodeContractState read the paged body as two bad rows and threw, so every sdk.staking.* read failed and wallets showed no stake. 1.7.0 decodes both shapes, and getPrefixEntries follows the cursor to the last page.
If you call the endpoint with your own HTTP client, page with the new helpers:
import { prefixPagePath, readAllPrefixPages } from '@amadeus-protocol/sdk'
const apiBaseUrl = 'https://mainnet-rpc.ama.one/api'
const prefix = new TextEncoder().encode('bic:lockup_vault:vault:')
const entries = await readAllPrefixPages(async (cursor) => {
const response = await fetch(apiBaseUrl + prefixPagePath(cursor), {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: prefix
})
return response.arrayBuffer()
})
console.log('Rows:', entries.length)
readAllPrefixPages throws instead of returning a cut-off list: on a page that does not decode, on a repeated cursor, or past maxPages (default 50). decodeContractStatePage(bytes) decodes a single page into { entries, cursor }. See Contract state.
1.8.0: Testnet Builder, NFT Calls and Node-Aligned Types
Testnet signing in TransactionBuilder
new TransactionBuilder(privateKey, { network }) signs every transaction of that builder for network. createContract(abi).connect(privateKey, network) takes it as a second argument, and every static method that signs (signCall, sign, buildAndSign, buildAndSignCall, buildSigned*) as an optional last one. Mainnet stays the default, so mainnet code is unchanged. You can drop the testnet workaround from 1.3.0:
- const call = buildCoinTransfer({ recipient, amount: 1, symbol: 'AMA' })
- const { txPacked } = signContractCall(seed, call, NetworkType.TESTNET)
+ const builder = new TransactionBuilder(seed, { network: NetworkType.TESTNET })
+ const { txPacked } = builder.transfer({ recipient, amount: 1, symbol: 'AMA' })
signContractCall(seed, call, NetworkType.TESTNET) still works and stays the way to sign a ContractCall without a builder.
NFT mint and create collection
The node takes one VecPak map for Nft.mint and Nft.create_collection. Up to 1.7.x, buildNftMint, buildNftCreateCollection, nftMint, nftCreateCollection and their static versions sent separate arguments, and every call failed with invalid_args. 1.8.0 sends the map. If you encoded the map yourself, switch back to the builders:
- const createCall = {
- contract: 'Nft',
- method: 'create_collection',
- args: [encode({ collection: 'AGENTIC', soulbound: 'false', nonfungible: 'false' })]
- }
+ const createCall = buildNftCreateCollection({ collection: 'AGENTIC' })
NftCreateCollectionParams gains an optional nonfungible and NftMintParams an optional soulbound, both booleans that default to false. createContract(NFT_ABI).create_collection and .mint still send separate arguments, so do not use them. Nft runs on testnet only; see Contracts and NFTs.
contract.view on deployed contracts
contract.view sent a Base58 contract address as text, so the node looked for a built-in contract by that name and answered invalid_bic_action. 1.8.0 sends it as the 48-byte key, and ContractViewParams.contract is typed string | Uint8Array. Remove the cast:
- const contract = fromBase58(contractAddress) as unknown as string
- await sdk.contract.view({ contract, function: 'get' })
+ await sdk.contract.view({ contract: contractAddress, function: 'get' })
Account history
chain.getTransactionEventsByAccount is typed { cursor: string | null, txs: Transaction[] }, which is what the node returns, and it sends cursor as cursor_b58, the parameter the node decodes. The old TransactionEvent type is deprecated. Code that read txid, amount or timestamp from the items now fails to compile; read the Transaction fields instead:
import { AmadeusSDK, TransactionEventType, type Transaction } from '@amadeus-protocol/sdk'
declare const account: string
const sdk = new AmadeusSDK()
async function readSent(cursor: string | undefined, pagesLeft: number): Promise<Transaction[]> {
const page = await sdk.chain.getTransactionEventsByAccount(account, {
type: TransactionEventType.SENT,
limit: 100,
sort: 'desc',
cursor
})
if (!page.cursor || pagesLeft <= 1) return page.txs
return [...page.txs, ...(await readSent(page.cursor, pagesLeft - 1))]
}
const sent = await readSent(undefined, 3)
console.log(sent.map((tx) => [tx.hash, tx.metadata.tx_event, tx.receipt.success]))
The node pages only when type is set. Without it, sent and received are merged and cursor is always null.
Proofs
ContractStateProof now has the node's shape: entry_height, entry_hash, root_contractstate and proofs, one { key, namespace, proof } per key. The old namespace, key, proof, value and result fields at the top level are gone, so drop any local type and cast:
- const answer = (await sdk.proof.getContractStateProof(key)) as unknown as StateProofAnswer
+ const answer = await sdk.proof.getContractStateProof(key)
console.log(answer.root_contractstate, answer.proofs[0]?.proof.terminus)
Two methods are new: proof.getValidatorRecord(height) and proof.getBlockProof(height, { atHeight }), typed ValidatorRecordProof and BlockProof. See Proof API.
peer.getANRByPk
anr is typed ANRInfo | null, as the node answers for an unknown key. Check it before you read its fields:
const { anr } = await sdk.peer.getANRByPk(publicKey)
- console.log(anr.ip4)
+ if (anr) console.log(anr.ip4)
Deprecated methods
These call routes the node does not serve. They now throw a deprecation AmadeusSDKError that names the method, instead of a plain 404 from the node:
| Method | In 1.8.0 | Instead |
|---|---|---|
contract.validateBytecode(bytecode) | Throws (status 404) without a request | None; contracts are checked when deployed |
proof.getValidators(entryHash) | Throws (status 404) without a request | proof.getValidatorRecord(height) |
chain.getMetricsBlock(height) | Sends the request; a 404 is rethrown as the deprecation error (status 404) | MetricsAPI for daily activity |
proof.getContractStateProof(key, value) | Throws without a request | getContractStateProof(key), then compare terminus.value_hash |
If you checked these for HTTP 404: not_found, check error.status === 404 or remove the calls.
Documentation fixes
toAtomicAma is now documented as rounding to the nearest atomic unit, which it already did. AMA_TRANSFER_FEE (0.02) is documented as a balance reserve, not the fee the chain charges: the chain locks 0.01 AMA per transaction and charges by usage (see Transaction fees). Neither value changed.
Checklist
- Install 1.8.0 and run your project as ESM.
- Replace
entry.height,stats.total_entries,richlist[i].addressandObject.entries(balances). - Remove every
result.error === 'ok'check; usetry/catchand checkreceipt.successaftersubmitAndWait. - Replace
contract.getPrefixwithcontract.getPrefixEntries. - Sign testnet transactions with
NetworkType.TESTNET, throughnew TransactionBuilder(seed, { network })orsignContractCall. - Build NFT mints and collections with
buildNftMintandbuildNftCreateCollection, not hand-encoded maps orcreateContract(NFT_ABI). - Remove calls to
validateBytecode,proof.getValidators,getMetricsBlockandgetContractStateProof(key, value). - If you import recovery phrases, look for the legacy account with
resolveMnemonicImportorresolveCandidateForAddress.