8. Best Practices
Security and development best practices for @amadeus-protocol/sdk 1.8.0.
Security
Private Key Management
Never:
- Commit private keys or recovery phrases to version control
- Log private keys in the console or in files
- Share private keys with anyone
- Store private keys in plain text
- Send private keys over unencrypted channels
Always:
- Load private keys from environment variables or a secret store
- Encrypt private keys at rest
- Use separate keys for development (testnet) and production (mainnet)
- Restrict who and what can read the keys
import { TransactionBuilder } from '@amadeus-protocol/sdk'
// read the seed from the environment, never from source code
const seed = process.env.AMADEUS_SEED
if (!seed) throw new Error('AMADEUS_SEED not set')
const builder = new TransactionBuilder(seed)
Password-Based Encryption
Encrypt seeds before you store them. encryptWithPassword uses AES-GCM with a key derived by PBKDF2 and returns encryptedData, iv and salt as Base64. Keep all three: decryption needs every one of them.
import { encryptWithPassword, decryptWithPassword } from '@amadeus-protocol/sdk'
declare const seed: string
declare const userPassword: string
declare const secureStorage: { save(value: object): Promise<void> }
const encrypted = await encryptWithPassword(seed, userPassword)
await secureStorage.save(encrypted)
// decrypt only when you need to sign
const decrypted = await decryptWithPassword(encrypted, userPassword)
Recovery Phrases
Since 1.4.0, mnemonicToSeedBase58 derives the standard EIP-2333 account (m/12381'/36969'/0'/0'/0'), the same one as the hub, Prime Hub and cli-wallet. A phrase restored with 1.3.0 or earlier opened a different, legacy account.
- Validate a phrase with
validateMnemonicbefore deriving anything from it. - When importing a phrase that may predate 1.4.0, use
resolveMnemonicImportso the user lands on the account that has history. - When you know the address the phrase should open, use
resolveCandidateForAddress.
See Recovery phrases.
Address Validation
Validate addresses before you send to them. The SDK only checks the Base58 alphabet, and the node answers a balance query for a wrong-length address with a zero balance instead of an error.
import { isValidAddress, validateAddress } from '@amadeus-protocol/sdk'
declare const recipient: string
// a valid address is Base58 that decodes to 48 bytes
if (!isValidAddress(recipient)) {
const result = validateAddress(recipient)
throw new Error(result.valid ? 'Invalid address' : result.error)
}
Transaction Verification
Build the transaction unsigned, check what it does, then sign it.
import { TransactionBuilder, toBase58 } from '@amadeus-protocol/sdk'
declare const seed: string
declare const recipient: string
const builder = new TransactionBuilder(seed)
const unsignedTx = builder.buildTransfer({ recipient, amount: 1.5, symbol: 'AMA' })
// Coin.transfer args: recipient bytes, atomic amount, symbol
const [recipientBytes, atomicAmount, symbol] = unsignedTx.tx.action.args
console.log('Recipient:', recipientBytes instanceof Uint8Array ? toBase58(recipientBytes) : recipientBytes)
console.log('Amount (atomic):', atomicAmount)
console.log('Symbol:', symbol)
const { txHash, txPacked } = builder.sign(unsignedTx)
Error Handling
How Errors Arrive
Every SDK method resolves with the data on success and throws an AmadeusSDKError on failure. There is no error field to check on a successful response: the SDK removes the node's error: 'ok' before it returns. error.status and error.message tell the cases apart:
| Case | status | message |
|---|---|---|
| Input rejected before sending (for example an address that is not Base58) | undefined | Schema error text |
Node answered 200 with an error code (for example a rejected submit) | 400 | The code itself, such as invalid_signature |
Node answered 200 with not_found | 404 | Resource not found |
| Node answered with an HTTP error | The HTTP status | HTTP <status>: <code or text>, such as HTTP 404: not_found |
No response before timeout | 408 | Request timeout after <timeout>ms |
Request aborted by sdk.cancel() | 0 | Request cancelled |
| Network failure | 0 | Request failed: <reason> |
error.response holds the node's parsed error body when there is one. To get the bare code whatever the case, strip the HTTP prefix: error.message.replace(/^HTTP \d+: /, '').
Two Kinds of Transaction Errors
A transaction can fail in two places, and you need to handle both:
- At submission. The node refuses the transaction and
submitorsubmitAndWaitthrows. Nothing was included and no nonce was used. The node's transaction pool returns codes such asinvalid_signature,invalid_tx_nonce,not_enough_tx_exec_balance(the balance cannot cover the transaction's execution budget),not_enough_txpool_balance(pending transactions from the same signer already reserve the balance),tx_exceeds_budgetandtxpool_full. Malformed transactions get a structure code such astoo_largeorinvalid_hash(most are listed inTransactionValidationError). - At execution. The transaction was included but the contract call failed.
submitAndWaitresolves normally withreceipt.success === false, andreceipt.resultholds aTransactionExecutionErrorcode, such asinsufficient_fundsfor a transfer larger than the balance.
import {
AmadeusSDK,
AmadeusSDKError,
getExecutionErrorMessage,
getTransactionErrorMessage
} from '@amadeus-protocol/sdk'
declare const txPacked: Uint8Array
const sdk = new AmadeusSDK()
try {
const { hash, receipt } = await sdk.transaction.submitAndWait(txPacked)
if (receipt.success) {
console.log('Executed:', hash)
} else {
console.error('Included but failed:', getExecutionErrorMessage(receipt.result ?? 'unknown'))
}
} catch (error) {
if (!(error instanceof AmadeusSDKError)) throw error
const code = error.message.replace(/^HTTP \d+: /, '')
switch (code) {
case 'invalid_signature':
console.error('Wrong key, or signed for another network')
break
case 'invalid_tx_nonce':
console.error('Nonce already used: build a new transaction')
break
case 'not_enough_tx_exec_balance':
console.error('Not enough AMA to pay for execution')
break
case 'txpool_full':
console.error('The node is busy: retry later')
break
default:
console.error(getTransactionErrorMessage(code), error.status)
}
}
Retry Logic
Retry only errors that can go away: network failures, timeouts, 5xx replies and txpool_full. Retry with the same txPacked. The node accepts a transaction it already holds in its pool without adding it twice, and a transaction can execute only once. Never build and sign a new transaction because the first call failed: if the first one landed, both execute.
import { AmadeusSDK, AmadeusSDKError, type SubmitTransactionResponse } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
function isTransient(error: unknown): boolean {
if (!(error instanceof AmadeusSDKError)) return false
const status = error.status ?? 0
if (error.message === 'Request cancelled') return false
return status === 0 || status === 408 || status >= 500 || error.message === 'txpool_full'
}
async function submitWithRetry(
txPacked: Uint8Array,
attempt = 1,
maxAttempts = 3
): Promise<SubmitTransactionResponse> {
try {
return await sdk.transaction.submit(txPacked)
} catch (error) {
if (!isTransient(error) || attempt >= maxAttempts) throw error
await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** (attempt - 1)))
return submitWithRetry(txPacked, attempt + 1, maxAttempts)
}
}
If a retry is rejected with invalid_tx_nonce, the first attempt most likely executed: look the hash up with sdk.transaction.get(txHash) before you do anything else.
Transaction Management
Nonce Management
The SDK derives the nonce from the build time: Date.now() * 1_000_000. The node only accepts a nonce higher than the last one the signer used. So:
- Build transactions for one signer one after another, never two in the same millisecond: they would share a nonce and only one could execute.
- Submit them in the order you built them. If a later transaction executes first, the earlier ones become invalid.
- A rejected
invalid_tx_noncemeans the nonce is used: build a new transaction instead of resubmitting.
import { AmadeusSDK, TransactionBuilder } from '@amadeus-protocol/sdk'
declare const seed: string
declare const recipients: string[]
const sdk = new AmadeusSDK()
const builder = new TransactionBuilder(seed)
// build and submit sequentially, so each nonce is newer than the last
for (const recipient of recipients) {
const { txPacked } = builder.transfer({ recipient, amount: 1, symbol: 'AMA' })
await sdk.transaction.submit(txPacked)
}
Balance Checking
Check the balance first. The node locks a 0.01 AMA budget on top of the amount and refunds what the transfer does not use (see Transaction fees). Holding back AMA_TRANSFER_FEE (0.02 AMA), the reserve the extension and mobile wallet use, covers it.
import { AMA_TRANSFER_FEE, AmadeusSDK, TransactionBuilder, toAtomicAma } from '@amadeus-protocol/sdk'
declare const seed: string
declare const senderAddress: string
const sdk = new AmadeusSDK()
const builder = new TransactionBuilder(seed)
async function safeTransfer(recipient: string, amount: number) {
const { balance } = await sdk.wallet.getBalance(senderAddress, 'AMA')
if (balance.flat < toAtomicAma(amount) + toAtomicAma(AMA_TRANSFER_FEE)) {
throw new Error('Insufficient balance')
}
const { txPacked } = builder.transfer({ recipient, amount, symbol: 'AMA' })
return sdk.transaction.submitAndWait(txPacked)
}
Amount Precision
Convert with the SDK helpers instead of multiplying by hand. AMA has 9 decimals: toAtomicAma rounds any digit past the ninth (toAtomicAma(0.1234567899) is 123456790).
import { toAtomicAma, fromAtomicAma } from '@amadeus-protocol/sdk'
const atomic = toAtomicAma(1.5) // 1500000000
const ama = fromAtomicAma(atomic) // 1.5
Atomic amounts can exceed Number.MAX_SAFE_INTEGER (about 9 million AMA). The largest mainnet balances already do, so the JSON number in balance.flat or a richlist entry's flat is not exact for them, and fromAtomicAma throws above that limit. Show float, compare with care, and read staking amounts from their bigint *Flat fields with flatToAma.
Configuration
Environment-Based Configuration
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({
baseUrl: process.env.AMADEUS_API_URL ?? 'https://mainnet-rpc.ama.one/api',
timeout: Number(process.env.AMADEUS_TIMEOUT_MS ?? 30000)
})
The SDK resolves every endpoint against the origin of baseUrl (/api/... paths), so a URL with an extra path prefix does not work. NETWORK_URLS and NETWORK_CONFIGS[...].rpcUrl hold the host only; append /api when you build baseUrl from them.
Request Timeouts
The default timeout is 30 seconds (DEFAULT_TIMEOUT). It covers the time until the response headers arrive. A timed-out request throws AmadeusSDKError with status 408.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
// short timeout for quick queries
const quickSdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api', timeout: 5000 })
// longer timeout for submitAndWait
const txSdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api', timeout: 60000 })
Code Organization
Separate Concerns
import { AmadeusSDK, TransactionBuilder } from '@amadeus-protocol/sdk'
export class WalletManager {
constructor(
private sdk: AmadeusSDK,
private builder: TransactionBuilder
) {}
async getBalance(address: string, symbol: string) {
return this.sdk.wallet.getBalance(address, symbol)
}
async transfer(recipient: string, amount: number, symbol: string) {
const { txPacked } = this.builder.transfer({ recipient, amount, symbol })
return this.sdk.transaction.submitAndWait(txPacked)
}
}
export class ChainQuerier {
constructor(private sdk: AmadeusSDK) {}
async getCurrentHeight() {
const { entry } = await this.sdk.chain.getTip()
return entry.header.height
}
async getStats() {
const { stats } = await this.sdk.chain.getStats()
return stats
}
}
Type Safety
Every response is typed. Import the types you pass around:
import type { ChainEntry, Transaction, WalletBalance } from '@amadeus-protocol/sdk'
function describeTransaction(tx: Transaction) {
return `${tx.hash}: ${tx.tx.action.contract}.${tx.tx.action.function}, success ${tx.receipt.success}`
}
function describeEntry(entry: ChainEntry) {
return `${entry.hash} at height ${entry.header.height}`
}
function describeBalance({ balance }: WalletBalance) {
return `${balance.float} ${balance.symbol}`
}
Testing
Testnet Usage
Test on testnet first. Testnet signs transactions under its own domain separation tag, so a transaction signed for mainnet is rejected there with invalid_signature, and the reverse. TransactionBuilder and createContract().connect() sign for mainnet unless you pass a network. For testnet, pass NetworkType.TESTNET:
import { AmadeusSDK, NETWORK_URLS, NetworkType, TransactionBuilder } from '@amadeus-protocol/sdk'
declare const seed: string
declare const recipient: string
// NETWORK_URLS holds the host only
const testnet = new AmadeusSDK({ baseUrl: `${NETWORK_URLS[NetworkType.TESTNET]}/api` })
const builder = new TransactionBuilder(seed, { network: NetworkType.TESTNET })
const { txHash, txPacked } = builder.transfer({ recipient, amount: 1, symbol: 'AMA' })
const { receipt } = await testnet.transaction.submitAndWait(txPacked)
console.log(txHash, receipt.success)
To sign a ContractCall without a builder, use signContractCall(seed, call, NetworkType.TESTNET). buildAndSignRaw, signUnsigned and the static TransactionBuilder methods take the same optional network argument. Get test AMA from the faucet at TESTNET_FAUCET_URL (https://mcp.ama.one/testnet-faucet): 100 AMA per claim, once per 24 hours per IP. See Networks and testnet.
Mock Implementations
Depend on the few methods you use, then pass a real AmadeusSDK in production and a small mock in tests:
import type { AmadeusSDK } from '@amadeus-protocol/sdk'
type AmadeusReader = {
wallet: Pick<AmadeusSDK['wallet'], 'getBalance'>
transaction: Pick<AmadeusSDK['transaction'], 'submit'>
}
const mockSdk: AmadeusReader = {
wallet: {
getBalance: async () => ({ balance: { float: 100, flat: 100_000_000_000, symbol: 'AMA' } })
},
transaction: {
submit: async () => ({ hash: 'mock-hash' })
}
}
async function readBalance(sdk: AmadeusReader, address: string) {
const { balance } = await sdk.wallet.getBalance(address, 'AMA')
return balance.float
}
console.log(await readBalance(mockSdk, 'any-address'))
Performance
Batch Operations
Run independent reads in parallel. This needs 1.7.0 or later: earlier versions aborted the request in flight whenever a new one started on the same client and reported it as a timeout. sdk.cancel() aborts every request in flight.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
declare const addresses: string[]
const sdk = new AmadeusSDK()
// parallel reads on one client (1.7.0+)
const balances = await Promise.all(
addresses.map((address) => sdk.wallet.getBalance(address, 'AMA'))
)
Keep transactions from one signer sequential (see Nonce Management).
Caching
Cache data that changes slowly. Entries arrive about every 500 ms, so a tip cached for a few seconds is already behind.
import type { AmadeusSDK, ChainEntry } from '@amadeus-protocol/sdk'
export class CachedChainQuerier {
private cache: { entry: ChainEntry; fetchedAt: number } | null = null
constructor(
private sdk: AmadeusSDK,
private ttlMs = 2000
) {}
async getTip(): Promise<ChainEntry> {
if (this.cache && Date.now() - this.cache.fetchedAt < this.ttlMs) {
return this.cache.entry
}
const { entry } = await this.sdk.chain.getTip()
this.cache = { entry, fetchedAt: Date.now() }
return entry
}
}
Logging
Structured Logging
import type { SubmitAndWaitTransactionResponse } from '@amadeus-protocol/sdk'
function logTransaction({ hash, metadata, receipt }: SubmitAndWaitTransactionResponse) {
console.log(
JSON.stringify({
type: 'transaction',
hash,
height: metadata.entry_height,
success: receipt.success,
result: receipt.result,
timestamp: new Date().toISOString()
})
)
}
Sensitive Data
Log only public data: transaction hashes, addresses, amounts. Never log a seed, a recovery phrase, a password or a decrypted vault.