# 5. API Modules

Complete reference for all API modules in the Amadeus Protocol SDK.

### Overview

The SDK provides access to various API modules through the `AmadeusSDK` instance:

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

const sdk = new AmadeusSDK()

// Access API modules
sdk.chain // Chain API
sdk.wallet // Wallet API
sdk.transaction // Transaction API
sdk.contract // Contract API
sdk.epoch // Epoch API
sdk.peer // Peer API
sdk.proof // Proof API
```

### Chain API

Query blockchain data including chain tip, statistics, entries, and transaction events.

#### `getTip()`

Get the current chain tip (latest entry).

```typescript
const { entry } = await sdk.chain.getTip()

console.log('Height:', entry.height)
console.log('Hash:', entry.hash)
console.log('Timestamp:', entry.timestamp)
```

**Returns**: `Promise<GetTipResponse>` with chain entry

#### `getStats()`

Get chain statistics.

```typescript
const { stats } = await sdk.chain.getStats()

console.log('Total entries:', stats.total_entries)
console.log('Total transactions:', stats.total_transactions)
console.log('Current height:', stats.height)
console.log('Circulating supply:', stats.circulating)
```

**Returns**: `Promise<GetStatsResponse>` with chain statistics

#### `getByHeight(height: number)`

Get entries at a specific height.

```typescript
const { entries } = await sdk.chain.getByHeight(1000)

entries.forEach((entry) => {
	console.log('Entry hash:', entry.hash)
	console.log('Height:', entry.height)
})
```

**Parameters**:

* `height` (number): Chain height

**Returns**: `Promise<GetByHeightResponse>` with array of entries

#### `getByHash(hash: string)`

Get entries by hash.

```typescript
const { entry } = await sdk.chain.getByHash('5Kd3N...')

console.log('Entry:', entry)
```

**Parameters**:

* `hash` (string): Entry hash (Base58 encoded)

**Returns**: `Promise<GetByHashResponse>` with chain entry

#### `getTransactionEventsByAccount(address: string, filters?: TransactionFilters)`

Get transaction events for an account.

```typescript
const events = await sdk.chain.getTransactionEventsByAccount('5Kd3N...', {
	limit: 10,
	sort: 'desc',
	type: 'sent' // or 'recv'
})

events.txs.forEach((event) => {
	console.log('Type:', event.type)
	console.log('Amount:', event.amount)
	console.log('Symbol:', event.symbol)
	console.log('Timestamp:', event.timestamp)
})
```

**Parameters**:

* `address` (string): Account address (Base58 encoded)
* `filters` (optional): Transaction filters

**Returns**: `Promise<GetTransactionEventsByAccountResponse>` with transaction events

### Wallet API

Query wallet balances and transaction information.

#### `getBalance(address: string, symbol?: string)`

Get balance for a specific address and token symbol.

```typescript
const balance = await sdk.wallet.getBalance('5Kd3N...', 'AMA')

console.log('Balance (float):', balance.balance.float)
console.log('Balance (flat):', balance.balance.flat)
console.log('Symbol:', balance.balance.symbol)
```

**Parameters**:

* `address` (string): Wallet address (Base58 encoded)
* `symbol` (string, optional): Token symbol (default: 'AMA')

**Returns**: `Promise<WalletBalance>` with token balance

#### `getAllBalances(address: string)`

Get all token balances for an address.

```typescript
const { balances } = await sdk.wallet.getAllBalances('5Kd3N...')

Object.entries(balances).forEach(([symbol, balance]) => {
	console.log(`${symbol}: ${balance.float}`)
})
```

**Parameters**:

* `address` (string): Wallet address (Base58 encoded)

**Returns**: `Promise<GetAllBalancesResponse>` with all balances

#### `getTransactions(address: string, query?: GetWalletTransactionsQuery)`

Get transactions for a wallet address.

```typescript
const { txs, cursor } = await sdk.wallet.getTransactions('5Kd3N...', {
	limit: 10,
	sort: 'desc',
	contract: 'Coin',
	function: 'transfer'
})

txs.forEach((tx) => {
	console.log('Hash:', tx.hash)
	console.log('Action:', tx.tx.action)
})
```

**Parameters**:

* `address` (string): Wallet address (Base58 encoded)
* `query` (optional): Query parameters (limit, sort, contract, function, type, cursor)

**Returns**: `Promise<GetWalletTransactionsResponse>` with transactions and cursor

### Transaction API

Submit transactions and query transaction data.

#### `submit(txPacked: Uint8Array | string)`

Submit a transaction to the network.

```typescript
const result = await sdk.transaction.submit(txPacked)

if (result.error === 'ok') {
	console.log('Transaction hash:', result.hash)
} else {
	console.error('Error:', result.error)
}
```

**Parameters**:

* `txPacked` (Uint8Array | string): Packed transaction as Uint8Array or Base58 string

**Returns**: `Promise<SubmitTransactionResponse>` with submission result

#### `submitAndWait(txPacked: Uint8Array | string)`

Submit a transaction and wait for confirmation.

```typescript
try {
	const result = await sdk.transaction.submitAndWait(txPacked)

	if (result.error === 'ok') {
		console.log('Hash:', result.hash)
		console.log('Entry hash:', result.metadata?.entry_hash)
		console.log('Receipt:', result.receipt)
	}
} catch (error) {
	console.error('Transaction failed or timed out:', error)
}
```

**Parameters**:

* `txPacked` (Uint8Array | string): Packed transaction

**Returns**: `Promise<SubmitAndWaitTransactionResponse>` with confirmation result

#### `get(txHash: string)`

Get a transaction by hash.

```typescript
const tx = await sdk.transaction.get('5Kd3N...')

console.log('Transaction:', tx.hash)
console.log('Signer:', tx.tx.signer)
console.log('Action:', tx.tx.action)
console.log('Receipt:', tx.receipt)
```

**Parameters**:

* `txHash` (string): Transaction hash (Base58 encoded)

**Returns**: `Promise<Transaction>` with transaction data

#### `getTransactionsInEntry(entryHash: string)`

Get all transactions in a specific entry.

```typescript
const { txs } = await sdk.transaction.getTransactionsInEntry('5Kd3N...')

txs.forEach((tx) => {
	console.log('Transaction:', tx.hash)
})
```

**Parameters**:

* `entryHash` (string): Entry hash (Base58 encoded)

**Returns**: `Promise<GetTransactionsInEntryResponse>` with transactions

### Contract API

Interact with smart contracts and query contract data.

#### `get(key: Uint8Array | string)`

Get contract data by key.

```typescript
const data = await sdk.contract.get(keyBytes)
// or
const data = await sdk.contract.get('5Kd3N...') // Base58 encoded key

console.log('Contract data:', data)
```

**Parameters**:

* `key` (Uint8Array | string): Contract key as Uint8Array or Base58 string

**Returns**: `Promise<ContractDataValue>` with contract data

#### `getPrefix(key: Uint8Array | string)`

Get contract data by key prefix.

```typescript
const data = await sdk.contract.getPrefix(keyPrefix)

data.forEach((item) => {
	console.log('Key:', item.key)
	console.log('Value:', item.value)
})
```

**Parameters**:

* `key` (Uint8Array | string): Contract key prefix

**Returns**: `Promise<ContractDataValue[]>` with array of key-value pairs

#### `validateBytecode(bytecode: Uint8Array | ArrayBuffer)`

Validate contract bytecode.

```typescript
const result = await sdk.contract.validateBytecode(wasmBytecode)

if (result.error === 'ok') {
	console.log('Bytecode is valid')
} else {
	console.error('Validation error:', result.error)
}
```

**Parameters**:

* `bytecode` (Uint8Array | ArrayBuffer): Contract bytecode to validate

**Returns**: `Promise<ValidateBytecodeResponse>` with validation result

#### `getRichlist()`

Get contract richlist (token holders).

```typescript
const { richlist } = await sdk.contract.getRichlist()

richlist.forEach((entry) => {
	console.log('Address:', entry.address)
	console.log('Balance:', entry.balance)
	console.log('Rank:', entry.rank)
})
```

**Returns**: `Promise<GetRichlistResponse>` with richlist entries

### Epoch API

Query epoch and validator data.

#### `getScore(publicKey?: string)`

Get epoch score(s).

```typescript
// Get score for specific validator
const score = await sdk.epoch.getScore('5Kd3N...')
console.log('Score:', score.score)

// Get all scores
const allScores = await sdk.epoch.getScore()
allScores.forEach(([address, score]) => {
	console.log(`${address}: ${score}`)
})
```

**Parameters**:

* `publicKey` (string, optional): Validator public key (Base58 encoded)

**Returns**: `Promise<EpochScore | EpochScore[]>` with score(s)

#### `getAllScores()`

Get all epoch scores.

```typescript
const scores = await sdk.epoch.getAllScores()

scores.forEach(([address, score]) => {
	console.log(`${address}: ${score}`)
})
```

**Returns**: `Promise<EpochScore[]>` with all scores

#### `getTopValidators(limit: number)`

Get top validators by score.

```typescript
const topValidators = await sdk.epoch.getTopValidators(10)

topValidators.forEach(([address, score]) => {
	console.log(`${address}: ${score}`)
})
```

**Parameters**:

* `limit` (number): Number of top validators to return

**Returns**: `Promise<EpochScore[]>` with top validators

#### `getEmissionAddress()`

Get the current emission address.

```typescript
const { emission_address } = await sdk.epoch.getEmissionAddress()

if (emission_address) {
	console.log('Emission address:', emission_address)
} else {
	console.log('No emission address set')
}
```

**Returns**: `Promise<GetEmissionAddressResponse>` with emission address

#### `getSolInEpoch(epoch: number, solutionHash: string)`

Check if a solution is in a specific epoch.

```typescript
const result = await sdk.epoch.getSolInEpoch(100, '5Kd3N...')

if (result.error === 'ok') {
	console.log('Solution found in epoch')
} else if (result.error === 'sol_not_found') {
	console.log('Solution not found')
} else {
	console.log('Invalid epoch')
}
```

**Parameters**:

* `epoch` (number): Epoch number
* `solutionHash` (string): Solution hash (Base58 encoded)

**Returns**: `Promise<GetSolInEpochResponse>` with check result

### Peer API

Query network peer information.

#### `getNodes()`

Get all network nodes.

```typescript
const nodes = await sdk.peer.getNodes()

nodes.forEach((node) => {
	console.log('Public Key:', node.pk)
	console.log('Version:', node.version)
	console.log('Height:', node.temporal_height)
	console.log('Online:', node.online)
})
```

**Returns**: `Promise<PeerInfo[]>` with node information

#### `getTrainers()`

Get all trainers.

```typescript
const trainers = await sdk.peer.getTrainers()

trainers.forEach((trainer) => {
	console.log('Trainer:', trainer.pk)
	console.log('Is Trainer:', trainer.is_trainer)
})
```

**Returns**: `Promise<PeerInfo[]>` with trainer information

#### `getRemovedTrainers()`

Get removed trainers.

```typescript
const removed = await sdk.peer.getRemovedTrainers()

removed.forEach((trainer) => {
	console.log('Removed trainer:', trainer.pk)
})
```

**Returns**: `Promise<PeerInfo[]>` with removed trainer information

#### `getANRs()`

Get ANR (Autonomous Network Registry) entries.

```typescript
const anrs = await sdk.peer.getANRs()

anrs.forEach((anr) => {
	console.log('Public Key:', anr.pk)
	console.log('IP:', anr.ip4)
	console.log('Port:', anr.port)
	console.log('Version:', anr.version)
})
```

**Returns**: `Promise<ANRInfo[]>` with ANR information

#### `getANRByPk(publicKey: string)`

Get ANR entry by public key.

```typescript
const anr = await sdk.peer.getANRByPk('5Kd3N...')

console.log('ANR:', anr)
```

**Parameters**:

* `publicKey` (string): Public key (Base58 encoded)

**Returns**: `Promise<ANRInfo>` with ANR information

### Proof API

Query validator proofs.

#### `getValidators(entryHash: string)`

Get validator proof for an entry.

```typescript
const proof = await sdk.proof.getValidators('5Kd3N...')

console.log('Key:', proof.key)
console.log('Value:', proof.value)
console.log('Validators:', proof.validators)
console.log('Proof:', proof.proof)
```

**Parameters**:

* `entryHash` (string): Entry hash (Base58 encoded)

**Returns**: `Promise<ProofValidators>` with validator proof

### Error Handling

All API methods throw `AmadeusSDKError` on failure:

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

try {
	const balance = await sdk.wallet.getBalance(address, 'AMA')
} catch (error) {
	if (error instanceof AmadeusSDKError) {
		console.error('SDK Error:', error.message)
		console.error('Status:', error.status)
		console.error('Response:', error.response)
	}
}
```

### Next Steps

* [**Utilities**: Learn about utility functions](/sdk/6.-utilities.md)
* [**Examples**: See complete API usage examples](/sdk/7.-examples.md)
* [**Best Practices**: Development guidelines](/sdk/8.-best-practices.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/5.-api-modules.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.
