3. Core Concepts
The ideas the rest of the SDK documentation builds on.
Keypairs
Amadeus uses BLS12-381 keys. An account is a keypair:
- Public key: 48 bytes, Base58-encoded. It is also the account's address.
- Private key (seed): 64 bytes, Base58-encoded. The SDK calls it
privateKeyor seed; the signing key is derived from it.
import { generateKeypair, derivePublicKeyFromSeedBase58 } from '@amadeus-protocol/sdk'
const keypair = generateKeypair()
console.log('Address:', keypair.publicKey) // Base58, 48 bytes
console.log('Seed:', keypair.privateKey) // Base58, 64 bytes; keep it secret
// The address can always be recomputed from the seed
const address = derivePublicKeyFromSeedBase58(keypair.privateKey)
console.log(address === keypair.publicKey) // true
generateKeypair uses crypto.getRandomValues. To use a raw 32-byte BLS secret key exported from another tool, wrap it into a seed with secretKeyToSeedBase58.
Recovery phrases
A 12-word BIP39 recovery phrase can stand in for the seed. The same phrase can open two different accounts, depending on how the seed was derived:
eip2333: EIP-2333 alongm/12381'/36969'/0'/0'/0'.mnemonicToSeedBase58returns this one since SDK 1.4.0.legacy: the raw 64-byte BIP39 seed.mnemonicToSeedBase58returned this one in SDK 1.3.0 and earlier.
import {
generateMnemonic,
mnemonicToSeedBase58,
mnemonicToCandidateKeypairs,
derivePublicKeyFromSeedBase58
} from '@amadeus-protocol/sdk'
const mnemonic = generateMnemonic() // 12 words
// Standard (EIP-2333) seed, returned since SDK 1.4.0
const seed = mnemonicToSeedBase58(mnemonic)
console.log(derivePublicKeyFromSeedBase58(seed))
// Both accounts the phrase can open: eip2333 first, legacy second
for (const candidate of mnemonicToCandidateKeypairs(mnemonic)) {
console.log(candidate.derivation, candidate.publicKey)
}
When you restore a phrase, check both candidates before you tell a user their account is empty. Recovery phrases covers validation, choosing the right account on import and the vault helpers.
Addresses
An address is the Base58-encoded 48-byte public key, and the same address works on mainnet and testnet. Addresses are usually 66 characters long, for example 6969GaCysicYUFd6JQhxG1QPwRvXdTGtWVCCAEgM6Kq1jcSMX7RySrSFU9WRHWbJyE. An address is public and safe to share.
Validate addresses with the SDK instead of checking the length yourself:
import { isValidAddress, validateAddress } from '@amadeus-protocol/sdk'
const address = '6969GaCysicYUFd6JQhxG1QPwRvXdTGtWVCCAEgM6Kq1jcSMX7RySrSFU9WRHWbJyE'
console.log(isValidAddress(address)) // true
const result = validateAddress('abc')
if (!result.valid) {
console.log(result.error) // Invalid address length: expected 48 bytes, got 3
}
Both decode the Base58 string and check that it is exactly 48 bytes.
Transactions
A transaction is one contract call signed by one account. The SDK:
- Builds it: signer public key, nonce, and an action (
op: 'call', contract, function, arguments). - Encodes it with VecPak and hashes the bytes with SHA-256.
- Signs the hash with the signer's BLS key, under the network's signing domain.
- Packs the transaction, hash and signature into one byte array (
txPacked) to submit.
Transaction structure
interface UnsignedTransaction {
signer: Uint8Array // sender public key, 48 bytes
nonce: bigint
action: TransactionAction
}
interface TransactionAction {
op: 'call'
contract: string // e.g. 'Coin', 'Nft', 'LockupPrime'
function: string // e.g. 'transfer'
args: SerializableValue[]
}
A token transfer, for example, is a call to Coin.transfer with the recipient's public key bytes, the amount in atomic units as a string, and the symbol.
Transaction lifecycle
builder.transfer() does all four steps at once. To inspect the transaction before signing, build and sign separately:
import { AmadeusSDK, TransactionBuilder } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const builder = new TransactionBuilder('<your Base58 seed>')
// 1. Build: signer, nonce and action, plus the SHA-256 hash of the encoded tx
const unsigned = builder.buildTransfer({
recipient: '<recipient address>',
amount: 10.5,
symbol: 'AMA'
})
console.log(unsigned.tx.nonce, unsigned.tx.action.contract, unsigned.tx.action.function)
// 2. Sign: BLS signature over the hash, packed with the tx
const { txHash, txPacked } = builder.sign(unsigned)
// 3. Submit
const { hash } = await sdk.transaction.submit(txPacked)
console.log(hash === txHash) // true
Transaction Building covers every builder method. For contract calls from an ABI and NFT operations, see Contracts and NFTs.
Nonces
The SDK sets the nonce from the clock when it builds a transaction: BigInt(Date.now()) * 1_000_000n. The node only applies a transaction whose nonce is higher than the last nonce it applied for that account. In practice:
- Two transactions built by the same account in the same millisecond get the same nonce, and only one of them can be applied.
- If you build several transactions and submit them later, submit them in the order you built them. A transaction with a lower nonce than one already applied is rejected.
Network-bound signing
Since SDK 1.3.0 a signature is bound to its network. The BLS signature is made under a domain separation tag (DST) that differs per network:
| Network | Signing domain (DST) |
|---|---|
| Mainnet and custom networks | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_TX_ |
| Testnet | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_TX_TESTNET_ |
A transaction signed for one network fails signature checks on the other, so it cannot be replayed there. txDstForNetwork(network) returns the tag for a NetworkType.
The default is mainnet. To sign for testnet, create the TransactionBuilder with { network: NetworkType.TESTNET } (since 1.8.0), or pass NetworkType.TESTNET to one of the signing functions (signContractCall, buildAndSignRaw or signUnsigned):
import { AmadeusSDK, NetworkType, TransactionBuilder, buildCoinTransfer, signContractCall } from '@amadeus-protocol/sdk'
const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })
// Every transaction this builder signs uses the testnet domain
const builder = new TransactionBuilder('<your Base58 seed>', { network: NetworkType.TESTNET })
const { txPacked } = builder.transfer({ recipient: '<recipient address>', amount: 1, symbol: 'AMA' })
const { hash } = await testnet.transaction.submit(txPacked)
console.log(hash)
// Same signature without a builder
const call = buildCoinTransfer({ recipient: '<recipient address>', amount: 1, symbol: 'AMA' })
const signed = signContractCall('<your Base58 seed>', call, NetworkType.TESTNET)
Networks and testnet covers NetworkType, the network URLs and the testnet faucet.
Confirmed vs finalized
After submission a transaction goes through two stages:
- Confirmed (
metadata.status: 'committed'): the transaction is in an entry on the chain, has executed, and its receipt is available. The node can still rewind an entry that is not finalized. - Finalized (
metadata.status: 'finalized'): the entry's height is at or below the chain's rooted (finalized) height. A finalized entry is never rewound.
submitAndWait(txPacked) returns as soon as the transaction is confirmed. Pass { finalized: true } when you need the stronger guarantee, for example before crediting an off-chain ledger or releasing goods.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
declare const txPacked: Uint8Array
// Returns once the tx is in an entry (metadata.status may still be 'committed')
const confirmed = await sdk.transaction.submitAndWait(txPacked)
// Returns only once that entry is final (metadata.status === 'finalized')
const finalized = await sdk.transaction.submitAndWait(txPacked, { finalized: true })
console.log(confirmed.metadata.status, finalized.metadata.status)
The node polls for the transaction for about 6 seconds (60 checks, 100 ms apart). If the transaction is not in an entry (or, with finalized: true, not final) by then, the call fails without a receipt; look it up with sdk.chain.getTransaction(txHash) before you build a new one. getTransaction returns the same metadata.status, or 'pending' while the transaction is still in the node's mempool. An entry's consensus.finality_reached tells you whether that entry is final.
Amounts
AMA has 9 decimal places: 1 AMA is 1,000,000,000 atomic units (the node and SDK call them "flat"). Transactions carry atomic units. builder.transfer() converts the human-readable amount for you; when you build arguments yourself, convert with toAtomicAma, which rounds to the nearest atomic unit.
import { toAtomicAma, fromAtomicAma, AMA_TRANSFER_FEE } from '@amadeus-protocol/sdk'
console.log(toAtomicAma(1.5)) // 1500000000
console.log(fromAtomicAma(1500000000)) // 1.5
// Plain float maths can drift; toAtomicAma does not
console.log(1.005 * 1_000_000_000) // 1004999999.9999999
console.log(toAtomicAma(1.005)) // 1005000000
console.log(AMA_TRANSFER_FEE) // 0.02 (reserve to hold back per transfer)
AMA_TRANSFER_FEE is a conservative reserve that the extension and mobile wallet keep back, not what the chain charges. Each transaction locks a 0.01 AMA budget, pays for its size, execution and storage from it and gets the rest refunded. A transfer to an account that already holds AMA costs about 0.0003 AMA. See Transaction fees.
toAtomicAma and fromAtomicAma work with JavaScript numbers, which are exact only up to 2^53. Staking amounts can be larger, so sdk.staking returns them as bigint fields (*Flat) with flatToAma to convert. See Staking.
Balances come back in both forms: balance.flat (atomic units) and balance.float (AMA). Both are parsed as JavaScript numbers, so flat can lose its last digits on balances above 2^53 atomic units (about 9 million AMA).
NFTs
NFTs live in the built-in Nft contract, which runs on testnet only (a mainnet call fails with invalid_bic_action). Each holding is an integer count per account, collection and token, stored at account:{pk}:nft:{collection}:{token}. A (collection, token) pair can have any supply, unless the collection was created as non-fungible: then each token is minted once, with amount 1.
- NFT amounts are integer counts, not AMA atomic units. Do not pass them through
toAtomicAma. - The account that creates a collection gets permission to mint in it. Minting without that permission fails.
- A soulbound collection or token cannot be transferred to another holder. Burning it (sending it to the burn address) is still allowed.
The SDK exports NFT_ABI, standalone builders (buildNftTransfer, buildNftMint, buildNftCreateCollection) and the TransactionBuilder methods nftTransfer, nftMint and nftCreateCollection. Since 1.8.0 the mint and create-collection helpers send the one VecPak map the node expects (1.7.0 sent separate arguments, which the node rejected). Sign them for testnet. Contracts and NFTs covers each call.
Serialization
The node hashes and signs transactions in VecPak, a canonical binary format: the same value always encodes to the same bytes, because map keys are sorted by their encoded bytes. The SDK's code and comments spell it "VecPack". encode and decode expose it directly:
import { encode, decode } from '@amadeus-protocol/sdk'
const encoded = encode({ foo: 'bar', count: 42, items: [1, 2, 3] })
console.log(encoded instanceof Uint8Array) // true
// Maps decode to Map, integers to bigint, strings to Uint8Array
const decoded = decode(encoded)
if (decoded instanceof Map) {
const text = new TextDecoder()
for (const [key, value] of decoded) {
const name = key instanceof Uint8Array ? text.decode(key) : String(key)
console.log(name, value)
}
}
| You encode | It decodes as |
|---|---|
null, true, false | the same |
integer number or bigint | bigint |
string or Uint8Array | Uint8Array (VecPak has one bytes type) |
| array | array |
object or Map | Map |
Only integers can be encoded. A fractional number such as 1.5 throws a RangeError, so send amounts as atomic-unit integers or strings.
Contract state that nodes return is VecPak too. Contract state covers the decoders for it.
Encoding formats
- Base58: addresses, seeds, transaction and entry hashes, signatures.
- Base64: encrypted payloads from
encryptWithPassword.
import { toBase58, fromBase58, uint8ArrayToBase64, base64ToUint8Array } from '@amadeus-protocol/sdk'
const bytes = new Uint8Array([1, 2, 3])
const base58 = toBase58(bytes) // 'Ldp'
console.log(base58, fromBase58(base58))
const base64 = uint8ArrayToBase64(bytes) // 'AQID'
console.log(base64, base64ToUint8Array(base64))
Encryption
encryptWithPassword protects a seed or phrase at rest with a password:
import { encryptWithPassword, decryptWithPassword } from '@amadeus-protocol/sdk'
const seed = '<your Base58 seed>'
// { encryptedData, iv, salt }, all Base64; safe to store
const encrypted = await encryptWithPassword(seed, 'correct horse battery staple')
const decrypted = await decryptWithPassword(encrypted, 'correct horse battery staple')
console.log(decrypted === seed) // true; a wrong password throws
- AES-GCM with a 256-bit key, so tampered data fails to decrypt.
- The key is derived with PBKDF2-SHA-256, 100,000 iterations.
- A new random 16-byte salt and 12-byte IV for every call.
It uses Web Crypto (crypto.subtle), available in browsers and Node.js 20+.
API client
AmadeusSDK wraps one HTTP client shared by all modules.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({
baseUrl: 'https://mainnet-rpc.ama.one/api',
timeout: 30000,
headers: { 'X-App-Name': 'my-dapp' } // merged into every request
})
sdk.setBaseUrl('https://testnet-rpc.ama.one/api') // switch node at runtime
console.log(sdk.getConfig().baseUrl)
sdk.cancel() // aborts every request still in flight on this instance
- Timeout: 30,000 ms by default. A request that times out throws
AmadeusSDKErrorwith status408. - Concurrency: since 1.7.0 each request has its own abort controller, so parallel requests on one instance no longer cancel each other.
cancel()aborts all of them; a request cancelled before the node answers throws with status0. - Base URL path: the SDK resolves every endpoint as an absolute path (
/api/...) againstbaseUrl, so only the scheme and host ofbaseUrlare used. A proxy prefix such ashttps://example.com/node1/apiis dropped and requests go tohttps://example.com/api/.... Serve the node API at/apion its own host if you put it behind a proxy.
API modules
sdk.chain: tip, stats, KPIs, entries, transactions, transaction events by account, filtered transaction queriessdk.wallet: balances (one token, or all tokens of an address)sdk.transaction: submit, submit and wait, get a transaction, transactions in an entrysdk.contract: contract state reads,viewcalls, richlistsdk.epoch: validator scores, emission addresses, solution checkssdk.peer: nodes, trainers, ANRssdk.proof: contract state proofssdk.staking: LockupVault staking positions (see Staking)
MetricsAPI is a separate client created with the URL of the metrics service. See API Modules for the full reference.
Error handling
Every failure from the client is an AmadeusSDKError with a message, an HTTP-style status and, when the node sent one, the parsed response body. Input that fails the SDK's own checks (for example an empty transaction) throws an AmadeusSDKError with no status before any request is sent.
import { AmadeusSDK, AmadeusSDKError } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const unknownHash = '11111111111111111111111111111111'
try {
await sdk.chain.getTransaction(unknownHash)
} catch (error) {
if (error instanceof AmadeusSDKError) {
console.log(error.message) // 'HTTP 404: not_found'
console.log(error.status) // 404
console.log(error.response) // { error: 'not_found' }
}
}
The node wraps its answers in an error field. The SDK turns that into results or exceptions:
| Node answer | What the SDK does |
|---|---|
error: 'ok' | Returns the response without the error field |
error: 'not_found' | Throws with status 404 |
Any other error value, such as invalid_signature | Throws with status 400; the message is the node's error code |
| Non-2xx HTTP status | Throws with that status |
| Timeout / cancelled / network failure | Throws with status 408 / 0 / 0 |
Never check result.error === 'ok' on an SDK result: on success the field is gone. getTransactionErrorMessage(code) turns a node error code into a readable message for your UI.
A transaction can also be accepted but fail when it executes. Then submitAndWait resolves, and receipt.success is false with the reason in receipt.result.
Next steps
- Transaction Building: build and sign every kind of transaction
- API Modules: reference for each
sdk.*module - Utilities: encoding, conversion, validation and formatting helpers
- Examples: end-to-end samples