# 6. Utilities

Complete reference for utility functions in the Amadeus Protocol SDK.

### Crypto Utilities

Cryptographic operations for key generation and key derivation.

#### `generateKeypair()`

Generate a new BLS12-381 keypair.

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

const keypair = generateKeypair()

console.log('Public Key:', keypair.publicKey) // Base58 encoded
console.log('Private Key:', keypair.privateKey) // Base58 encoded seed
```

**Returns**: `KeyPair` with `publicKey` and `privateKey` (both Base58 encoded)

#### `generatePrivateKey()`

Generate a new random 64-byte seed.

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

const seed = generatePrivateKey() // Returns Uint8Array (64 bytes)
```

**Returns**: `Uint8Array` (64 bytes)

#### `getPublicKey(seed: Uint8Array)`

Derive a public key from a 64-byte seed.

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

const seed = generatePrivateKey()
const publicKey = getPublicKey(seed) // Returns Uint8Array (48 bytes)
```

**Parameters**:

* `seed` (Uint8Array): 64-byte seed

**Returns**: `Uint8Array` (48 bytes) - BLS12-381 public key

#### `derivePublicKeyFromSeedBase58(seedBase58: string)`

Derive public key from Base58-encoded seed.

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

const publicKey = derivePublicKeyFromSeedBase58('5Kd3N...')
console.log('Public Key:', publicKey) // Base58 encoded
```

**Parameters**:

* `seedBase58` (string): Base58-encoded seed

**Returns**: `string` - Base58-encoded public key

#### `deriveSkAndSeed64FromBase58Seed(seedBase58: string)`

Derive secret key and seed from Base58-encoded seed.

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

const { sk, seed64 } = deriveSkAndSeed64FromBase58Seed('5Kd3N...')

console.log('Secret Key:', sk) // Uint8Array
console.log('Seed64:', seed64) // Uint8Array
```

**Parameters**:

* `seedBase58` (string): Base58-encoded seed

**Returns**: `{ sk: Uint8Array, seed64: Uint8Array }`

### Encoding Utilities

Convert between different binary formats and string encodings.

#### Base58 Encoding

**`toBase58(bytes: Uint8Array): string`**

Encode bytes to Base58 string.

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

const bytes = new Uint8Array([1, 2, 3])
const encoded = toBase58(bytes)
console.log('Base58:', encoded)
```

**Parameters**:

* `bytes` (Uint8Array): Bytes to encode

**Returns**: `string` - Base58 encoded string

**`fromBase58(str: string): Uint8Array`**

Decode Base58 string to bytes.

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

const bytes = fromBase58('5Kd3N...')
console.log('Bytes:', bytes)
```

**Parameters**:

* `str` (string): Base58 string to decode

**Returns**: `Uint8Array` - Decoded bytes

#### Base64 Encoding

**`uint8ArrayToBase64(bytes: Uint8Array): string`**

Convert Uint8Array to Base64 string.

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

const bytes = new Uint8Array([1, 2, 3])
const base64 = uint8ArrayToBase64(bytes)
console.log('Base64:', base64)
```

**Parameters**:

* `bytes` (Uint8Array): Bytes to encode

**Returns**: `string` - Base64 encoded string

**`base64ToUint8Array(base64: string): Uint8Array`**

Convert Base64 string to Uint8Array.

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

const bytes = base64ToUint8Array('AQID')
console.log('Bytes:', bytes)
```

**Parameters**:

* `base64` (string): Base64 encoded string

**Returns**: `Uint8Array` - Decoded bytes

**`arrayBufferToBase64(buffer: ArrayBuffer): string`**

Convert ArrayBuffer to Base64 string.

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

const buffer = new ArrayBuffer(8)
const base64 = arrayBufferToBase64(buffer)
```

**Parameters**:

* `buffer` (ArrayBuffer): Buffer to encode

**Returns**: `string` - Base64 encoded string

**`base64ToArrayBuffer(base64: string): ArrayBuffer`**

Convert Base64 string to ArrayBuffer.

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

const buffer = base64ToArrayBuffer('AQID')
```

**Parameters**:

* `base64` (string): Base64 encoded string

**Returns**: `ArrayBuffer` - Decoded buffer

#### Array Conversion

**`uint8ArrayToArrayBuffer(bytes: Uint8Array): ArrayBuffer`**

Convert Uint8Array to ArrayBuffer.

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

const bytes = new Uint8Array([1, 2, 3])
const buffer = uint8ArrayToArrayBuffer(bytes)
```

**Parameters**:

* `bytes` (Uint8Array): The Uint8Array to convert

**Returns**: `ArrayBuffer`

**`arrayBufferToUint8Array(buffer: ArrayBuffer): Uint8Array`**

Convert ArrayBuffer to Uint8Array.

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

const buffer = new ArrayBuffer(8)
const bytes = arrayBufferToUint8Array(buffer)
```

**Parameters**:

* `buffer` (ArrayBuffer): The ArrayBuffer to convert

**Returns**: `Uint8Array` - View of the buffer

### Serialization

Canonical serialization using VecPack format.

#### `encode(value: SerializableValue): Uint8Array`

Encode a value using VecPack canonical serialization.

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

const data = {
	foo: 'bar',
	count: 42,
	items: [1, 2, 3],
	nested: {
		value: true
	}
}

const encoded = encode(data)
console.log('Encoded:', encoded) // Uint8Array
```

**Parameters**:

* `value`: Serializable value (null, boolean, number, bigint, string, Uint8Array, array, object, Map)

**Returns**: `Uint8Array` - Encoded bytes

**Supported Types**:

* `null`
* `boolean`
* `number` / `bigint`
* `string`
* `Uint8Array`
* Arrays
* Objects / Maps

#### `decode(bytes: Uint8Array | number[]): DecodedValue`

Decode VecPack-encoded bytes.

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

const decoded = decode(encoded)
console.log('Decoded:', decoded)
```

**Parameters**:

* `bytes` (Uint8Array | number\[]): Encoded bytes

**Returns**: `DecodedValue` - Decoded value

### Conversion Utilities

Convert between human-readable amounts and atomic units.

#### `toAtomicAma(amount: number): number`

Convert AMA amount to atomic units.

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

const atomic = toAtomicAma(1.5) // Returns 1500000000
console.log('Atomic units:', atomic)
```

**Parameters**:

* `amount` (number): Amount in AMA (e.g., 1.5)

**Returns**: `number` - Amount in atomic units

**Note**: AMA tokens use 9 decimal places.

#### `fromAtomicAma(atomic: number | string): number`

Convert atomic units to AMA amount.

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

const ama = fromAtomicAma(1500000000) // Returns 1.5
console.log('AMA:', ama)
```

**Parameters**:

* `atomic` (number | string): Amount in atomic units

**Returns**: `number` - Amount in AMA

### Encryption Utilities

Password-based encryption for securing sensitive wallet data.

#### `encryptWithPassword(plaintext: string, password: string): Promise<EncryptedPayload>`

Encrypt plaintext using AES-GCM encryption with PBKDF2 key derivation.

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

const encrypted = await encryptWithPassword('sensitive data', 'my-password')

console.log('Encrypted Data:', encrypted.encryptedData) // Base64
console.log('IV:', encrypted.iv) // Base64
console.log('Salt:', encrypted.salt) // Base64

// Store encrypted.encryptedData, encrypted.iv, encrypted.salt
```

**Parameters**:

* `plaintext` (string): Data to encrypt
* `password` (string): Password for encryption

**Returns**: `Promise<EncryptedPayload>` - Object containing:

* `encryptedData` (string): Base64-encoded encrypted data
* `iv` (string): Base64-encoded initialization vector
* `salt` (string): Base64-encoded salt

**Security Features**:

* AES-GCM encryption with 256-bit keys
* PBKDF2 key derivation with 100,000 iterations
* Unique salt and IV for each encryption
* Authenticated encryption (prevents tampering)

#### `decryptWithPassword(payload: EncryptedPayload, password: string): Promise<string>`

Decrypt encrypted data using the provided password.

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

const decrypted = await decryptWithPassword(encrypted, 'my-password')
console.log('Decrypted:', decrypted)
```

**Parameters**:

* `payload` (EncryptedPayload): Encrypted payload with `encryptedData`, `iv`, and `salt`
* `password` (string): Password used for encryption

**Returns**: `Promise<string>` - Decrypted plaintext

**Throws**: `Error` if decryption fails (wrong password or corrupted data)

#### `generateSalt(): Uint8Array`

Generate a cryptographically secure random salt.

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

const salt = generateSalt() // Returns Uint8Array (16 bytes)
```

**Returns**: `Uint8Array` - Random salt (16 bytes / 128 bits)

#### `generateIV(): Uint8Array`

Generate a cryptographically secure random IV for AES-GCM.

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

const iv = generateIV() // Returns Uint8Array (12 bytes)
```

**Returns**: `Uint8Array` - Random IV (12 bytes / 96 bits)

#### `deriveKey(password: string, salt: Uint8Array | ArrayBuffer): Promise<CryptoKey>`

Derive an AES-GCM key from a password using PBKDF2.

```typescript
import { deriveKey, generateSalt } from '@amadeus-protocol/sdk'

const salt = generateSalt()
const key = await deriveKey('my-password', salt)
```

**Parameters**:

* `password` (string): Password string
* `salt` (Uint8Array | ArrayBuffer): Salt for key derivation

**Returns**: `Promise<CryptoKey>` - Derived AES-GCM key (256 bits)

### Constants

#### `AMADEUS_PUBLIC_KEY_BYTE_LENGTH`

Byte length of BLS12-381 public key: `48`

#### `AMADEUS_SEED_BYTE_LENGTH`

Byte length of seed: `64`

#### `AMA_TOKEN_DECIMALS`

Number of decimal places for AMA tokens: `9`

#### `AMA_TOKEN_DECIMALS_MULTIPLIER`

Multiplier for conversions: `1000000000` (10^9)

#### `AMA_TRANSFER_FEE`

Network transfer fee: `0.02`

#### `EXPLORER_URL`

Default explorer URL: `https://explorer.ama.one`

#### `NODE_API_URL`

Default node API URL: `https://nodes.amadeus.bot/api`

### Usage Examples

#### Complete Encryption Flow

```typescript
import { encryptWithPassword, decryptWithPassword, generateKeypair } from '@amadeus-protocol/sdk'

// Generate keypair
const keypair = generateKeypair()

// Encrypt private key
const encrypted = await encryptWithPassword(keypair.privateKey, 'user-password')

// Store encrypted data
localStorage.setItem('encryptedData', encrypted.encryptedData)
localStorage.setItem('iv', encrypted.iv)
localStorage.setItem('salt', encrypted.salt)

// Later: Decrypt private key
const encryptedPayload = {
	encryptedData: localStorage.getItem('encryptedData')!,
	iv: localStorage.getItem('iv')!,
	salt: localStorage.getItem('salt')!
}

const privateKey = await decryptWithPassword(encryptedPayload, 'user-password')
```

#### Address Validation

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

function isValidAddress(address: string): boolean {
	try {
		const bytes = fromBase58(address)
		return bytes.length === AMADEUS_PUBLIC_KEY_BYTE_LENGTH
	} catch {
		return false
	}
}
```

#### Amount Conversion

```typescript
import { toAtomicAma, fromAtomicAma } from '@amadeus-protocol/sdk'

// Convert for transaction
const amount = 10.5
const atomic = toAtomicAma(amount) // 10500000000

// Convert for display
const display = fromAtomicAma(atomic) // 10.5
```

### Next Steps

* [**Examples**: See complete utility usage examples](/sdk/7.-examples.md)
* [**Best Practices**: Security and development guidelines](/sdk/8.-best-practices.md)
* [**API Modules**: Learn about API endpoints](/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/6.-utilities.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.
