Skip to main content

9. Troubleshooting

Common issues and solutions when using @amadeus-protocol/sdk. Most of them are fixed by upgrading to the latest version, 1.8.0:

npm install @amadeus-protocol/sdk@latest

AmadeusSDK.getVersion() returns the installed version (it reported 1.2.0 on 1.3.0 to 1.5.0; fixed in 1.6.0).

Installation Issues​

ERR_MODULE_NOT_FOUND for dist/types, dist/client, etc. (1.0.x only)​

Problem: Running plain node against an app that imports @amadeus-protocol/sdk fails with:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/path/to/node_modules/@amadeus-protocol/sdk/dist/types' imported from /path/to/node_modules/@amadeus-protocol/sdk/dist/index.js

Cause: Versions 1.0.0 to 1.0.8 shipped compiled ESM without .js extensions on relative imports. The Node.js ESM resolver requires them. Bundlers (Vite, webpack, esbuild, Metro) tolerate the missing extensions, so the error only shows up under plain node.

Solution: Upgrade to 1.1.0 or later. If you cannot upgrade yet, run your entry file with tsx (npx tsx your-entry.ts) or through a bundler.

ERR_PACKAGE_PATH_NOT_EXPORTED (CommonJS projects)​

Problem: require('@amadeus-protocol/sdk') fails with:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in .../node_modules/@amadeus-protocol/sdk/package.json

Cause: The package is ESM only. Its exports map has an import entry and no require entry, so CommonJS require() cannot load it.

Solutions:

  1. Make your project ESM: add "type": "module" to package.json (or name the file .mjs / .mts) and use import.

  2. From CommonJS code you cannot convert, load it with a dynamic import:

    async function loadSdk() {
    const { AmadeusSDK } = await import('@amadeus-protocol/sdk')
    return new AmadeusSDK()
    }
  3. Run through tsx or a bundler.

TypeScript Errors​

Problem: In a package without "type": "module", "module": "Node16" reports TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module. With "module": "NodeNext" (TypeScript 5.9) or "CommonJS" the build typechecks, but the emitted require() fails at runtime with ERR_PACKAGE_PATH_NOT_EXPORTED.

Solution: Compile as ESM. With Node.js, set "type": "module" in package.json and:

{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2022"
}
}

With a bundler or tsx, "module": "ESNext" and "moduleResolution": "Bundler" also work. The older "moduleResolution": "node" typechecks, but if it emits CommonJS the output fails at runtime as described above.

"Module not found" Error​

Problem: Cannot find module @amadeus-protocol/sdk.

Solutions:

  1. Install the package in the project that imports it:

    npm install @amadeus-protocol/sdk
  2. Check package.json:

    {
    "dependencies": {
    "@amadeus-protocol/sdk": "^1.8.0"
    }
    }
  3. Reinstall from scratch:

    rm -rf node_modules package-lock.json
    npm install

Node.js Version Issues​

The SDK requires Node.js 20 or later (engines.node is >=20.0.0). Check with node --version and upgrade if needed, for example with nvm install 20 && nvm use 20.

Runtime Errors​

"Expected Base58 encoded address string"​

Problem: A call throws AmadeusSDKError with status undefined and a message such as:

Base58Address
└─ Predicate refinement failure
└─ Expected Base58 encoded address string, actual "0OIl"

Cause: The SDK checks inputs before sending. Base58 has no 0, O, I or l.

Solution: Validate user input first. The SDK only checks the alphabet: a Base58 string of the wrong length passes, and the node then answers a balance query for it with a zero balance. Use isValidAddress, which also checks that the address decodes to 48 bytes:

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

declare const address: string

if (!isValidAddress(address)) {
throw new Error('Invalid address')
}

"Request timeout after 30000ms"​

Problem: A request throws AmadeusSDKError with status 408.

Causes: The node is slow or unreachable, or the timeout is too short. The timeout covers the time until the response headers arrive.

Solutions:

  1. Increase the timeout:

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

    const sdk = new AmadeusSDK({
    baseUrl: 'https://mainnet-rpc.ama.one/api',
    timeout: 60000
    })
  2. Retry transient failures with the same signed transaction. See Retry Logic.

"Request failed: fetch failed"​

Problem: A call throws AmadeusSDKError with status 0 and the message Request failed: fetch failed.

Cause: No response arrived at all: the host in baseUrl is wrong or does not resolve, or the machine is offline.

Solutions:

  1. Check baseUrl. The public endpoints are https://mainnet-rpc.ama.one/api and https://testnet-rpc.ama.one/api (see Networks).

  2. Test the connection with a cheap read:

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

    async function checkConnection(sdk: AmadeusSDK): Promise<boolean> {
    try {
    await sdk.chain.getTip()
    return true
    } catch {
    return false
    }
    }

    console.log(await checkConnection(new AmadeusSDK()))
  3. Retry transient failures. See Retry Logic.

"Request cancelled" or timeouts when making parallel calls​

Problem: With Promise.all (or any overlapping calls) on one AmadeusSDK instance, some requests fail with a timeout or cancellation even though the node is healthy.

Cause: Before 1.7.0, AmadeusClient aborted the request in flight whenever a new one started, and reported it as a timeout.

Solution: Upgrade to 1.7.0 or later, where each request has its own controller. sdk.cancel() now aborts every request in flight; calls it aborts throw Request cancelled with status 0.

Custom RPC URL with a path prefix is ignored​

Problem: With baseUrl: 'https://example.com/amadeus/api', requests go to https://example.com/api/....

Cause: The SDK resolves its /api/... endpoint paths against the origin of baseUrl, so any path in between is dropped.

Solution: Serve the node API at /api on its own origin (host or port). addressHasActivity(apiBaseUrl, address) is the exception: it builds absolute URLs and keeps the prefix.

Transaction Errors​

Submission errors are thrown as AmadeusSDKError whose message is the node's code. Execution errors are not thrown: they arrive in receipt.result with receipt.success === false. See Two Kinds of Transaction Errors.

"invalid_signature"​

Problem: submit or submitAndWait throws invalid_signature.

Causes:

  • The transaction was signed for the other network. Since 1.3.0, testnet verifies transactions under its own signing domain (..._TX_TESTNET_). A TransactionBuilder created without a network, and createContract().connect() without one, sign for mainnet, so their output is rejected on testnet. Before 1.8.0 they had no network option at all.
  • The wrong private key was used for the signer.
  • The packed transaction was modified after signing.

Solutions:

  1. For testnet, sign with NetworkType.TESTNET:

    import { NetworkType, TransactionBuilder, buildCoinTransfer, signContractCall } from '@amadeus-protocol/sdk'

    declare const seed: string
    declare const recipient: string

    const builder = new TransactionBuilder(seed, { network: NetworkType.TESTNET })
    const { txPacked } = builder.transfer({ recipient, amount: 1, symbol: 'AMA' })

    // Or without a builder
    const signed = signContractCall(
    seed,
    buildCoinTransfer({ recipient, amount: 1, symbol: 'AMA' }),
    NetworkType.TESTNET
    )

    buildAndSignRaw, signUnsigned and the static TransactionBuilder methods take the same optional network argument. See Testnet usage.

  2. Check that the key matches the address you expect:

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

    declare const seed: string
    declare const expectedAddress: string

    if (derivePublicKeyFromSeedBase58(seed) !== expectedAddress) {
    throw new Error('Private key does not match address')
    }
  3. Submit txPacked exactly as the builder returned it.

"invalid_tx_nonce"​

Problem: The node rejects the transaction with invalid_tx_nonce.

Causes: The nonce is not higher than the last nonce the signer used. This happens when the same signed transaction is submitted after it already executed, when a transaction built later executed first, or when two transactions were built in the same millisecond (the nonce is Date.now() * 1_000_000).

Solution: Build a new transaction, and build and submit one signer's transactions one after another. See Nonce Management.

Insufficient balance​

There are two different errors:

  • not_enough_tx_exec_balance is thrown at submission: the balance cannot cover the transaction's 0.01 AMA budget. not_enough_txpool_balance means pending transactions from the same signer already reserve the balance; wait for them to execute.
  • insufficient_funds appears in receipt.result after execution: the transaction was included, but the transfer amount was larger than the balance left after the budget was locked. Its costs are still charged.

Check the balance before you send. It must cover the amount plus the 0.01 AMA budget (see Transaction fees); holding back the 0.02 AMA AMA_TRANSFER_FEE reserve covers it:

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

declare const address: string
declare const amount: number

const sdk = new AmadeusSDK()
const { balance } = await sdk.wallet.getBalance(address, 'AMA')

if (balance.flat < toAtomicAma(amount) + toAtomicAma(AMA_TRANSFER_FEE)) {
throw new Error('Insufficient balance')
}

"txpool_full"​

The node's transaction pool is out of space. Retry the same txPacked later.

Invalid transaction structure​

Problem: The node rejects a transaction with a structure code such as too_large, invalid_hash, op_must_be_call, arg_must_be_binary or args_length_cannot_exceed_16.

Solutions:

  1. Build transactions with TransactionBuilder, buildCoinTransfer / signContractCall or createContract(ABI) instead of encoding them by hand.
  2. Pass contract arguments as strings or Uint8Array. Amounts go in atomic units as strings (toAtomicAma(amount).toString()).
  3. Turn the code into a readable message with getTransactionErrorMessage(code).

Transaction Stuck or Pending​

Problem: submit succeeded, but the transaction does not show up.

Solutions:

  1. Look it up by hash with sdk.transaction.get(hash). metadata.status tells you where it is: 'pending' while it waits in the answering node's pool (no receipt yet), 'committed' once it is in an entry, and 'finalized' once that entry is rooted. A hash the node does not know throws with status 404:

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

    declare const txHash: string

    const sdk = new AmadeusSDK()

    try {
    const tx = await sdk.transaction.get(txHash)
    if (tx.metadata.status === 'pending') console.log('In the pool, not executed yet')
    else console.log('Included at height', tx.metadata.entry_height, tx.metadata.status, tx.receipt.success)
    } catch (error) {
    if (error instanceof AmadeusSDKError && error.status === 404) console.log('Unknown to this node')
    else throw error
    }
  2. Use submitAndWait next time. The node waits for the transaction for about 6 seconds; if the call fails, look the hash up before you sign anything new, so you do not send twice.

  3. If an invalid_tx_nonce comes back for a resubmission, the transaction already executed or was replaced by a later nonce.

Wrong Amount​

Causes: Manual multiplication (1.5 * 1000000000) or reading flat above Number.MAX_SAFE_INTEGER.

Solutions:

  1. Convert with toAtomicAma and fromAtomicAma. AMA has 9 decimals, and toAtomicAma rounds digits past the ninth.
  2. fromAtomicAma throws Value exceeds maximum safe integer above about 9 million AMA. For large balances show balance.float; for staking amounts use the bigint *Flat fields with flatToAma.

Read Errors​

"HTTP 404: not_found" or "Resource not found"​

Both mean the node has no such resource, and both have status 404. The message depends on how the node answered: an HTTP 404 gives HTTP 404: not_found, and a 200 reply with error: 'not_found' gives Resource not found. Check error.status, not the message:

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

declare const error: unknown

if (error instanceof AmadeusSDKError && error.status === 404) {
console.log('Not found')
}

A balance query never returns 404: an unknown address has a zero balance.

Staked balances missing, or "Expected MAP type, got object"​

Problem: sdk.staking.* throws, wallets show no stake, decodeContractState throws Expected MAP type, got object, or sdk.contract.getPrefix() returns unreadable text.

Causes: /api/contract/get_prefix answers with binary VecPack. Before 1.2.0, a prefix with no matches (an account that never staked) failed to decode. Since node commit 78b5e9c the endpoint answers in pages of {rows, cursor}, which only 1.7.0 and later decode. getPrefix() parses the body as text, so it cannot read it at all.

Solution: Upgrade to 1.7.0 or later and read prefixes with sdk.contract.getPrefixEntries(prefix), which follows every page. If you make your own HTTP calls, use readAllPrefixPages with prefixPagePath. See Contract state.

getTransactionEventsByAccount items have no txid or amount​

Problem: On 1.7.0 and earlier, the TransactionEvent type (type, txid, amount, symbol, timestamp) does not match the data, the cursor is null, or the next page repeats the first.

Cause: The node returns full transactions (with hash, tx, receipt, and metadata.tx_event set to sent or recv). It pages only when type is set, and it reads a Base58 cursor from cursor_b58, while those SDKs sent it as cursor.

Solution: Upgrade to 1.8.0, which types the answer as { cursor: string | null, txs: Transaction[] } and sends cursor as cursor_b58. Set type to TransactionEventType.SENT or RECEIVED to page. See getTransactionEventsByAccount. sdk.chain.getByFilter({ signer }) and getByFilter({ arg0 }) also work; see Get Transaction History.

contract.view returns invalid_bic_action​

Built-in contracts (Coin, LockupVault, LockupPrime, Nft and the others) have no read-only functions. sdk.contract.view with a function name the built-in contract does not handle, such as Coin.balance, resolves with { success: false, result: 'invalid_bic_action' }. Read built-in contract state with getPrefixEntries, contract.get or sdk.staking instead. Contracts you deploy are RISC-V programs and run on testnet only; see Smart contracts.

A deployed contract's Base58 address got the same answer on SDK 1.7.0 and earlier, which sent the address as text, so the node looked for a built-in contract by that name. Since 1.8.0 the SDK sends it as the 48-byte key.

Deprecated methods throw "... is deprecated"​

Current nodes do not serve the routes behind contract.validateBytecode, proof.getValidators and chain.getMetricsBlock. Before 1.8.0 they failed with HTTP 404: not_found. Since 1.8.0 they are deprecated and throw an AmadeusSDKError with status 404 whose message names the method, such as contract.validateBytecode is deprecated: .... validateBytecode and getValidators throw without sending a request. Use proof.getValidatorRecord(height) in place of getValidators.

proof.getContractStateProof(key, value) also throws a deprecation error, because the node no longer verifies values. Call it with the key only.

getByFilter fails with a large limit​

The node accepts at most 1,000 results per page and rejects a larger limit; through mainnet-rpc.ama.one this shows up as HTTP 520. Use limit 1,000 or less and follow the cursor.

Recovery Phrase Issues​

My recovery phrase opens a different or empty address​

Cause: Since 1.4.0, mnemonicToSeedBase58 derives the standard EIP-2333 account (m/12381'/36969'/0'/0'/0'). Wallets created with 1.3.0 or earlier used the raw BIP39 seed (legacy), which opens a different address for the same phrase. Seeds already stored in a vault are not affected.

Solution: Derive both accounts and open the one in use.

import {
addressHasActivity,
mnemonicToCandidateKeypairs,
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')

// both candidates, standard (eip2333) first
const [standard, legacy] = mnemonicToCandidateKeypairs(mnemonic)
console.log(standard.publicKey, legacy.publicKey)

// when the address is known
const match = knownAddress ? resolveCandidateForAddress(mnemonic, knownAddress) : null

// otherwise, let the chain decide
const result = await resolveMnemonicImport(mnemonic, (address) =>
addressHasActivity('https://mainnet-rpc.ama.one/api', address)
)
console.log(match?.derivation, result.reason, result.chosen?.publicKey)

resolveMnemonicImport opens an account only when the answer is clear (single-active or none-active); for both-active or check-failed it sets needsChoice, and you let the user pick. See Recovery phrases.

A pasted phrase fails validation​

Since 1.6.0, validateMnemonic and the derive functions collapse extra spaces and line breaks. On older versions, normalize the phrase first (trim, lowercase, single spaces), or upgrade and use normalizeMnemonic.

Encryption Issues​

"Decryption failed"​

Problem: decryptWithPassword throws Decryption failed. Incorrect password or corrupted data.

Causes: Wrong password, corrupted data, or a missing or swapped iv or salt.

Solutions:

  1. Catch the exact message:

    import { decryptWithPassword, type EncryptedPayload } from '@amadeus-protocol/sdk'

    declare const encrypted: EncryptedPayload
    declare const password: string

    try {
    await decryptWithPassword(encrypted, password)
    } catch (error) {
    if (error instanceof Error && error.message.startsWith('Decryption failed')) {
    console.error('Wrong password or corrupted data')
    }
    }
  2. Store and restore all three fields, encryptedData, iv and salt, exactly as encryptWithPassword returned them.

Debugging​

Log Every Request​

The SDK calls the global fetch, so you can wrap it while debugging:

const originalFetch = globalThis.fetch

globalThis.fetch = async (input, init) => {
console.log(init?.method ?? 'GET', String(input))
return originalFetch(input, init)
}

On an error, error.response holds the node's parsed reply.

Transaction Inspection​

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, symbol: 'AMA' })

console.log('Transaction details:', {
signer: toBase58(unsignedTx.tx.signer),
nonce: unsignedTx.tx.nonce.toString(),
contract: unsignedTx.tx.action.contract,
function: unsignedTx.tx.action.function,
args: unsignedTx.tx.action.args,
hash: toBase58(unsignedTx.hash)
})

Getting Help​

When reporting an issue, include the SDK version (AmadeusSDK.getVersion()), the Node.js version, the full error (message, status and response), a snippet that reproduces it, and the expected versus actual behavior.

Next Steps​