@amadeus-protocol/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +410 -0
  3. package/dist/api/chain.d.ts +119 -0
  4. package/dist/api/chain.d.ts.map +1 -0
  5. package/dist/api/chain.js +147 -0
  6. package/dist/api/chain.js.map +1 -0
  7. package/dist/api/contract.d.ts +62 -0
  8. package/dist/api/contract.d.ts.map +1 -0
  9. package/dist/api/contract.js +76 -0
  10. package/dist/api/contract.js.map +1 -0
  11. package/dist/api/epoch.d.ts +68 -0
  12. package/dist/api/epoch.d.ts.map +1 -0
  13. package/dist/api/epoch.js +99 -0
  14. package/dist/api/epoch.js.map +1 -0
  15. package/dist/api/index.d.ts +8 -0
  16. package/dist/api/index.d.ts.map +1 -0
  17. package/dist/api/index.js +8 -0
  18. package/dist/api/index.js.map +1 -0
  19. package/dist/api/peer.d.ts +80 -0
  20. package/dist/api/peer.d.ts.map +1 -0
  21. package/dist/api/peer.js +95 -0
  22. package/dist/api/peer.js.map +1 -0
  23. package/dist/api/proof.d.ts +25 -0
  24. package/dist/api/proof.d.ts.map +1 -0
  25. package/dist/api/proof.js +30 -0
  26. package/dist/api/proof.js.map +1 -0
  27. package/dist/api/transaction.d.ts +71 -0
  28. package/dist/api/transaction.d.ts.map +1 -0
  29. package/dist/api/transaction.js +85 -0
  30. package/dist/api/transaction.js.map +1 -0
  31. package/dist/api/wallet.d.ts +39 -0
  32. package/dist/api/wallet.d.ts.map +1 -0
  33. package/dist/api/wallet.js +51 -0
  34. package/dist/api/wallet.js.map +1 -0
  35. package/dist/client.d.ts +70 -0
  36. package/dist/client.d.ts.map +1 -0
  37. package/dist/client.js +280 -0
  38. package/dist/client.js.map +1 -0
  39. package/dist/constants.d.ts +42 -0
  40. package/dist/constants.d.ts.map +1 -0
  41. package/dist/constants.js +42 -0
  42. package/dist/constants.js.map +1 -0
  43. package/dist/conversion.d.ts +32 -0
  44. package/dist/conversion.d.ts.map +1 -0
  45. package/dist/conversion.js +50 -0
  46. package/dist/conversion.js.map +1 -0
  47. package/dist/crypto.d.ts +93 -0
  48. package/dist/crypto.d.ts.map +1 -0
  49. package/dist/crypto.js +156 -0
  50. package/dist/crypto.js.map +1 -0
  51. package/dist/encoding.d.ts +108 -0
  52. package/dist/encoding.d.ts.map +1 -0
  53. package/dist/encoding.js +165 -0
  54. package/dist/encoding.js.map +1 -0
  55. package/dist/encryption.d.ts +76 -0
  56. package/dist/encryption.d.ts.map +1 -0
  57. package/dist/encryption.js +137 -0
  58. package/dist/encryption.js.map +1 -0
  59. package/dist/index.d.ts +47 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +47 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/schemas.d.ts +67 -0
  64. package/dist/schemas.d.ts.map +1 -0
  65. package/dist/schemas.js +103 -0
  66. package/dist/schemas.js.map +1 -0
  67. package/dist/sdk.d.ts +100 -0
  68. package/dist/sdk.d.ts.map +1 -0
  69. package/dist/sdk.js +120 -0
  70. package/dist/sdk.js.map +1 -0
  71. package/dist/serialization.d.ts +42 -0
  72. package/dist/serialization.d.ts.map +1 -0
  73. package/dist/serialization.js +247 -0
  74. package/dist/serialization.js.map +1 -0
  75. package/dist/transaction-builder.d.ts +267 -0
  76. package/dist/transaction-builder.d.ts.map +1 -0
  77. package/dist/transaction-builder.js +397 -0
  78. package/dist/transaction-builder.js.map +1 -0
  79. package/dist/types.d.ts +550 -0
  80. package/dist/types.d.ts.map +1 -0
  81. package/dist/types.js +78 -0
  82. package/dist/types.js.map +1 -0
  83. package/dist/validation.d.ts +15 -0
  84. package/dist/validation.d.ts.map +1 -0
  85. package/dist/validation.js +39 -0
  86. package/dist/validation.js.map +1 -0
  87. package/package.json +80 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Amadeus Protocol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,410 @@
1
+ # @amadeus-protocol/sdk
2
+
3
+ Official TypeScript/JavaScript SDK for Amadeus Protocol - Core utilities for serialization, cryptography, transaction building, and API client.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@amadeus-protocol/sdk)](https://www.npmjs.com/package/@amadeus-protocol/sdk)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@amadeus-protocol/sdk)](https://www.npmjs.com/package/@amadeus-protocol/sdk)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.7+-blue.svg)](https://www.typescriptlang.org/)
9
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org/)
10
+ [![Bundle Size](https://img.shields.io/bundlephobia/minzip/@amadeus-protocol/sdk)](https://bundlephobia.com/package/@amadeus-protocol/sdk)
11
+ [![GitHub stars](https://img.shields.io/github/stars/amadeusprotocol/amadeus-typescript-sdk)](https://github.com/amadeusprotocol/amadeus-typescript-sdk)
12
+ [![GitHub forks](https://img.shields.io/github/forks/amadeusprotocol/amadeus-typescript-sdk)](https://github.com/amadeusprotocol/amadeus-typescript-sdk)
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @amadeus-protocol/sdk
18
+ # or
19
+ yarn add @amadeus-protocol/sdk
20
+ # or
21
+ pnpm add @amadeus-protocol/sdk
22
+ # or
23
+ bun add @amadeus-protocol/sdk
24
+ ```
25
+
26
+ ## Features
27
+
28
+ - **Canonical Serialization (VecPack)**: Deterministic encoding/decoding for cryptographic operations
29
+ - **Cryptographic Operations**: BLS12-381 key generation, signing, and verification
30
+ - **Password-Based Encryption**: Secure AES-GCM encryption with PBKDF2 key derivation for wallet data
31
+ - **Transaction Building**: Create and sign Amadeus protocol transactions
32
+ - **Token Conversions**: Convert between atomic units and human-readable amounts
33
+ - **Encoding Utilities**: Base58 and Base64 encoding/decoding for addresses, keys, and binary data
34
+ - **API Client**: Full-featured HTTP client for interacting with Amadeus nodes
35
+ - **Type Safety**: Complete TypeScript definitions for all APIs
36
+ - **Zero Dependencies**: Uses native fetch (no axios or other HTTP libraries)
37
+
38
+ ## Quick Start
39
+
40
+ ### Using the SDK
41
+
42
+ ```typescript
43
+ import { AmadeusSDK } from '@amadeus-protocol/sdk'
44
+
45
+ // Initialize SDK (uses default node URL if not specified)
46
+ const sdk = new AmadeusSDK({
47
+ baseUrl: 'https://nodes.amadeus.bot/api'
48
+ })
49
+
50
+ // Query chain
51
+ const tip = await sdk.chain.getTip()
52
+ console.log('Current height:', tip.entry.height)
53
+
54
+ // Query wallet balance
55
+ const balance = await sdk.wallet.getBalance('5Kd3N...', 'AMA')
56
+ console.log('Balance:', balance.balance.float)
57
+
58
+ // Submit transaction
59
+ const result = await sdk.transaction.submit(txPacked)
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ ### API Client
65
+
66
+ ```typescript
67
+ import { AmadeusSDK } from '@amadeus-protocol/sdk'
68
+
69
+ const sdk = new AmadeusSDK({
70
+ baseUrl: 'https://nodes.amadeus.bot/api',
71
+ timeout: 30000 // Optional: custom timeout
72
+ })
73
+
74
+ // Chain API
75
+ const stats = await sdk.chain.getStats()
76
+ const tip = await sdk.chain.getTip()
77
+ const entry = await sdk.chain.getByHash('5Kd3N...')
78
+
79
+ // Wallet API
80
+ const balance = await sdk.wallet.getBalance('5Kd3N...', 'AMA')
81
+ const allBalances = await sdk.wallet.getAllBalances('5Kd3N...')
82
+
83
+ // Transaction API
84
+ const result = await sdk.transaction.submit(txPacked)
85
+ const resultWithWait = await sdk.transaction.submitAndWait(txPacked)
86
+ const tx = await sdk.transaction.get('5Kd3N...')
87
+
88
+ // Contract API
89
+ const contractData = await sdk.contract.get(key)
90
+ const richlist = await sdk.contract.getRichlist()
91
+
92
+ // Epoch API
93
+ const scores = await sdk.epoch.getScore()
94
+ const emission = await sdk.epoch.getEmissionAddress('5Kd3N...')
95
+
96
+ // Peer API
97
+ const nodes = await sdk.peer.getNodes()
98
+ const trainers = await sdk.peer.getTrainers()
99
+ ```
100
+
101
+ ### Key Generation
102
+
103
+ ```typescript
104
+ import { generateKeypair, derivePublicKeyFromSeedBase58 } from '@amadeus-protocol/sdk'
105
+
106
+ // Generate a new keypair
107
+ const keypair = generateKeypair()
108
+ console.log(keypair.publicKey) // Base58 public key
109
+ console.log(keypair.privateKey) // Base58 private key (seed)
110
+
111
+ // Derive public key from existing seed
112
+ const publicKey = derivePublicKeyFromSeedBase58(keypair.privateKey)
113
+ ```
114
+
115
+ ### Transaction Building
116
+
117
+ #### Using TransactionBuilder Class (Recommended)
118
+
119
+ ```typescript
120
+ import { TransactionBuilder, fromBase58, toAtomicAma } from '@amadeus-protocol/sdk'
121
+
122
+ // Instance-based usage (convenient for multiple transactions)
123
+ const builder = new TransactionBuilder('5Kd3N...') // Base58 encoded seed
124
+
125
+ // Option 1: Build and sign in one step (convenience)
126
+ const { txHash, txPacked } = builder.transfer({
127
+ recipient: '5Kd3N...', // Base58 encoded recipient address
128
+ amount: 10.5, // Amount in human-readable format
129
+ symbol: 'AMA' // Token symbol
130
+ })
131
+
132
+ // Option 2: Build unsigned, then sign (more control)
133
+ const unsignedTx = builder.buildTransfer({
134
+ recipient: '5Kd3N...',
135
+ amount: 10.5,
136
+ symbol: 'AMA'
137
+ })
138
+ // Can inspect or modify unsignedTx before signing
139
+ const { txHash, txPacked } = builder.sign(unsignedTx)
140
+
141
+ // Option 3: Build custom transaction and sign
142
+ const unsignedTx = builder.build('Coin', 'transfer', [
143
+ fromBase58('5Kd3N...'), // Recipient bytes
144
+ toAtomicAma(10.5).toString(), // Amount in atomic units
145
+ 'AMA'
146
+ ])
147
+ const { txHash, txPacked } = builder.sign(unsignedTx)
148
+
149
+ // Option 4: Build and sign custom transaction (convenience)
150
+ const { txHash, txPacked } = builder.buildAndSign('Coin', 'transfer', [
151
+ fromBase58('5Kd3N...'),
152
+ toAtomicAma(10.5).toString(),
153
+ 'AMA'
154
+ ])
155
+ ```
156
+
157
+ #### Using Static Methods
158
+
159
+ ```typescript
160
+ import {
161
+ TransactionBuilder,
162
+ fromBase58,
163
+ toAtomicAma,
164
+ getPublicKey,
165
+ deriveSkAndSeed64FromBase58Seed
166
+ } from '@amadeus-protocol/sdk'
167
+
168
+ // Option 1: Build and sign transfer in one step (convenience)
169
+ const { txHash, txPacked } = TransactionBuilder.buildSignedTransfer({
170
+ senderPrivkey: '5Kd3N...', // Base58 encoded seed
171
+ recipient: '5Kd3N...', // Base58 encoded recipient address
172
+ amount: 10.5, // Amount in human-readable format
173
+ symbol: 'AMA' // Token symbol
174
+ })
175
+
176
+ // Option 2: Build unsigned transfer, then sign
177
+ const { seed64 } = deriveSkAndSeed64FromBase58Seed('5Kd3N...')
178
+ const signerPubKey = getPublicKey(seed64)
179
+
180
+ const unsignedTx = TransactionBuilder.buildTransfer(
181
+ { recipient: '5Kd3N...', amount: 10.5, symbol: 'AMA' },
182
+ signerPubKey
183
+ )
184
+ const { txHash, txPacked } = TransactionBuilder.sign(unsignedTx, '5Kd3N...')
185
+
186
+ // Option 3: Build custom unsigned transaction, then sign
187
+ const unsignedTx = TransactionBuilder.build(
188
+ signerPubKey,
189
+ 'Coin', // Contract name
190
+ 'transfer', // Method name
191
+ [fromBase58('5Kd3N...'), toAtomicAma(10.5).toString(), 'AMA']
192
+ )
193
+ const { txHash, txPacked } = TransactionBuilder.sign(unsignedTx, '5Kd3N...')
194
+
195
+ // Option 4: Build and sign custom transaction (convenience)
196
+ const { seed64, sk } = deriveSkAndSeed64FromBase58Seed('5Kd3N...')
197
+ const signerPubKey = getPublicKey(seed64)
198
+
199
+ const { txHash, txPacked } = TransactionBuilder.buildAndSign(signerPubKey, sk, 'Coin', 'transfer', [
200
+ fromBase58('5Kd3N...'),
201
+ toAtomicAma(10.5).toString(),
202
+ 'AMA'
203
+ ])
204
+ ```
205
+
206
+ ### Serialization
207
+
208
+ ```typescript
209
+ import { encode, decode } from '@amadeus-protocol/sdk'
210
+
211
+ // Encode data to canonical format
212
+ const data = {
213
+ foo: 'bar',
214
+ count: 42,
215
+ items: [1, 2, 3]
216
+ }
217
+ const encoded = encode(data)
218
+
219
+ // Decode data from canonical format
220
+ const decoded = decode(encoded)
221
+ ```
222
+
223
+ ### Token Conversions
224
+
225
+ ```typescript
226
+ import { toAtomicAma, fromAtomicAma } from '@amadeus-protocol/sdk'
227
+
228
+ // Convert to atomic units
229
+ const atomic = toAtomicAma(1.5) // Returns 1500000000
230
+
231
+ // Convert from atomic units
232
+ const ama = fromAtomicAma(1500000000) // Returns 1.5
233
+ ```
234
+
235
+ ### Signing Transactions
236
+
237
+ ```typescript
238
+ import { TransactionBuilder } from '@amadeus-protocol/sdk'
239
+
240
+ // Using TransactionBuilder instance
241
+ const builder = new TransactionBuilder('5Kd3N...')
242
+
243
+ // Build unsigned transaction
244
+ const unsignedTx = builder.build('Coin', 'transfer', args)
245
+
246
+ // Sign the transaction
247
+ const { txHash, txPacked } = builder.sign(unsignedTx)
248
+
249
+ // Or build and sign in one step
250
+ const { txHash, txPacked } = builder.buildAndSign('Coin', 'transfer', args)
251
+ ```
252
+
253
+ ### Encoding Utilities
254
+
255
+ ```typescript
256
+ import { toBase58, fromBase58, uint8ArrayToBase64, base64ToUint8Array } from '@amadeus-protocol/sdk'
257
+
258
+ // Base58 encoding
259
+ const encoded = toBase58(new Uint8Array([1, 2, 3]))
260
+ const decoded = fromBase58('5Kd3N...')
261
+
262
+ // Base64 encoding
263
+ const base64 = uint8ArrayToBase64(new Uint8Array([1, 2, 3]))
264
+ const bytes = base64ToUint8Array(base64)
265
+ ```
266
+
267
+ ### Password-Based Encryption
268
+
269
+ ```typescript
270
+ import { encryptWithPassword, decryptWithPassword } from '@amadeus-protocol/sdk'
271
+
272
+ // Encrypt sensitive data (e.g., private keys)
273
+ const encrypted = await encryptWithPassword('sensitive wallet data', 'my-password')
274
+ // Returns: { encryptedData, iv, salt } (all Base64 encoded)
275
+
276
+ // Decrypt the data
277
+ const decrypted = await decryptWithPassword(encrypted, 'my-password')
278
+ // Returns: 'sensitive wallet data'
279
+ ```
280
+
281
+ ## API Reference
282
+
283
+ ### Constants
284
+
285
+ - `AMADEUS_PUBLIC_KEY_BYTE_LENGTH`: Byte length of public key (48)
286
+ - `AMADEUS_SEED_BYTE_LENGTH`: Byte length of seed (64)
287
+ - `AMA_TOKEN_DECIMALS`: Number of decimal places (9)
288
+ - `AMA_TOKEN_DECIMALS_MULTIPLIER`: Multiplier for conversions (10^9)
289
+ - `AMA_TRANSFER_FEE`: Network transfer fee (0.02)
290
+ - `EXPLORER_URL`: Default explorer URL
291
+ - `NODE_API_URL`: Default node API URL
292
+
293
+ ### Serialization
294
+
295
+ - `encode(term: SerializableValue): Uint8Array` - Encode value to canonical format
296
+ - `decode(bytes: Uint8Array | number[]): DecodedValue` - Decode from canonical format
297
+
298
+ ### Crypto
299
+
300
+ - `generateKeypair(): KeyPair` - Generate a new keypair
301
+ - `generatePrivateKey(): Uint8Array` - Generate a random 64-byte seed
302
+ - `getPublicKey(seed64: Uint8Array): Uint8Array` - Derive public key from seed
303
+ - `derivePublicKeyFromSeedBase58(base58Seed: string): string` - Derive public key from Base58 seed
304
+ - `deriveSkAndSeed64FromBase58Seed(base58Seed64: string)` - Derive secret key and seed
305
+
306
+ ### Encoding
307
+
308
+ - `toBase58(buf: Uint8Array): string` - Encode bytes to Base58
309
+ - `fromBase58(str: string): Uint8Array` - Decode Base58 to bytes
310
+ - `uint8ArrayToBase64(bytes: Uint8Array): string` - Convert bytes to Base64
311
+ - `base64ToUint8Array(base64: string): Uint8Array` - Convert Base64 to bytes
312
+ - `arrayBufferToBase64(buffer: ArrayBuffer): string` - Convert ArrayBuffer to Base64
313
+ - `base64ToArrayBuffer(base64: string): ArrayBuffer` - Convert Base64 to ArrayBuffer
314
+ - `uint8ArrayToArrayBuffer(bytes: Uint8Array): ArrayBuffer` - Convert Uint8Array to ArrayBuffer
315
+ - `arrayBufferToUint8Array(buffer: ArrayBuffer): Uint8Array` - Convert ArrayBuffer to Uint8Array
316
+
317
+ ### Signing
318
+
319
+ - `signTx(hash: Uint8Array, sk: PrivKey): Uint8Array` - Sign a transaction hash
320
+ - `signOOB(sk: string, msg: Uint8Array): Uint8Array` - Sign an out-of-band message
321
+
322
+ ### Conversion
323
+
324
+ - `toAtomicAma(ama: number): number` - Convert AMA to atomic units
325
+ - `fromAtomicAma(atomicAma: number | string): number` - Convert atomic units to AMA
326
+
327
+ ### Encryption
328
+
329
+ - `encryptWithPassword(plaintext: string, password: string): Promise<EncryptedPayload>` - Encrypt data with password (AES-GCM + PBKDF2)
330
+ - `decryptWithPassword(payload: EncryptedPayload, password: string): Promise<string>` - Decrypt data with password
331
+ - `generateSalt(): Uint8Array` - Generate random salt (16 bytes)
332
+ - `generateIV(): Uint8Array` - Generate random IV (12 bytes)
333
+ - `deriveKey(password: string, salt: Uint8Array | ArrayBuffer): Promise<CryptoKey>` - Derive AES-GCM key from password
334
+
335
+ ### Transaction Building
336
+
337
+ - `TransactionBuilder` - Class for building and signing transactions
338
+ - **Constructor:** `new TransactionBuilder(privateKey?: string)` - Create a new builder instance
339
+ - **Instance Methods:**
340
+ - `build(contract, method, args, signerPk?): UnsignedTransactionWithHash` - Build an unsigned transaction
341
+ - `sign(unsignedTx, signerSk?): BuildTxResult` - Sign an unsigned transaction
342
+ - `buildAndSign(contract, method, args, signerPk?, signerSk?): BuildTxResult` - Build and sign in one step
343
+ - `buildTransfer(input, signerPk?): UnsignedTransactionWithHash` - Build an unsigned transfer
344
+ - `transfer(input): BuildTxResult` - Build and sign a transfer (convenience)
345
+ - **Static Methods:**
346
+ - `build(signerPk, contract, method, args): UnsignedTransactionWithHash` - Build unsigned transaction
347
+ - `sign(unsignedTx, signerSk): BuildTxResult` - Sign an unsigned transaction
348
+ - `buildAndSign(signerPk, signerSk, contract, method, args): BuildTxResult` - Build and sign in one step
349
+ - `buildTransfer(input, signerPk): UnsignedTransactionWithHash` - Build unsigned transfer
350
+ - `buildSignedTransfer(input): BuildTxResult` - Build and sign transfer (convenience)
351
+
352
+ ## Examples
353
+
354
+ See the [`examples/`](./examples/) directory for comprehensive usage examples:
355
+
356
+ - **Basic Usage** - SDK initialization, key generation, queries
357
+ - **Transaction Flow** - Complete transaction building and submission flow
358
+ - **API Usage** - All API endpoints demonstrated
359
+
360
+ ```bash
361
+ # Run examples
362
+ npm run example:basic
363
+ npm run example:tx
364
+ npm run example:api
365
+ ```
366
+
367
+ ## Testing
368
+
369
+ The SDK includes comprehensive test coverage:
370
+
371
+ ```bash
372
+ # Run tests
373
+ npm test
374
+
375
+ # Run tests in watch mode
376
+ npm run test:watch
377
+
378
+ # Run tests with coverage
379
+ npm run test:coverage
380
+ ```
381
+
382
+ ## TypeScript Support
383
+
384
+ This package is written in TypeScript and includes full type definitions. All exports are typed and documented.
385
+
386
+ ## Error Handling
387
+
388
+ All errors are thrown as `AmadeusSDKError` instances with descriptive messages:
389
+
390
+ ```typescript
391
+ import { AmadeusSDK, AmadeusSDKError } from '@amadeus-protocol/sdk'
392
+
393
+ try {
394
+ const balance = await sdk.wallet.getBalance('invalid')
395
+ } catch (error) {
396
+ if (error instanceof AmadeusSDKError) {
397
+ console.error('SDK Error:', error.message)
398
+ console.error('Status:', error.status)
399
+ console.error('Response:', error.response)
400
+ }
401
+ }
402
+ ```
403
+
404
+ ## License
405
+
406
+ MIT
407
+
408
+ ## Contributing
409
+
410
+ Contributions are welcome! Please ensure all code follows the existing style and includes appropriate tests.
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Chain API
3
+ *
4
+ * Provides methods for querying blockchain data
5
+ */
6
+ import type { AmadeusClient } from '../client';
7
+ import type { TransactionFilters, GetTipResponse, GetStatsResponse, GetByHashResponse, GetByHeightResponse, GetTransactionsInEntryResponse, GetTransactionEventsByAccountResponse, Transaction } from '../types';
8
+ export declare class ChainAPI {
9
+ private client;
10
+ constructor(client: AmadeusClient);
11
+ /**
12
+ * Get the current chain tip (latest entry)
13
+ *
14
+ * @returns Promise resolving to the latest chain entry
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const { entry } = await sdk.chain.getTip()
19
+ * console.log('Current height:', entry.height)
20
+ * ```
21
+ */
22
+ getTip(): Promise<GetTipResponse>;
23
+ /**
24
+ * Get chain statistics
25
+ *
26
+ * @returns Promise resolving to chain statistics
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const { stats } = await sdk.chain.getStats()
31
+ * console.log('Total entries:', stats.total_entries)
32
+ * ```
33
+ */
34
+ getStats(): Promise<GetStatsResponse>;
35
+ /**
36
+ * Get entry by hash
37
+ *
38
+ * @param hash - Entry hash (Base58 encoded)
39
+ * @param filterOnFunction - Optional function filter
40
+ * @returns Promise resolving to chain entry
41
+ * @throws {Error} If hash is invalid
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * const { entry } = await sdk.chain.getByHash('5Kd3N...')
46
+ * ```
47
+ */
48
+ getByHash(hash: string, filterOnFunction?: string): Promise<GetByHashResponse>;
49
+ /**
50
+ * Get entries by height
51
+ *
52
+ * @param height - Block height (must be >= 0)
53
+ * @returns Promise resolving to chain entries at the specified height
54
+ * @throws {Error} If height is invalid
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const { entries } = await sdk.chain.getByHeight(1000)
59
+ * ```
60
+ */
61
+ getByHeight(height: number): Promise<GetByHeightResponse>;
62
+ /**
63
+ * Get entries by height with transactions
64
+ *
65
+ * @param height - Block height (must be >= 0)
66
+ * @returns Promise resolving to chain entries with transactions at the specified height
67
+ * @throws {Error} If height is invalid
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * const { entries } = await sdk.chain.getByHeightWithTxs(1000)
72
+ * ```
73
+ */
74
+ getByHeightWithTxs(height: number): Promise<GetByHeightResponse>;
75
+ /**
76
+ * Get a specific transaction by ID
77
+ *
78
+ * @param txid - Transaction ID (Base58 encoded)
79
+ * @returns Promise resolving to transaction data
80
+ * @throws {Error} If transaction ID is invalid
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const tx = await sdk.chain.getTransaction('5Kd3N...')
85
+ * ```
86
+ */
87
+ getTransaction(txid: string): Promise<Transaction>;
88
+ /**
89
+ * Get transactions in a specific entry
90
+ *
91
+ * @param entryHash - Entry hash (Base58 encoded)
92
+ * @returns Promise resolving to transactions in the entry
93
+ * @throws {Error} If entry hash is invalid
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * const { txs } = await sdk.chain.getTransactionsInEntry('5Kd3N...')
98
+ * ```
99
+ */
100
+ getTransactionsInEntry(entryHash: string): Promise<GetTransactionsInEntryResponse>;
101
+ /**
102
+ * Get transaction events by account with filtering
103
+ *
104
+ * @param account - Account address (Base58 encoded)
105
+ * @param filters - Optional filters for transactions
106
+ * @returns Promise resolving to transaction events
107
+ * @throws {Error} If account address is invalid
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * const { txs, cursor } = await sdk.chain.getTransactionEventsByAccount('5Kd3N...', {
112
+ * limit: 10,
113
+ * sort: 'desc'
114
+ * })
115
+ * ```
116
+ */
117
+ getTransactionEventsByAccount(account: string, filters?: TransactionFilters): Promise<GetTransactionEventsByAccountResponse>;
118
+ }
119
+ //# sourceMappingURL=chain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chain.d.ts","sourceRoot":"","sources":["../../src/api/chain.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,KAAK,EACX,kBAAkB,EAClB,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,EACnB,8BAA8B,EAC9B,qCAAqC,EACrC,WAAW,EACX,MAAM,UAAU,CAAA;AAKjB,qBAAa,QAAQ;IACR,OAAO,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAEzC;;;;;;;;;;OAUG;IACG,MAAM,IAAI,OAAO,CAAC,cAAc,CAAC;IAIvC;;;;;;;;;;OAUG;IACG,QAAQ,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAI3C;;;;;;;;;;;;OAYG;IACG,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAOpF;;;;;;;;;;;OAWG;IACG,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAK/D;;;;;;;;;;;OAWG;IACG,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAKtE;;;;;;;;;;;OAWG;IACG,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAKxD;;;;;;;;;;;OAWG;IACG,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,8BAA8B,CAAC;IAOxF;;;;;;;;;;;;;;;OAeG;IACG,6BAA6B,CAClC,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,kBAAuB,GAC9B,OAAO,CAAC,qCAAqC,CAAC;CASjD"}
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Chain API
3
+ *
4
+ * Provides methods for querying blockchain data
5
+ */
6
+ import { Base58HashSchema, TransactionFiltersSchema } from '../schemas';
7
+ import { Schema } from 'effect';
8
+ import { validate } from '../validation';
9
+ export class ChainAPI {
10
+ client;
11
+ constructor(client) {
12
+ this.client = client;
13
+ }
14
+ /**
15
+ * Get the current chain tip (latest entry)
16
+ *
17
+ * @returns Promise resolving to the latest chain entry
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const { entry } = await sdk.chain.getTip()
22
+ * console.log('Current height:', entry.height)
23
+ * ```
24
+ */
25
+ async getTip() {
26
+ return this.client.get('/api/chain/tip');
27
+ }
28
+ /**
29
+ * Get chain statistics
30
+ *
31
+ * @returns Promise resolving to chain statistics
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const { stats } = await sdk.chain.getStats()
36
+ * console.log('Total entries:', stats.total_entries)
37
+ * ```
38
+ */
39
+ async getStats() {
40
+ return this.client.get('/api/chain/stats');
41
+ }
42
+ /**
43
+ * Get entry by hash
44
+ *
45
+ * @param hash - Entry hash (Base58 encoded)
46
+ * @param filterOnFunction - Optional function filter
47
+ * @returns Promise resolving to chain entry
48
+ * @throws {Error} If hash is invalid
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const { entry } = await sdk.chain.getByHash('5Kd3N...')
53
+ * ```
54
+ */
55
+ async getByHash(hash, filterOnFunction) {
56
+ validate(Base58HashSchema, hash);
57
+ return this.client.get(`/api/chain/hash/${hash}`, {
58
+ filter_on_function: filterOnFunction
59
+ });
60
+ }
61
+ /**
62
+ * Get entries by height
63
+ *
64
+ * @param height - Block height (must be >= 0)
65
+ * @returns Promise resolving to chain entries at the specified height
66
+ * @throws {Error} If height is invalid
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * const { entries } = await sdk.chain.getByHeight(1000)
71
+ * ```
72
+ */
73
+ async getByHeight(height) {
74
+ validate(Schema.NonNegativeInt, height);
75
+ return this.client.get(`/api/chain/height/${height}`);
76
+ }
77
+ /**
78
+ * Get entries by height with transactions
79
+ *
80
+ * @param height - Block height (must be >= 0)
81
+ * @returns Promise resolving to chain entries with transactions at the specified height
82
+ * @throws {Error} If height is invalid
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * const { entries } = await sdk.chain.getByHeightWithTxs(1000)
87
+ * ```
88
+ */
89
+ async getByHeightWithTxs(height) {
90
+ validate(Schema.NonNegativeInt, height);
91
+ return this.client.get(`/api/chain/height_with_txs/${height}`);
92
+ }
93
+ /**
94
+ * Get a specific transaction by ID
95
+ *
96
+ * @param txid - Transaction ID (Base58 encoded)
97
+ * @returns Promise resolving to transaction data
98
+ * @throws {Error} If transaction ID is invalid
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const tx = await sdk.chain.getTransaction('5Kd3N...')
103
+ * ```
104
+ */
105
+ async getTransaction(txid) {
106
+ validate(Base58HashSchema, txid);
107
+ return this.client.get(`/api/chain/tx/${txid}`);
108
+ }
109
+ /**
110
+ * Get transactions in a specific entry
111
+ *
112
+ * @param entryHash - Entry hash (Base58 encoded)
113
+ * @returns Promise resolving to transactions in the entry
114
+ * @throws {Error} If entry hash is invalid
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * const { txs } = await sdk.chain.getTransactionsInEntry('5Kd3N...')
119
+ * ```
120
+ */
121
+ async getTransactionsInEntry(entryHash) {
122
+ validate(Base58HashSchema, entryHash);
123
+ return this.client.get(`/api/chain/txs_in_entry/${entryHash}`);
124
+ }
125
+ /**
126
+ * Get transaction events by account with filtering
127
+ *
128
+ * @param account - Account address (Base58 encoded)
129
+ * @param filters - Optional filters for transactions
130
+ * @returns Promise resolving to transaction events
131
+ * @throws {Error} If account address is invalid
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * const { txs, cursor } = await sdk.chain.getTransactionEventsByAccount('5Kd3N...', {
136
+ * limit: 10,
137
+ * sort: 'desc'
138
+ * })
139
+ * ```
140
+ */
141
+ async getTransactionEventsByAccount(account, filters = {}) {
142
+ validate(Base58HashSchema, account);
143
+ validate(TransactionFiltersSchema, filters);
144
+ return this.client.get(`/api/chain/tx_events_by_account/${account}`, filters);
145
+ }
146
+ }
147
+ //# sourceMappingURL=chain.js.map