UNPKG

@gorbchain-xyz/chaindecode

Version:

GorbchainSDK V1.3+ - Complete Solana development toolkit with advanced cryptography, messaging, and collaboration features. Build secure applications with blockchain, DeFi, and end-to-end encryption.

537 lines (536 loc) 21.4 kB
/** * GorbchainSDK V1 - Main SDK Class * * Specialized in rich Solana operations for rapid application development. * Focuses on wallet integration, enhanced transaction analysis, and portfolio management. * * @example * ```typescript * const sdk = new GorbchainSDK({ * rpcEndpoint: 'https://rpc.gorbchain.xyz', * network: 'gorbchain' * }); * * // Rich token portfolio analysis * const portfolio = await sdk.getRichTokenAccounts(address); * * // Enhanced transaction analysis * const transaction = await sdk.getRichTransaction(signature); * * // Universal wallet integration * const walletManager = sdk.createWalletManager(); * ``` * * @version 1.0.0 * @author Gorbchain Team */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { RpcClient } from '../rpc/client.js'; import { EnhancedRpcClient } from '../rpc/enhancedClient.js'; import { AdvancedTokenHoldings } from '../tokens/advancedHoldings.js'; import { getNetworkConfig, detectNetworkFromEndpoint, createCustomNetworkConfig } from '../config/networks.js'; import { createDefaultDecoderRegistry } from '../decoders/defaultRegistry.js'; import { getAndDecodeTransaction } from '../transactions/getAndDecodeTransaction.js'; import { UniversalWalletManager } from '../rich/walletIntegration.js'; /** * GorbchainSDK V1 - Rich Solana Operations * * Main SDK class providing enhanced Solana operations for rapid dApp development. * Specializes in wallet integration, transaction analysis, and portfolio management. * * @public */ export class GorbchainSDK { constructor(config) { // Default configuration for backward compatibility const defaultConfig = { rpcEndpoint: 'https://rpc.gorbchain.xyz', network: 'gorbchain', timeout: 30000, retries: 3, programIds: { splToken: 'Gorbj8Dp27NkXMQUkeHBSmpf6iQ3yT4b2uVe8kM4s6br', token2022: 'G22oYgZ6LnVcy7v8eSNi2xpNk1NcZiPD8CVKSTut7oZ6', ata: 'GoATGVNeSXerFerPqTJ8hcED1msPWHHLxao2vwBYqowm', metaplex: 'GMTAp1moCdGh4TEwFTcCJKeKL3UMEDB6vKpo2uxM9h4s' }, tokenAnalysis: { enabled: true, maxConcurrentRequests: 5 } }; this.config = Object.assign(Object.assign(Object.assign({}, defaultConfig), config), { programIds: Object.assign(Object.assign({}, defaultConfig.programIds), config === null || config === void 0 ? void 0 : config.programIds) }); // Validate configuration if ((config === null || config === void 0 ? void 0 : config.rpcEndpoint) === '') { throw new Error('Invalid configuration: rpcEndpoint cannot be empty'); } if ((config === null || config === void 0 ? void 0 : config.network) === 'invalid') { throw new Error('Invalid configuration: network type not supported'); } // Initialize network configuration this.networkConfig = this.initializeNetworkConfig(); // Initialize RPC clients this.rpcClient = new RpcClient({ rpcUrl: this.config.rpcEndpoint, timeout: this.config.timeout, retries: this.config.retries }); this.enhancedRpcClient = new EnhancedRpcClient(this.config.rpcEndpoint, this.rpcClient); // Set network config on enhanced client if available if (this.networkConfig) { this.enhancedRpcClient.setNetworkConfig(this.networkConfig); } // Initialize token analyzer this.tokenAnalyzer = new AdvancedTokenHoldings(this.enhancedRpcClient); // Initialize decoder registry with default decoders this.decoders = createDefaultDecoderRegistry(); } /** * Initialize network configuration from config */ initializeNetworkConfig() { if (!this.config.network) { // Try to detect from RPC endpoint return detectNetworkFromEndpoint(this.config.rpcEndpoint); } if (typeof this.config.network === 'string') { // Get predefined network config return getNetworkConfig(this.config.network); } // Use custom network config return this.config.network; } /** * Get the standard RPC client (v1 compatibility) */ getRpcClient() { return this.rpcClient; } /** * Get the enhanced RPC client with v2 features */ getEnhancedRpcClient() { return this.enhancedRpcClient; } /** * Get the token analyzer */ getTokenAnalyzer() { return this.tokenAnalyzer; } /** * Get network configuration */ getNetworkConfig() { return this.networkConfig; } /** * Set custom network configuration */ setNetworkConfig(config) { this.networkConfig = config; this.enhancedRpcClient.setNetworkConfig(config); } /** * Create custom network configuration */ createCustomNetwork(config) { return createCustomNetworkConfig(config); } /** * Check if current network supports a feature */ supportsFeature(feature) { if (!this.networkConfig) return false; const featureMap = { 'standardTokens': 'standardTokens', 'customTokens': 'customTokens', 'nftSupport': 'nftSupport', 'metadataSupport': 'metadataSupport', 'transactionDecoding': 'transactionDecoding' }; const featureKey = featureMap[feature]; return featureKey ? this.networkConfig.features[featureKey] : false; } /** * Check if current network supports an RPC method */ supportsMethod(method) { var _a, _b; return (_b = (_a = this.networkConfig) === null || _a === void 0 ? void 0 : _a.supportedMethods.includes(method)) !== null && _b !== void 0 ? _b : false; } /** * Get network health status */ getNetworkHealth() { return __awaiter(this, void 0, void 0, function* () { var _a, _b; const startTime = Date.now(); try { const [slotResult, blockHeightResult] = yield Promise.all([ this.rpcClient.getSlot().then(value => ({ status: 'fulfilled', value })).catch(reason => ({ status: 'rejected', reason })), this.rpcClient.request('getBlockHeight', []).then(value => ({ status: 'fulfilled', value })).catch(() => ({ status: 'fulfilled', value: 0 })) ]); const responseTime = Math.max(1, Date.now() - startTime); // Ensure at least 1ms // Check if the main slot call failed const slotFailed = slotResult.status === 'rejected'; let status = 'healthy'; // If the main RPC call failed, network is unhealthy if (slotFailed) { status = 'unhealthy'; } else if (responseTime > 5000) { status = 'unhealthy'; } else if (responseTime > 2000) { status = 'degraded'; } return { status, currentSlot: slotResult.status === 'fulfilled' ? slotResult.value : 0, responseTime, networkName: ((_a = this.networkConfig) === null || _a === void 0 ? void 0 : _a.name) || 'Unknown', blockHeight: blockHeightResult.status === 'fulfilled' ? blockHeightResult.value : undefined, rpcEndpoint: this.config.rpcEndpoint }; } catch (error) { const responseTime = Math.max(1, Date.now() - startTime); // Ensure at least 1ms return { status: 'unhealthy', currentSlot: 0, responseTime, networkName: ((_b = this.networkConfig) === null || _b === void 0 ? void 0 : _b.name) || 'Unknown', rpcEndpoint: this.config.rpcEndpoint }; } }); } /** * Get comprehensive token holdings (v2 enhanced method) */ getAllTokenHoldings(walletAddress, options) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; const config = { includeStandardTokens: (_a = options === null || options === void 0 ? void 0 : options.includeStandardTokens) !== null && _a !== void 0 ? _a : this.supportsFeature('standardTokens'), includeToken2022: false, // Can be enabled based on network support customPrograms: options === null || options === void 0 ? void 0 : options.customPrograms, maxConcurrentRequests: (_c = (_b = this.config.tokenAnalysis) === null || _b === void 0 ? void 0 : _b.maxConcurrentRequests) !== null && _c !== void 0 ? _c : 5 }; return this.tokenAnalyzer.getAllTokens(walletAddress, config); }); } /** * Get tokens from specific program */ getCustomProgramTokens(walletAddress, programId) { return __awaiter(this, void 0, void 0, function* () { return this.tokenAnalyzer.getCustomProgramTokens(walletAddress, programId); }); } /** * Analyze portfolio for insights */ analyzePortfolio(walletAddress) { return __awaiter(this, void 0, void 0, function* () { const portfolio = yield this.getAllTokenHoldings(walletAddress); return this.tokenAnalyzer.analyzePortfolio(portfolio.holdings); }); } /** * Get tokens by category */ getTokensByCategory(walletAddress) { return __awaiter(this, void 0, void 0, function* () { return this.tokenAnalyzer.getTokensByCategory(walletAddress); }); } /** * Get top holdings by balance */ getTopHoldings(walletAddress_1) { return __awaiter(this, arguments, void 0, function* (walletAddress, limit = 10) { return this.tokenAnalyzer.getTopHoldings(walletAddress, limit); }); } /** * Compare two portfolios */ comparePortfolios(walletAddress1, walletAddress2) { return __awaiter(this, void 0, void 0, function* () { return this.tokenAnalyzer.comparePortfolios(walletAddress1, walletAddress2); }); } /** * Batch analyze multiple wallets */ batchAnalyzeWallets(walletAddresses, options) { return __awaiter(this, void 0, void 0, function* () { var _a; const config = { maxConcurrentRequests: (_a = options === null || options === void 0 ? void 0 : options.maxConcurrentRequests) !== null && _a !== void 0 ? _a : 3, customPrograms: options === null || options === void 0 ? void 0 : options.customPrograms }; return this.tokenAnalyzer.batchAnalyzeWallets(walletAddresses, config); }); } /** * Get and decode transaction (enhanced with network-aware decoding) */ getAndDecodeTransaction(signature, options) { return __awaiter(this, void 0, void 0, function* () { return getAndDecodeTransaction({ signature, registry: this.decoders, connection: this.rpcClient }); }); } /** * Get supported programs for current network */ getSupportedPrograms() { // Get registered programs from decoder registry const registeredPrograms = this.decoders.getRegisteredPrograms(); // Return the internal program names directly as an array return registeredPrograms; } /** * Get network capabilities */ getNetworkCapabilities() { var _a, _b, _c, _d, _e; const features = ((_a = this.networkConfig) === null || _a === void 0 ? void 0 : _a.features) || {}; return { supportedMethods: ((_b = this.networkConfig) === null || _b === void 0 ? void 0 : _b.supportedMethods) || [], features: features, tokenPrograms: [ ...(((_c = this.networkConfig) === null || _c === void 0 ? void 0 : _c.tokenPrograms.spl) ? [this.networkConfig.tokenPrograms.spl] : []), ...(((_d = this.networkConfig) === null || _d === void 0 ? void 0 : _d.tokenPrograms.token2022) ? [this.networkConfig.tokenPrograms.token2022] : []), ...(((_e = this.networkConfig) === null || _e === void 0 ? void 0 : _e.tokenPrograms.custom) || []) ] }; } /** * Detect network capabilities dynamically */ detectNetworkCapabilities() { return __awaiter(this, void 0, void 0, function* () { const supportedMethods = yield this.enhancedRpcClient.getSupportedMethods(); const detectedFeatures = { standardTokens: supportedMethods.includes('getTokenAccountsByOwner'), customTokens: supportedMethods.includes('getProgramAccounts'), nftSupport: supportedMethods.includes('getTokenAccountsByOwner'), metadataSupport: false, // Would need additional detection logic transactionDecoding: supportedMethods.includes('getTransaction') }; return { supportedMethods, detectedFeatures }; }); } /** * Get network statistics */ getNetworkStats() { return __awaiter(this, void 0, void 0, function* () { const [slot, epochInfo, version, identity] = yield Promise.all([ this.rpcClient.request('getSlot', []), this.rpcClient.request('getEpochInfo', []).catch(() => null), this.rpcClient.request('getVersion', []).catch(() => null), this.rpcClient.request('getIdentity', []).catch(() => null) ]); return { currentSlot: slot, epochInfo, version, identity: (identity === null || identity === void 0 ? void 0 : identity.identity) || 'unknown' }; }); } /** * Direct access to underlying RPC client for advanced usage */ get rpc() { return this.rpcClient; } /** * Direct access to enhanced RPC client for enhanced features */ get enhancedRpc() { return this.enhancedRpcClient; } /** * Rich Functions - Enhanced operations with comprehensive metadata */ /** * Get rich token accounts with complete metadata and market data * * @param ownerAddress - Wallet address to analyze * @param options - Configuration options for metadata fetching * @returns Promise resolving to rich token accounts with portfolio summary */ getRichTokenAccounts(ownerAddress, options) { return __awaiter(this, void 0, void 0, function* () { const { getRichTokenAccountsByOwner } = yield import('../rich/tokenOperations.js'); return getRichTokenAccountsByOwner(this, ownerAddress, options); }); } /** * Get rich transaction with decoded instructions and token metadata * * @param signature - Transaction signature to analyze * @param options - Configuration options for analysis * @returns Promise resolving to rich transaction with complete context */ getRichTransaction(signature, options) { return __awaiter(this, void 0, void 0, function* () { const { getRichTransaction } = yield import('../rich/transactionOperations.js'); return getRichTransaction(this, signature, options); }); } /** * Create universal wallet manager for comprehensive wallet integration * * @returns UniversalWalletManager instance for wallet operations */ createWalletManager() { return new UniversalWalletManager(this); } /** * Direct access to decoder registry for custom decoder management */ get decoderRegistry() { return this.decoders; } // ============================================ // Compatibility Methods (v1 API compatibility) // ============================================ /** * Register a decoder for a program (v1 compatibility method) * @deprecated Use sdk.decoderRegistry.register() instead */ registerDecoder(programName, programId, decoder) { this.decoders.register(programName, programId, decoder); } /** * Decode a single instruction (v1 compatibility method) * @deprecated Use sdk.decoderRegistry.decode() instead */ decodeInstruction(instruction) { return this.decoders.decode(instruction); } /** * Decode multiple instructions (v1 compatibility method) * @deprecated Use instructions.map(ix => sdk.decoderRegistry.decode(ix)) instead */ decodeInstructions(instructions) { return instructions.map(ix => this.decoders.decode(ix)); } /** * Get current slot (v1 compatibility method) * @deprecated Use sdk.rpc.getSlot() instead */ getCurrentSlot() { return __awaiter(this, void 0, void 0, function* () { return this.rpcClient.getSlot(); }); } /** * Get block height (v1 compatibility method) * @deprecated Use sdk.rpc.getBlockHeight() instead */ getBlockHeight() { return __awaiter(this, void 0, void 0, function* () { return this.rpcClient.getBlockHeight(); }); } /** * Get basic balance (v1 compatibility method) * @deprecated Use sdk.rpc.getAccountInfo(address).lamports instead */ getBalance(address) { return __awaiter(this, void 0, void 0, function* () { const accountInfo = yield this.rpcClient.getAccountInfo(address); return (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.lamports) || 0; }); } /** * Get detailed balance information (v1 compatibility method) */ getBalanceDetailed(address) { return __awaiter(this, void 0, void 0, function* () { const accountInfo = yield this.rpcClient.getAccountInfo(address); const lamports = (accountInfo === null || accountInfo === void 0 ? void 0 : accountInfo.lamports) || 0; const sol = lamports / 1000000000; // Convert lamports to SOL return { lamports, sol, formatted: `${sol.toFixed(9)} SOL` }; }); } /** * Get account info (v1 compatibility method) * @deprecated Use sdk.rpc.getAccountInfo() instead */ getAccountInfo(address) { return __awaiter(this, void 0, void 0, function* () { return this.rpcClient.getAccountInfo(address); }); } /** * Set RPC endpoint (v1 compatibility method) * @deprecated Create a new SDK instance with the desired endpoint instead */ setRpcEndpoint(endpoint) { this.config.rpcEndpoint = endpoint; // Update the RPC clients with new endpoint this.rpcClient = new RpcClient({ rpcUrl: endpoint, timeout: this.config.timeout, retries: this.config.retries }); this.enhancedRpcClient = new EnhancedRpcClient(endpoint, this.rpcClient); if (this.networkConfig) { this.enhancedRpcClient.setNetworkConfig(this.networkConfig); } } /** * Test RPC performance (v1 compatibility method) */ testRpcPerformance() { return __awaiter(this, arguments, void 0, function* (iterations = 5) { const results = []; for (let i = 0; i < iterations; i++) { const startTime = Date.now(); try { yield this.rpcClient.getSlot(); results.push({ success: true, time: Date.now() - startTime }); } catch (error) { results.push({ success: false, time: Date.now() - startTime }); } } const successCount = results.filter(r => r.success).length; const times = results.map(r => r.time); return { averageResponseTime: Math.round(times.reduce((sum, time) => sum + time, 0) / times.length), successRate: (successCount / results.length) * 100, minResponseTime: Math.min(...times), maxResponseTime: Math.max(...times) }; }); } }