# 9. Troubleshooting

Common issues and solutions when using the Amadeus Protocol SDK.

### Installation Issues

#### "Module not found" Error

**Problem**: Cannot find module '@amadeus-protocol/sdk'

**Solutions**:

1. Ensure the package is installed:

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

   ```json
   {
   	"dependencies": {
   		"@amadeus-protocol/sdk": "^1.0.0"
   	}
   }
   ```
3. Clear cache and reinstall:

   ```bash
   npm cache clean --force
   rm -rf node_modules package-lock.json
   npm install
   ```

#### TypeScript Errors

**Problem**: Type errors when importing

**Solutions**:

1. Ensure TypeScript is installed:

   ```bash
   npm install -D typescript @types/node
   ```
2. Check `tsconfig.json`:

   ```json
   {
   	"compilerOptions": {
   		"moduleResolution": "node",
   		"esModuleInterop": true
   	}
   }
   ```
3. Restart your TypeScript server/IDE

#### Node.js Version Issues

**Problem**: Errors related to Node.js version

**Solutions**:

1. Check Node.js version:

   ```bash
   node --version
   ```
2. Update to Node.js 20+ if needed
3. Use a version manager like `nvm`:

   ```bash
   nvm install 20
   nvm use 20
   ```

### Runtime Errors

#### "Invalid Base58 string"

**Problem**: Error when decoding Base58 addresses or keys

**Causes**:

* Invalid Base58 encoding
* Missing or extra characters
* Wrong string format

**Solutions**:

```typescript
import { fromBase58 } from '@amadeus-protocol/sdk'

function validateBase58(str: string): boolean {
	try {
		fromBase58(str)
		return true
	} catch {
		return false
	}
}

// Validate before use
if (!validateBase58(address)) {
	throw new Error('Invalid Base58 address')
}
```

#### "Transaction failed: insufficient balance"

**Problem**: Transaction rejected due to insufficient funds

**Solutions**:

1. Check balance before transferring:

   ```typescript
   const balance = await sdk.wallet.getBalance(address, 'AMA')
   if (balance.balance.float < amount + fee) {
   	throw new Error('Insufficient balance')
   }
   ```
2. Account for transaction fees:

   ```typescript
   const requiredAmount = amount + AMA_TRANSFER_FEE
   ```

#### "Request timeout"

**Problem**: API requests timing out

**Causes**:

* Network connectivity issues
* Node is slow or overloaded
* Timeout too short

**Solutions**:

1. Increase timeout:

   ```typescript
   const sdk = new AmadeusSDK({
   	baseUrl: 'https://nodes.amadeus.bot/api',
   	timeout: 60000 // 60 seconds
   })
   ```
2. Implement retry logic:

   ```typescript
   async function submitWithRetry(txPacked: Uint8Array, maxRetries = 3) {
   	for (let i = 0; i < maxRetries; i++) {
   		try {
   			return await sdk.transaction.submit(txPacked)
   		} catch (error) {
   			if (i === maxRetries - 1) throw error
   			await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)))
   		}
   	}
   }
   ```

#### "Invalid transaction structure"

**Problem**: Transaction validation fails

**Causes**:

* Transaction not properly built
* Invalid arguments
* Wrong contract/function names

**Solutions**:

1. Always use `TransactionBuilder`:

   ```typescript
   const builder = new TransactionBuilder(privateKey)
   const { txPacked } = builder.transfer({
   	recipient: address,
   	amount: amount,
   	symbol: 'AMA'
   })
   ```
2. Validate inputs:

   ```typescript
   function validateTransferInput(input: TransferInput): boolean {
   	return (
   		isValidAddress(input.recipient) && input.amount > 0 && typeof input.symbol === 'string'
   	)
   }
   ```

#### "Invalid signature"

**Problem**: Transaction signature validation fails

**Causes**:

* Wrong private key used
* Transaction modified after signing
* Corrupted transaction data

**Solutions**:

1. Verify private key matches address:

   ```typescript
   const publicKey = derivePublicKeyFromSeedBase58(privateKey)
   if (publicKey !== expectedAddress) {
   	throw new Error('Private key does not match address')
   }
   ```
2. Don't modify transactions after signing:

   ```typescript
   // ✅ Good: Use txPacked directly
   await sdk.transaction.submit(txPacked)

   // ❌ Bad: Don't modify after signing
   // const modified = modifyTransaction(txPacked)
   ```

### API Errors

#### 404 Not Found

**Problem**: Resource not found

**Solutions**:

```typescript
try {
	const balance = await sdk.wallet.getBalance(address, 'AMA')
} catch (error) {
	if (error instanceof AmadeusSDKError && error.status === 404) {
		console.log('Address not found or has no balance')
		// Handle gracefully
	}
}
```

#### 400 Bad Request

**Problem**: Invalid request parameters

**Solutions**:

1. Validate inputs before API calls:

   ```typescript
   function isValidAddress(address: string): boolean {
   	try {
   		const bytes = fromBase58(address)
   		return bytes.length === 48
   	} catch {
   		return false
   	}
   }
   ```
2. Check error response for details:

   ```typescript
   catch (error) {
     if (error instanceof AmadeusSDKError) {
       console.error('Error details:', error.response)
     }
   }
   ```

#### Network Errors

**Problem**: Network connectivity issues

**Solutions**:

1. Check network connectivity:

   ```typescript
   async function checkConnection(): Promise<boolean> {
   	try {
   		await sdk.chain.getTip()
   		return true
   	} catch {
   		return false
   	}
   }
   ```
2. Use different node URL:

   ```typescript
   const sdk = new AmadeusSDK({
   	baseUrl: 'https://backup-node.com/api'
   })
   ```

### Transaction Issues

#### Transaction Stuck/Pending

**Problem**: Transaction submitted but not confirming

**Solutions**:

1. Check transaction status:

   ```typescript
   const tx = await sdk.transaction.get(txHash)
   console.log('Transaction status:', tx.receipt)
   ```
2. Wait for confirmation:

   ```typescript
   try {
   	const result = await sdk.transaction.submitAndWait(txPacked)
   	console.log('Confirmed:', result.metadata?.entry_hash)
   } catch (error) {
   	console.error('Confirmation timeout')
   }
   ```

#### Nonce Collisions

**Problem**: Multiple transactions with same nonce

**Causes**:

* Transactions submitted too quickly
* Timestamp-based nonce collision

**Solutions**:

1. Add delays between transactions:

   ```typescript
   async function submitMultiple(txs: Uint8Array[]) {
   	for (const tx of txs) {
   		await sdk.transaction.submit(tx)
   		await new Promise((resolve) => setTimeout(resolve, 100))
   	}
   }
   ```

#### Wrong Amount

**Problem**: Amount not matching expected value

**Causes**:

* Precision loss from manual calculation
* Wrong conversion

**Solutions**:

1. Always use conversion functions:

   ```typescript
   // ✅ Good
   const atomic = toAtomicAma(1.5)

   // ❌ Bad
   const atomic = 1.5 * 1000000000
   ```
2. Verify amounts:

   ```typescript
   const amount = 10.5
   const atomic = toAtomicAma(amount)
   const back = fromAtomicAma(atomic)
   console.log('Matches:', amount === back) // Should be true
   ```

### Encryption Issues

#### "Decryption failed"

**Problem**: Cannot decrypt encrypted data

**Causes**:

* Wrong password
* Corrupted encrypted data
* Missing IV or salt

**Solutions**:

1. Verify password:

   ```typescript
   try {
   	const decrypted = await decryptWithPassword(encrypted, password)
   } catch (error) {
   	if (error.message.includes('decryption')) {
   		console.error('Wrong password or corrupted data')
   	}
   }
   ```
2. Ensure all components are present:

   ```typescript
   const encrypted = {
   	encryptedData: stored.encryptedData,
   	iv: stored.iv,
   	salt: stored.salt
   }
   ```

### Debugging

#### Enable Verbose Logging

```typescript
// Log all API requests
const originalGet = sdk.client.get.bind(sdk.client)
sdk.client.get = async (...args) => {
  console.log('GET:', args)
  return originalGet(...args)
}

// Log transaction building
const builder = new TransactionBuilder(privateKey)
const unsignedTx = builder.buildTransfer({...})
console.log('Unsigned transaction:', {
  nonce: unsignedTx.tx.nonce.toString(),
  action: unsignedTx.tx.action,
  hash: toBase58(unsignedTx.hash)
})
```

#### Transaction Inspection

```typescript
// Inspect transaction before signing
const unsignedTx = builder.buildTransfer({
	recipient: address,
	amount: amount,
	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

#### Check Documentation

1. Review API Reference
2. Check Examples
3. Read Best Practices

#### Common Resources

* **GitHub Issues**: Report bugs and request features
* **Documentation**: Complete API reference
* **Examples**: Real-world usage examples

#### Reporting Issues

When reporting issues, include:

1. SDK version
2. Node.js version
3. Error message and stack trace
4. Code snippet that reproduces the issue
5. Expected vs actual behavior

### Next Steps

* [**Best Practices**: Security and development guidelines](/sdk/8.-best-practices.md)
* [**Examples**: Real-world usage examples](/sdk/7.-examples.md)
* [**API Modules**: Complete API reference](/sdk/5.-api-modules.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.ama.one/sdk/9.-troubleshooting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
