6. Utilities
Reference for the standalone helpers in @amadeus-protocol/sdk 1.8.0: keys, encoding, amounts, validation, formatting, explorer links, transaction errors, password encryption and contract-state values. Everything on this page is a named export of the package root, so import { ... } from '@amadeus-protocol/sdk' is all you need.
The SDK is built on @noble/curves and @noble/hashes (BLS12-381, SHA-256), @scure/bip39 (recovery phrases), bs58 and effect (input validation). HTTP calls use the native fetch.
Two topics have their own pages:
- Recovery phrases: BIP39 phrases, the EIP-2333 derivation used since 1.4.0, and importing a phrase that may belong to a legacy account.
- Networks and testnet:
NetworkType, network URLs, the faucet and network-bound signing.
Keys
An Amadeus account is a BLS12-381 key pair. The private key is a 64-byte seed, shown as Base58. The public key, which is also the account address, is 48 bytes, also Base58. The seed is reduced to a 32-byte BLS secret key when it signs.
import { derivePublicKeyFromSeedBase58, generateKeypair } from '@amadeus-protocol/sdk'
const keypair = generateKeypair()
console.log(keypair.publicKey) // Base58 48-byte public key: the account address
console.log(keypair.privateKey) // Base58 64-byte seed: keep it secret
console.log(derivePublicKeyFromSeedBase58(keypair.privateKey) === keypair.publicKey) // true
| Function | Returns | Notes |
|---|---|---|
generateKeypair() | KeyPair ({ publicKey, privateKey }, both Base58) | Random 64-byte seed and its public key |
generatePrivateKey() | Uint8Array (64 bytes) | Random seed from crypto.getRandomValues |
getPublicKey(seed64) | Uint8Array (48 bytes) | Public key for a 64-byte seed |
seed64ToKeypair(seed64) | [publicKey, secretKey] | secretKey is the 32-byte BLS key |
derivePublicKeyFromSeedBase58(seedBase58) | string | Base58 public key. Throws if the seed is empty or not 64 bytes |
deriveSkAndSeed64FromBase58Seed(seedBase58) | { sk, seed64 } | Throws if the seed is not 64 bytes |
reduce512To256LE(bytes64) | Uint8Array (32 bytes) | Seed to BLS secret key: reads the seed little-endian, reduces it mod the BLS12-381 group order and returns it big-endian. Throws unless the input is 64 bytes |
secretKeyToSeedBase58(secretKey) | string | Wraps a raw 32-byte BLS key into a 64-byte seed. See Recovery phrases |
Working with raw bytes:
import {
deriveSkAndSeed64FromBase58Seed,
generatePrivateKey,
getPublicKey,
seed64ToKeypair,
toBase58
} from '@amadeus-protocol/sdk'
const seed64 = generatePrivateKey() // Uint8Array(64)
const publicKey = getPublicKey(seed64) // Uint8Array(48)
const [samePublicKey, secretKey] = seed64ToKeypair(seed64) // secretKey: Uint8Array(32)
const { sk, seed64: decodedSeed } = deriveSkAndSeed64FromBase58Seed(toBase58(seed64))
console.log(publicKey.length, samePublicKey.length, secretKey.length, sk.length, decodedSeed.length) // 48 48 32 32 64
Encoding
Addresses, keys and hashes use Base58. Binary payloads such as encrypted vaults use Base64.
import {
base64ToUint8Array,
fromBase58,
toBase58,
uint8ArrayToBase64
} from '@amadeus-protocol/sdk'
const bytes = new Uint8Array([1, 2, 3])
const base58 = toBase58(bytes) // 'Ldp'
const base64 = uint8ArrayToBase64(bytes) // 'AQID'
console.log(fromBase58(base58)) // Uint8Array(3) [ 1, 2, 3 ]
console.log(base64ToUint8Array(base64)) // Uint8Array(3) [ 1, 2, 3 ]
| Function | Signature |
|---|---|
toBase58 | (buf: Uint8Array) => string |
fromBase58 | (str: string) => Uint8Array, throws on invalid Base58 |
uint8ArrayToBase64 | (bytes: Uint8Array) => string |
base64ToUint8Array | (base64: string) => Uint8Array |
arrayBufferToBase64 | (buffer: ArrayBuffer) => string |
base64ToArrayBuffer | (base64: string) => ArrayBuffer |
uint8ArrayToArrayBuffer | (bytes: Uint8Array) => ArrayBuffer |
arrayBufferToUint8Array | (buffer: ArrayBuffer) => Uint8Array |
The Base64 helpers use Node's Buffer when it exists and btoa/atob in browsers.
For VecPak, the binary format transactions and contract state use, the SDK exports encode(value) and decode(bytes). They are covered in Core concepts.
Amounts
AMA has 9 decimals: 1 AMA is 1,000,000,000 atomic units (called "flat" in the node and SDK). Transactions carry atomic units; people read AMA.
import { flatToAma, fromAtomicAma, toAtomicAma } from '@amadeus-protocol/sdk'
console.log(toAtomicAma(10.5)) // 10500000000
console.log(toAtomicAma('0.02')) // 20000000
console.log(fromAtomicAma(1500000000)) // 1.5
console.log(fromAtomicAma('20000000')) // 0.02
// bigint amounts above Number.MAX_SAFE_INTEGER (staking *Flat fields)
console.log(flatToAma(12345678901234567890n)) // 12345678901.234568
toAtomicAma(ama: number | string): number
Converts AMA to atomic units. The value is formatted with toFixed(9), so digits past the 9th decimal are rounded (toAtomicAma(1.0000000019) is 1000000002). Validate user input with validateAmount first so it never has more than 9 decimals.
fromAtomicAma(atomicAma: number | string): number
Converts atomic units to AMA. Returns 0 for 0 or a non-numeric string.
Throws: Error for a negative value, for a value between 0 and 1 ('Value is less than 1'), and for a value above Number.MAX_SAFE_INTEGER (about 9 million AMA).
flatToAma(flat: bigint): number
Converts a bigint atomic amount without the precision loss of Number(flat) / 1e9. Use it for the *Flat fields that sdk.staking returns (see Staking) and for any balance that can exceed 2^53 atomic units.
Validation
Use these instead of hand-rolled checks. Each validate* function in the table below returns a ValidationResult, { valid: true } or { valid: false, error: string }, and never throws. The isValid* versions return a boolean.
import {
isValidAddress,
validateAddress,
validateAmount,
validatePassword,
validateSeed,
validateTokenSymbol
} from '@amadeus-protocol/sdk'
const recipient = '5kizwGYhCDy8Dev7Qw31aVutXwk4sZCK18hVwWqUdLx8X6oG338XpoSR7X9c1fMg5o'
const addressCheck = validateAddress(recipient)
if (!addressCheck.valid) console.error(addressCheck.error)
console.log(isValidAddress('not-an-address')) // false
console.log(validateAmount('1.0000000001')) // { valid: false, error: 'Amount cannot have more than 9 decimal places' }
console.log(validateSeed('abc')) // { valid: false, error: 'Invalid seed length: expected 64 bytes, got 3' }
console.log(validateTokenSymbol('ama')) // { valid: false, error: 'Token symbol must contain only uppercase letters and numbers' }
console.log(validatePassword('correct horse', { requireUppercase: false, requireNumber: false, requireSpecial: false })) // { valid: true }
| Function | Checks |
|---|---|
validateAddress(address) / isValidAddress | Valid Base58 that decodes to 48 bytes |
validateSeed(seed) / isValidSeed | Valid Base58 that decodes to 64 bytes |
validateAmount(amount: string) / isValidAmount | Plain decimal string (/^\d+(\.\d+)?$/), at most 9 decimals, greater than 0 and at least MIN_TRANSFERABLE_AMOUNT (0.000000001) |
validatePassword(password, options?) | Length and character classes. Defaults: minLength 8, maxLength 128, and requireLowercase, requireUppercase, requireNumber, requireSpecial all true |
validateTokenSymbol(symbol) | 1 to 10 characters, uppercase letters and digits only |
These checks cover format only. validateAmount does not know the balance, and it does not add the 0.01 AMA transaction budget or the 0.02 AMA reserve (AMA_TRANSFER_FEE).
Formatting
Display helpers for amounts and addresses. Number formatting uses toLocaleString, so separators follow the runtime locale. The outputs below are for en-US.
import {
formatAMAAmount,
formatBalance,
formatBalanceWithPrivacy,
formatNumber,
formatShortAddress
} from '@amadeus-protocol/sdk'
console.log(formatNumber(1234567.891, 2)) // '1,234,567.89' (en-US locale)
console.log(formatAMAAmount(1234.5)) // '1,234.5 AMA'
console.log(formatBalance('0.020000000')) // '0.02'
console.log(formatBalanceWithPrivacy(42, true)) // '******'
console.log(formatShortAddress('5kizwGYhCDy8Dev7Qw31aVutXwk4sZCK18hVwWqUdLx8X6oG338XpoSR7X9c1fMg5o')) // '5kizwG...1fMg5o'
| Function | Signature |
|---|---|
formatNumber | (num: number, digits = 9) => string |
formatAMAAmount | (amount: number) => string, adds the AMA suffix |
formatBalance | (amount: string | number | undefined) => string, returns '0' for undefined |
formatBalanceWithPrivacy | (amount, hideBalances: boolean) => string, returns '******' when hidden |
formatShortAddress | (address: string, chars = 6) => string |
Explorer links
Build links to the Amadeus explorer. Links have the form <explorer>/network/tx/<hash> and <explorer>/network/address/<address>. Without a base URL they point at the mainnet explorer, https://explorer.ama.one.
import {
ExplorerType,
NETWORK_EXPLORER_URLS,
NetworkType,
makeAddressUrl,
makeExplorerUrl,
makeTransactionUrl
} from '@amadeus-protocol/sdk'
const txHash = '4J2sq34ahiFYB1wTevzbC1KwBNWJqVKQBL8ShTn7Pc6n'
const address = '5kizwGYhCDy8Dev7Qw31aVutXwk4sZCK18hVwWqUdLx8X6oG338XpoSR7X9c1fMg5o'
console.log(makeTransactionUrl(txHash)) // https://explorer.ama.one/network/tx/<hash>
console.log(makeAddressUrl(address, NETWORK_EXPLORER_URLS[NetworkType.TESTNET])) // https://testnet.explorer.ama.one/network/address/<address>
console.log(makeExplorerUrl(ExplorerType.ADDRESS, address)) // same as makeAddressUrl(address)
makeTransactionUrl(txHash, baseUrl?)makeAddressUrl(address, baseUrl?)makeExplorerUrl(type, id, baseUrl?), whereExplorerTypeisTRANSACTION('tx'),ADDRESS('address') orTIP('tip')
For testnet links pass NETWORK_EXPLORER_URLS[NetworkType.TESTNET] as the base URL.
Transaction errors
When the node rejects a transaction, the SDK throws an AmadeusSDKError whose message is the node's error code, such as invalid_signature or nonce_too_high. When a transaction is included but fails during execution, submitAndWait returns receipt.success === false and the code in receipt.result, such as insufficient_funds. These helpers turn either kind of code into a readable message.
import { AmadeusSDK, AmadeusSDKError, getTransactionErrorMessage } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
export async function submitTransfer(txPacked: Uint8Array): Promise<string> {
try {
const { hash, receipt } = await sdk.transaction.submitAndWait(txPacked)
if (!receipt.success) {
throw new Error(getTransactionErrorMessage(receipt.result ?? 'unknown'))
}
return hash
} catch (error) {
// Node rejections arrive as AmadeusSDKError with the error code as message
if (error instanceof AmadeusSDKError) {
throw new Error(getTransactionErrorMessage(error.message))
}
throw error
}
}
| Function | Looks up | Unknown code |
|---|---|---|
getTransactionErrorMessage(code) | Validation codes, then execution codes | 'Transaction failed: <code>' |
getValidationErrorMessage(code) | TRANSACTION_VALIDATION_ERROR_MESSAGES | 'Transaction validation failed: <code>' |
getExecutionErrorMessage(code) | TRANSACTION_EXECUTION_ERROR_MESSAGES | 'Transaction execution failed: <code>' |
For example, getTransactionErrorMessage('invalid_signature') returns 'Transaction signature is invalid' and getTransactionErrorMessage('insufficient_funds') returns 'Insufficient funds'. The codes these helpers know are the TransactionValidationError and TransactionExecutionError enums. The node's transaction pool can return other codes, such as invalid_tx_nonce or not_enough_tx_exec_balance, and those get the fallback message.
Timeouts, network failures and non-2xx HTTP responses are also thrown as AmadeusSDKError, but their message is not a bare node code: it reads like 'Request timeout after 30000ms' or 'HTTP 503: <reason>'.
Password encryption
Encrypt secrets such as a seed with a password before you store them. encryptWithPassword derives a 256-bit AES-GCM key with PBKDF2 (SHA-256, 100,000 iterations) and uses a fresh random salt and IV each time. All three output fields are Base64.
import { decryptWithPassword, encryptWithPassword, generateKeypair } from '@amadeus-protocol/sdk'
import type { EncryptedPayload } from '@amadeus-protocol/sdk'
const keypair = generateKeypair()
const encrypted: EncryptedPayload = await encryptWithPassword(keypair.privateKey, 'user-password')
// Store all three fields; each is Base64
localStorage.setItem('vault', JSON.stringify(encrypted))
const stored = localStorage.getItem('vault')
if (stored) {
const payload = JSON.parse(stored) as EncryptedPayload
const privateKey = await decryptWithPassword(payload, 'user-password')
console.log(privateKey === keypair.privateKey) // true
}
| Function | Signature |
|---|---|
encryptWithPassword | (plaintext: string, password: string) => Promise<EncryptedPayload> ({ encryptedData, iv, salt }) |
decryptWithPassword | (payload: EncryptedPayload, password: string) => Promise<string>. Throws 'Decryption failed. Incorrect password or corrupted data.' |
deriveKey | (password: string, salt: Uint8Array | ArrayBuffer, iterations = 100000) => Promise<CryptoKey> |
generateSalt | () => Uint8Array (16 bytes) |
generateIV | () => Uint8Array (12 bytes) |
To store a recovery phrase next to its seed, wrap both with encodeVaultSecret before encrypting. See Recovery phrases.
Contract state values
Contract storage values come back as bytes. parseStateNumber reads UTF-8 digits first and falls back to little-endian binary; it returns 0 for empty or missing values. parseStateString decodes UTF-8 and returns null for missing values.
import { parseStateNumber, parseStateString } from '@amadeus-protocol/sdk'
const encoder = new TextEncoder()
console.log(parseStateNumber(encoder.encode('42'))) // 42 (UTF-8 digits)
console.log(parseStateNumber(new Uint8Array([0x2a, 0x00]))) // 42 (little-endian bytes)
console.log(parseStateNumber(null)) // 0
console.log(parseStateString(encoder.encode('AMA'))) // 'AMA'
console.log(parseStateString(undefined)) // null
Reading whole prefixes (getPrefixEntries, decodeContractState, readAllPrefixPages) is covered in Contract state.
Constants
| Constant | Value |
|---|---|
SDK_VERSION | '1.8.0' (also AmadeusSDK.getVersion()) |
AMADEUS_PUBLIC_KEY_BYTE_LENGTH | 48 |
AMADEUS_SEED_BYTE_LENGTH | 64 |
AMA_TOKEN_DECIMALS | 9 |
AMA_TOKEN_DECIMALS_MULTIPLIER | 1000000000 |
MIN_TRANSFERABLE_AMOUNT | 0.000000001 (1 atomic unit) |
AMA_TRANSFER_FEE | 0.02, a conservative per-transfer reserve in AMA. The chain charges less, see Transaction fees |
NODE_API_URL | 'https://mainnet-rpc.ama.one/api' (default baseUrl) |
EXPLORER_URL | 'https://explorer.ama.one' |
DEFAULT_TIMEOUT | 30000 (ms, default request timeout) |
ACTIVITY_PROBE_TIMEOUT_MS | 8000 (ms, see Recovery phrases) |
Network constants (NetworkType, NETWORK_URLS, NETWORK_EXPLORER_URLS, NETWORK_CONFIGS, TESTNET_FAUCET_URL) are listed in Networks and testnet.
Next steps
- Recovery phrases: generate, validate and import BIP39 phrases
- Networks and testnet: connect to testnet and sign for it
- Examples: complete programs
- Best practices: security and development guidelines
- API modules: the node API through
AmadeusSDK