@movebridge/core 0.0.1

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.
package/LICENSE ADDED
File without changes
@@ -0,0 +1,602 @@
1
+ import { Aptos } from '@aptos-labs/ts-sdk';
2
+ import EventEmitter from 'eventemitter3';
3
+
4
+ /**
5
+ * @movebridge/core - Type definitions
6
+ */
7
+ /** Supported network types */
8
+ type NetworkType = 'mainnet' | 'testnet';
9
+ /** Supported wallet types for Movement Network */
10
+ type WalletType = 'petra' | 'pontem' | 'nightly';
11
+ /** Configuration options for Movement client */
12
+ interface MovementConfig {
13
+ /** Network to connect to */
14
+ network: NetworkType;
15
+ /** Custom RPC URL (overrides network default) */
16
+ rpcUrl?: string;
17
+ /** Custom indexer URL (overrides network default) */
18
+ indexerUrl?: string;
19
+ /** Auto-connect to previously connected wallet */
20
+ autoConnect?: boolean;
21
+ }
22
+ /** Network-specific configuration */
23
+ interface NetworkConfig {
24
+ chainId: number;
25
+ rpcUrl: string;
26
+ indexerUrl: string | null;
27
+ explorerUrl: string;
28
+ faucetUrl?: string;
29
+ }
30
+ /** Account resource from blockchain */
31
+ interface Resource {
32
+ type: string;
33
+ data: Record<string, unknown>;
34
+ }
35
+ /** Transaction data */
36
+ interface Transaction {
37
+ hash: string;
38
+ sender: string;
39
+ sequenceNumber: string;
40
+ payload: TransactionPayload;
41
+ timestamp: string;
42
+ }
43
+ /** Transaction response after confirmation */
44
+ interface TransactionResponse {
45
+ hash: string;
46
+ success: boolean;
47
+ vmStatus: string;
48
+ gasUsed: string;
49
+ events: ContractEvent[];
50
+ }
51
+ /** Transaction payload for entry functions */
52
+ interface TransactionPayload {
53
+ type: 'entry_function_payload';
54
+ function: string;
55
+ typeArguments: string[];
56
+ arguments: unknown[];
57
+ }
58
+ /** Signed transaction ready for submission */
59
+ interface SignedTransaction {
60
+ payload: TransactionPayload;
61
+ signature: string;
62
+ sender: string;
63
+ }
64
+ /** Contract event data */
65
+ interface ContractEvent {
66
+ type: string;
67
+ sequenceNumber: string;
68
+ data: Record<string, unknown>;
69
+ }
70
+ /** Wallet connection state */
71
+ interface WalletState {
72
+ connected: boolean;
73
+ address: string | null;
74
+ publicKey: string | null;
75
+ }
76
+ /** Wallet event handlers */
77
+ interface WalletEvents {
78
+ connect: (address: string) => void;
79
+ disconnect: () => void;
80
+ accountChanged: (newAddress: string) => void;
81
+ networkChanged: (network: string) => void;
82
+ }
83
+ /** Options for token transfer */
84
+ interface TransferOptions {
85
+ to: string;
86
+ amount: string;
87
+ coinType?: string;
88
+ }
89
+ /** Options for building transactions */
90
+ interface BuildOptions {
91
+ function: string;
92
+ typeArguments: string[];
93
+ arguments: unknown[];
94
+ }
95
+ /** Options for creating contract interface */
96
+ interface ContractOptions {
97
+ address: string;
98
+ module: string;
99
+ }
100
+ /** Event subscription configuration */
101
+ interface EventSubscription {
102
+ eventHandle: string;
103
+ callback: (event: ContractEvent) => void;
104
+ }
105
+
106
+ /**
107
+ * @movebridge/core - Wallet Manager
108
+ * Handles wallet detection, connection, and state management
109
+ * Uses Aptos Wallet Standard (AIP-62) for wallet interactions
110
+ */
111
+
112
+ interface UnifiedWalletAdapter {
113
+ name: string;
114
+ icon: string;
115
+ connect(): Promise<{
116
+ address: string;
117
+ publicKey: string;
118
+ }>;
119
+ disconnect(): Promise<void>;
120
+ signAndSubmitTransaction(payload: any): Promise<{
121
+ hash: string;
122
+ }>;
123
+ signTransaction(payload: any): Promise<Uint8Array>;
124
+ onAccountChange(cb: (account: {
125
+ address: string;
126
+ publicKey: string;
127
+ } | null) => void): void;
128
+ onNetworkChange(cb: (network: string) => void): void;
129
+ }
130
+ declare class WalletManager extends EventEmitter<WalletEvents> {
131
+ private state;
132
+ private currentWallet;
133
+ private adapter;
134
+ private standardWallets;
135
+ private detectedWallets;
136
+ private unsubscribe;
137
+ detectWallets(): WalletType[];
138
+ getWalletInfo(): Array<{
139
+ type: WalletType;
140
+ name: string;
141
+ icon: string;
142
+ }>;
143
+ connect(wallet: WalletType): Promise<void>;
144
+ disconnect(): Promise<void>;
145
+ getState(): WalletState;
146
+ getWallet(): WalletType | null;
147
+ getAdapter(): UnifiedWalletAdapter | null;
148
+ autoConnect(): Promise<void>;
149
+ destroy(): void;
150
+ private setupEventListeners;
151
+ private saveLastWallet;
152
+ private getLastWallet;
153
+ private clearLastWallet;
154
+ }
155
+
156
+ /**
157
+ * @movebridge/core - Transaction Builder
158
+ * Constructs, signs, and submits transactions
159
+ */
160
+
161
+ /**
162
+ * Transaction Builder
163
+ * Provides methods for building, signing, and submitting transactions
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * // Transfer tokens
168
+ * const tx = await movement.transaction.transfer({
169
+ * to: '0x123...',
170
+ * amount: '1000000',
171
+ * });
172
+ *
173
+ * // Build custom transaction
174
+ * const tx = await movement.transaction.build({
175
+ * function: '0x1::coin::transfer',
176
+ * typeArguments: ['0x1::aptos_coin::AptosCoin'],
177
+ * arguments: ['0x123...', '1000000'],
178
+ * });
179
+ *
180
+ * // Sign and submit
181
+ * const signed = await movement.transaction.sign(tx);
182
+ * const hash = await movement.transaction.submit(signed);
183
+ * ```
184
+ */
185
+ declare class TransactionBuilder {
186
+ private readonly aptosClient;
187
+ private readonly walletManager;
188
+ constructor(aptosClient: Aptos, walletManager: WalletManager);
189
+ /**
190
+ * Builds a transfer transaction payload
191
+ * @param options - Transfer options
192
+ * @returns Transaction payload
193
+ */
194
+ transfer(options: TransferOptions): Promise<TransactionPayload>;
195
+ /**
196
+ * Builds a generic transaction payload
197
+ * @param options - Build options
198
+ * @returns Transaction payload
199
+ */
200
+ build(options: BuildOptions): Promise<TransactionPayload>;
201
+ /**
202
+ * Signs a transaction payload
203
+ * @param payload - Transaction payload to sign
204
+ * @returns Signed transaction
205
+ * @throws MovementError with code WALLET_NOT_CONNECTED if no wallet is connected
206
+ */
207
+ sign(payload: TransactionPayload): Promise<SignedTransaction>;
208
+ /**
209
+ * Submits a signed transaction to the network
210
+ * @param signed - Signed transaction
211
+ * @returns Transaction hash
212
+ */
213
+ submit(signed: SignedTransaction): Promise<string>;
214
+ /**
215
+ * Signs and submits a transaction in one step
216
+ * @param payload - Transaction payload
217
+ * @returns Transaction hash
218
+ */
219
+ signAndSubmit(payload: TransactionPayload): Promise<string>;
220
+ /**
221
+ * Simulates a transaction without submitting
222
+ * @param payload - Transaction payload
223
+ * @returns Simulation result with gas estimate
224
+ */
225
+ simulate(payload: TransactionPayload): Promise<{
226
+ success: boolean;
227
+ gasUsed: string;
228
+ vmStatus: string;
229
+ }>;
230
+ }
231
+
232
+ /**
233
+ * @movebridge/core - Contract Interface
234
+ * Simplified interface for contract interactions
235
+ */
236
+
237
+ /**
238
+ * Contract Interface
239
+ * Provides simplified methods for interacting with Move modules
240
+ *
241
+ * @example
242
+ * ```typescript
243
+ * const contract = movement.contract({
244
+ * address: '0x123...',
245
+ * module: 'counter',
246
+ * });
247
+ *
248
+ * // Read (view function)
249
+ * const count = await contract.view('get_count', []);
250
+ *
251
+ * // Write (entry function)
252
+ * const txHash = await contract.call('increment', []);
253
+ * ```
254
+ */
255
+ declare class ContractInterface {
256
+ private readonly aptosClient;
257
+ private readonly walletManager;
258
+ /** Contract address */
259
+ readonly address: string;
260
+ /** Module name */
261
+ readonly module: string;
262
+ constructor(aptosClient: Aptos, walletManager: WalletManager, options: ContractOptions);
263
+ /**
264
+ * Calls a view function (read-only)
265
+ * @param functionName - Name of the view function
266
+ * @param args - Function arguments
267
+ * @param typeArgs - Type arguments (optional)
268
+ * @returns Function result
269
+ * @throws MovementError with code VIEW_FUNCTION_FAILED if call fails
270
+ */
271
+ view<T = unknown>(functionName: string, args: unknown[], typeArgs?: string[]): Promise<T>;
272
+ /**
273
+ * Calls an entry function (write operation)
274
+ * @param functionName - Name of the entry function
275
+ * @param args - Function arguments
276
+ * @param typeArgs - Type arguments (optional)
277
+ * @returns Transaction hash
278
+ * @throws MovementError with code WALLET_NOT_CONNECTED if no wallet is connected
279
+ * @throws MovementError with code TRANSACTION_FAILED if transaction fails
280
+ */
281
+ call(functionName: string, args: unknown[], typeArgs?: string[]): Promise<string>;
282
+ /**
283
+ * Checks if a resource exists at the contract address
284
+ * @param resourceType - Full resource type (e.g., '0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>')
285
+ * @returns true if resource exists
286
+ */
287
+ hasResource(resourceType: string): Promise<boolean>;
288
+ /**
289
+ * Gets a resource from the contract address
290
+ * @param resourceType - Full resource type
291
+ * @returns Resource data or null if not found
292
+ */
293
+ getResource<T = unknown>(resourceType: string): Promise<T | null>;
294
+ /**
295
+ * Gets the full function name for a function in this module
296
+ * @param functionName - Function name
297
+ * @returns Full function name (address::module::function)
298
+ */
299
+ getFullFunctionName(functionName: string): string;
300
+ }
301
+
302
+ /**
303
+ * @movebridge/core - Event Listener
304
+ * Subscribes to and handles contract events
305
+ */
306
+
307
+ /**
308
+ * Event Listener
309
+ * Manages event subscriptions and polling
310
+ *
311
+ * @example
312
+ * ```typescript
313
+ * // Subscribe to events
314
+ * const subscriptionId = movement.events.subscribe({
315
+ * eventHandle: '0x123::counter::CounterChanged',
316
+ * callback: (event) => {
317
+ * console.log('Counter changed:', event);
318
+ * },
319
+ * });
320
+ *
321
+ * // Unsubscribe
322
+ * movement.events.unsubscribe(subscriptionId);
323
+ * ```
324
+ */
325
+ declare class EventListener {
326
+ private readonly aptosClient;
327
+ private subscriptions;
328
+ private subscriptionCounter;
329
+ private readonly pollIntervalMs;
330
+ constructor(aptosClient: Aptos, options?: {
331
+ pollIntervalMs?: number;
332
+ });
333
+ /**
334
+ * Subscribes to contract events
335
+ * @param subscription - Subscription configuration
336
+ * @returns Subscription ID
337
+ * @throws MovementError with code INVALID_EVENT_HANDLE if event handle is invalid
338
+ */
339
+ subscribe(subscription: EventSubscription): string;
340
+ /**
341
+ * Unsubscribes from events
342
+ * @param subscriptionId - Subscription ID to remove
343
+ */
344
+ unsubscribe(subscriptionId: string): void;
345
+ /**
346
+ * Unsubscribes from all events
347
+ */
348
+ unsubscribeAll(): void;
349
+ /**
350
+ * Gets active subscription count
351
+ * @returns Number of active subscriptions
352
+ */
353
+ getSubscriptionCount(): number;
354
+ /**
355
+ * Checks if a subscription exists
356
+ * @param subscriptionId - Subscription ID
357
+ * @returns true if subscription exists
358
+ */
359
+ hasSubscription(subscriptionId: string): boolean;
360
+ /**
361
+ * Polls for new events
362
+ * @param subscriptionId - Subscription ID
363
+ */
364
+ private pollEvents;
365
+ }
366
+
367
+ /**
368
+ * @movebridge/core - Movement Client
369
+ * Main entry point for SDK interactions
370
+ */
371
+
372
+ /**
373
+ * Resolved configuration with all URLs
374
+ */
375
+ interface ResolvedConfig {
376
+ network: NetworkType;
377
+ chainId: number;
378
+ rpcUrl: string;
379
+ indexerUrl: string | null;
380
+ explorerUrl: string;
381
+ autoConnect: boolean;
382
+ }
383
+ /**
384
+ * Movement SDK client
385
+ * Provides unified interface for Movement Network interactions
386
+ *
387
+ * @example
388
+ * ```typescript
389
+ * import { Movement } from '@movebridge/core';
390
+ *
391
+ * const movement = new Movement({ network: 'testnet' });
392
+ *
393
+ * // Get account balance
394
+ * const balance = await movement.getAccountBalance('0x1');
395
+ *
396
+ * // Connect wallet
397
+ * await movement.wallet.connect('petra');
398
+ * ```
399
+ */
400
+ declare class Movement {
401
+ /** Resolved configuration */
402
+ readonly config: ResolvedConfig;
403
+ /** Aptos SDK client instance */
404
+ private readonly aptosClient;
405
+ /** Wallet manager instance */
406
+ readonly wallet: WalletManager;
407
+ /** Transaction builder instance */
408
+ readonly transaction: TransactionBuilder;
409
+ /** Event listener instance */
410
+ readonly events: EventListener;
411
+ /**
412
+ * Creates a new Movement client
413
+ * @param config - Configuration options
414
+ */
415
+ constructor(config: MovementConfig);
416
+ /**
417
+ * Gets the underlying Aptos client
418
+ * @returns Aptos SDK client instance
419
+ */
420
+ getAptosClient(): Aptos;
421
+ /**
422
+ * Gets the account balance for an address
423
+ * @param address - Account address
424
+ * @returns Balance as string in smallest unit (octas)
425
+ * @throws MovementError with code INVALID_ADDRESS if address is invalid
426
+ */
427
+ getAccountBalance(address: string): Promise<string>;
428
+ /**
429
+ * Gets all resources for an account
430
+ * @param address - Account address
431
+ * @returns Array of resources
432
+ * @throws MovementError with code INVALID_ADDRESS if address is invalid
433
+ */
434
+ getAccountResources(address: string): Promise<Resource[]>;
435
+ /**
436
+ * Gets a transaction by hash
437
+ * @param hash - Transaction hash
438
+ * @returns Transaction data
439
+ */
440
+ getTransaction(hash: string): Promise<Transaction>;
441
+ /**
442
+ * Waits for a transaction to be confirmed
443
+ * @param hash - Transaction hash
444
+ * @param options - Wait options
445
+ * @returns Transaction response
446
+ */
447
+ waitForTransaction(hash: string, options?: {
448
+ timeoutMs?: number;
449
+ checkIntervalMs?: number;
450
+ }): Promise<TransactionResponse>;
451
+ /**
452
+ * Creates a contract interface for interacting with a Move module
453
+ * @param options - Contract options
454
+ * @returns Contract interface
455
+ */
456
+ contract(options: ContractOptions): ContractInterface;
457
+ }
458
+
459
+ /**
460
+ * @movebridge/core - Network configuration
461
+ */
462
+
463
+ /**
464
+ * Network configuration constants for Movement Network
465
+ */
466
+ declare const NETWORK_CONFIG: Record<NetworkType, NetworkConfig>;
467
+ /**
468
+ * Default coin type for native token transfers
469
+ */
470
+ declare const DEFAULT_COIN_TYPE = "0x1::aptos_coin::AptosCoin";
471
+ /**
472
+ * Resolves the full configuration from user options
473
+ * @param config - User-provided configuration
474
+ * @returns Resolved network configuration with all URLs
475
+ */
476
+ declare function resolveConfig(config: MovementConfig): {
477
+ network: NetworkType;
478
+ chainId: number;
479
+ rpcUrl: string;
480
+ indexerUrl: string | null;
481
+ explorerUrl: string;
482
+ autoConnect: boolean;
483
+ };
484
+ /**
485
+ * Validates a Movement/Aptos address format
486
+ * @param address - Address to validate
487
+ * @returns true if valid, false otherwise
488
+ */
489
+ declare function isValidAddress(address: string): boolean;
490
+ /**
491
+ * Validates an event handle format
492
+ * @param eventHandle - Event handle to validate
493
+ * @returns true if valid, false otherwise
494
+ */
495
+ declare function isValidEventHandle(eventHandle: string): boolean;
496
+ /**
497
+ * Gets the explorer URL for a transaction
498
+ * @param network - Network type
499
+ * @param txHash - Transaction hash
500
+ * @returns Explorer URL for the transaction
501
+ */
502
+ declare function getExplorerTxUrl(network: NetworkType, txHash: string): string;
503
+ /**
504
+ * Gets the explorer URL for an account
505
+ * @param network - Network type
506
+ * @param address - Account address
507
+ * @returns Explorer URL for the account
508
+ */
509
+ declare function getExplorerAccountUrl(network: NetworkType, address: string): string;
510
+
511
+ /**
512
+ * @movebridge/core - Error handling
513
+ */
514
+ /**
515
+ * Error codes for MovementError
516
+ */
517
+ type ErrorCode = 'INVALID_ADDRESS' | 'WALLET_NOT_FOUND' | 'WALLET_CONNECTION_FAILED' | 'WALLET_NOT_CONNECTED' | 'TRANSACTION_FAILED' | 'TRANSACTION_TIMEOUT' | 'VIEW_FUNCTION_FAILED' | 'INVALID_EVENT_HANDLE' | 'NETWORK_ERROR' | 'ABI_FETCH_FAILED' | 'CODEGEN_FAILED' | 'INVALID_ARGUMENT';
518
+ /**
519
+ * Error details - flexible record type for error context
520
+ */
521
+ type ErrorDetails = Record<string, unknown>;
522
+ /**
523
+ * Custom error class for MoveBridge SDK
524
+ * Provides structured error information with code, message, and details
525
+ */
526
+ declare class MovementError extends Error {
527
+ readonly code: ErrorCode;
528
+ readonly details?: ErrorDetails | undefined;
529
+ readonly name = "MovementError";
530
+ constructor(message: string, code: ErrorCode, details?: ErrorDetails | undefined);
531
+ /**
532
+ * Serializes the error to a JSON-compatible object
533
+ */
534
+ toJSON(): Record<string, unknown>;
535
+ /**
536
+ * Creates a string representation of the error
537
+ */
538
+ toString(): string;
539
+ }
540
+ /**
541
+ * Factory functions for creating common errors
542
+ */
543
+ declare const Errors: {
544
+ /**
545
+ * Creates an invalid address error
546
+ */
547
+ invalidAddress(address: string, reason?: string): MovementError;
548
+ /**
549
+ * Creates a wallet not found error
550
+ */
551
+ walletNotFound(wallet: string, available: string[]): MovementError;
552
+ /**
553
+ * Creates a wallet connection failed error
554
+ */
555
+ walletConnectionFailed(wallet: string, originalError?: unknown): MovementError;
556
+ /**
557
+ * Creates a wallet not connected error
558
+ */
559
+ walletNotConnected(): MovementError;
560
+ /**
561
+ * Creates a transaction failed error
562
+ */
563
+ transactionFailed(hash: string, vmStatus: string, gasUsed?: string): MovementError;
564
+ /**
565
+ * Creates a transaction timeout error
566
+ */
567
+ transactionTimeout(hash: string): MovementError;
568
+ /**
569
+ * Creates a view function failed error
570
+ */
571
+ viewFunctionFailed(functionName: string, args: unknown[], originalError?: unknown): MovementError;
572
+ /**
573
+ * Creates an invalid event handle error
574
+ */
575
+ invalidEventHandle(eventHandle: string): MovementError;
576
+ /**
577
+ * Creates a network error
578
+ */
579
+ networkError(url: string, httpStatus?: number, responseBody?: unknown): MovementError;
580
+ /**
581
+ * Creates an ABI fetch failed error
582
+ */
583
+ abiFetchFailed(address: string, network: string, originalError?: unknown): MovementError;
584
+ /**
585
+ * Creates a codegen failed error
586
+ */
587
+ codegenFailed(reason: string, abi?: unknown): MovementError;
588
+ /**
589
+ * Creates an invalid argument error
590
+ */
591
+ invalidArgument(argument: string, reason: string): MovementError;
592
+ };
593
+ /**
594
+ * Type guard to check if an error is a MovementError
595
+ */
596
+ declare function isMovementError(error: unknown): error is MovementError;
597
+ /**
598
+ * Wraps an unknown error as a MovementError
599
+ */
600
+ declare function wrapError(error: unknown, code: ErrorCode, context?: string): MovementError;
601
+
602
+ export { type BuildOptions, type ContractEvent, ContractInterface, type ContractOptions, DEFAULT_COIN_TYPE, type ErrorCode, type ErrorDetails, Errors, EventListener, type EventSubscription, Movement, type MovementConfig, MovementError, NETWORK_CONFIG, type NetworkConfig, type NetworkType, type ResolvedConfig, type Resource, type SignedTransaction, type Transaction, TransactionBuilder, type TransactionPayload, type TransactionResponse, type TransferOptions, type WalletEvents, WalletManager, type WalletState, type WalletType, getExplorerAccountUrl, getExplorerTxUrl, isMovementError, isValidAddress, isValidEventHandle, resolveConfig, wrapError };