diff --git a/docs/api/core-sdk.md b/docs/api/core-sdk.md new file mode 100644 index 0000000..28ca172 --- /dev/null +++ b/docs/api/core-sdk.md @@ -0,0 +1,904 @@ +# Core SDK API Reference + +Complete API reference for `@chenaikit/core` package. + +## Installation + +```bash +npm install @chenaikit/core +# or +pnpm add @chenaikit/core +# or +yarn add @chenaikit/core +``` + +## Table of Contents + +- [Stellar Module](#stellar-module) +- [AI Module](#ai-module) +- [Blockchain Module](#blockchain-module) +- [Utils Module](#utils-module) +- [Types](#types) + +--- + +## Stellar Module + +### StellarConnector + +Main class for interacting with the Stellar network. + +#### Constructor + +```typescript +new StellarConnector(config: StellarConfig) +``` + +**Parameters:** +- `config.network` - Network to connect to (`'testnet'` | `'mainnet'`) +- `config.horizonUrl` - Optional custom Horizon URL +- `config.timeout` - Optional request timeout in milliseconds (default: 30000) + +**Example:** +```typescript +import { StellarConnector } from '@chenaikit/core'; + +const stellar = new StellarConnector({ + network: 'testnet', + horizonUrl: 'https://horizon-testnet.stellar.org', + timeout: 30000 +}); +``` + +#### Methods + +##### getAccount(accountId: string): Promise + +Fetches account information from Stellar network. + +**Parameters:** +- `accountId` - Stellar account public key (starts with 'G') + +**Returns:** Promise resolving to Account object + +**Throws:** +- `ChenAIKitError` with code `ACCOUNT_NOT_FOUND` if account doesn't exist +- `ChenAIKitError` with code `NETWORK_ERROR` if network request fails + +**Example:** +```typescript +const account = await stellar.getAccount('GABC...'); +console.log('Account ID:', account.id); +console.log('Sequence:', account.sequence); +console.log('Balances:', account.balances); +``` + +##### getAccountBalances(accountId: string): Promise + +Fetches account balances. + +**Parameters:** +- `accountId` - Stellar account public key + +**Returns:** Promise resolving to array of Balance objects + +**Example:** +```typescript +const balances = await stellar.getAccountBalances('GABC...'); +balances.forEach(balance => { + console.log(`${balance.asset_type}: ${balance.balance}`); +}); +``` + +##### getAccountTransactions(accountId: string, options?: TransactionOptions): Promise + +Fetches account transaction history. + +**Parameters:** +- `accountId` - Stellar account public key +- `options.limit` - Maximum number of transactions (default: 10, max: 200) +- `options.order` - Sort order ('asc' | 'desc', default: 'desc') +- `options.cursor` - Pagination cursor + +**Returns:** Promise resolving to array of Transaction objects + +**Example:** +```typescript +const transactions = await stellar.getAccountTransactions('GABC...', { + limit: 50, + order: 'desc' +}); + +transactions.forEach(tx => { + console.log(`${tx.id}: ${tx.operation_count} operations`); +}); +``` + +##### invokeContract(contractId: string, method: string, args: any[]): Promise + +Invokes a Soroban smart contract method. + +**Parameters:** +- `contractId` - Contract address (starts with 'C') +- `method` - Contract method name +- `args` - Array of arguments to pass to the method + +**Returns:** Promise resolving to contract method return value + +**Example:** +```typescript +const score = await stellar.invokeContract( + 'CAAAA...', + 'get_score', + ['GABC...'] +); +console.log('Credit score:', score); +``` + +##### submitTransaction(transaction: Transaction): Promise + +Submits a signed transaction to the network. + +**Parameters:** +- `transaction` - Signed Stellar transaction + +**Returns:** Promise resolving to transaction result + +**Example:** +```typescript +const result = await stellar.submitTransaction(signedTx); +console.log('Transaction hash:', result.hash); +console.log('Ledger:', result.ledger); +``` + +--- + +## AI Module + +### AIService + +Main class for AI operations including credit scoring and fraud detection. + +#### Constructor + +```typescript +new AIService(config: AIConfig) +``` + +**Parameters:** +- `config.apiKey` - AI service API key +- `config.baseUrl` - Optional custom base URL +- `config.timeout` - Optional request timeout (default: 60000) +- `config.retries` - Optional number of retries (default: 3) + +**Example:** +```typescript +import { AIService } from '@chenaikit/core'; + +const ai = new AIService({ + apiKey: process.env.AI_API_KEY, + baseUrl: 'https://api.chenaikit.com', + timeout: 60000 +}); +``` + +#### Methods + +##### calculateCreditScore(accountData: AccountData): Promise + +Calculates credit score for account data using AI models. + +**Parameters:** +- `accountData` - Account information object containing balances, transactions, etc. + +**Returns:** Promise resolving to credit score (0-1000) + +**Example:** +```typescript +const account = await stellar.getAccount('GABC...'); +const score = await ai.calculateCreditScore(account); +console.log(`Credit Score: ${score}/1000`); +``` + +##### getScoreFactors(accountData: AccountData): Promise + +Returns factors that influenced the credit score. + +**Parameters:** +- `accountData` - Account information object + +**Returns:** Promise resolving to array of score factors + +**Example:** +```typescript +const factors = await ai.getScoreFactors(account); +factors.forEach(factor => { + console.log(`${factor.name}: ${factor.impact} (${factor.weight}%)`); +}); +``` + +##### detectFraud(transactionData: TransactionData): Promise + +Detects fraud in transaction data using AI models. + +**Parameters:** +- `transactionData` - Transaction information object + +**Returns:** Promise resolving to fraud detection result + +**Example:** +```typescript +const result = await ai.detectFraud(transaction); +console.log('Is Fraud:', result.isFraud); +console.log('Confidence:', result.confidence); +console.log('Risk Factors:', result.riskFactors); +``` + +##### getRiskFactors(transactionData: TransactionData): Promise + +Returns risk factors identified in the transaction. + +**Parameters:** +- `transactionData` - Transaction information object + +**Returns:** Promise resolving to array of risk factors + +**Example:** +```typescript +const risks = await ai.getRiskFactors(transaction); +risks.forEach(risk => { + console.log(`${risk.type}: ${risk.severity} - ${risk.description}`); +}); +``` + +### CreditScorer + +Specialized class for credit scoring operations with advanced features. + +#### Constructor + +```typescript +new CreditScorer(config: AIConfig) +``` + +#### Methods + +##### calculateScore(accountData: AccountData, options?: ScoringOptions): Promise + +Calculates credit score with detailed breakdown. + +**Parameters:** +- `accountData` - Account information +- `options.includeFactors` - Include factor breakdown (default: true) +- `options.includeHistory` - Include historical scores (default: false) + +**Returns:** Promise resolving to detailed credit score object + +**Example:** +```typescript +import { CreditScorer } from '@chenaikit/core'; + +const scorer = new CreditScorer({ apiKey: process.env.AI_API_KEY }); +const result = await scorer.calculateScore(account, { + includeFactors: true, + includeHistory: true +}); + +console.log('Score:', result.score); +console.log('Grade:', result.grade); // A, B, C, D, F +console.log('Factors:', result.factors); +console.log('History:', result.history); +``` + +##### compareScores(accountId1: string, accountId2: string): Promise + +Compares credit scores between two accounts. + +**Parameters:** +- `accountId1` - First account ID +- `accountId2` - Second account ID + +**Returns:** Promise resolving to comparison result + +**Example:** +```typescript +const comparison = await scorer.compareScores('GABC...', 'GDEF...'); +console.log('Difference:', comparison.difference); +console.log('Better Account:', comparison.betterAccount); +``` + +### FraudDetector + +Specialized class for fraud detection operations. + +#### Constructor + +```typescript +new FraudDetector(config: AIConfig) +``` + +#### Methods + +##### detectAnomalies(transactionData: TransactionData): Promise + +Detects anomalies in transaction data. + +**Parameters:** +- `transactionData` - Transaction information + +**Returns:** Promise resolving to array of detected anomalies + +**Example:** +```typescript +import { FraudDetector } from '@chenaikit/core'; + +const detector = new FraudDetector({ apiKey: process.env.AI_API_KEY }); +const anomalies = await detector.detectAnomalies(transaction); + +anomalies.forEach(anomaly => { + console.log(`${anomaly.type}: ${anomaly.severity}`); + console.log(`Description: ${anomaly.description}`); +}); +``` + +##### analyzePattern(transactions: Transaction[]): Promise + +Analyzes patterns across multiple transactions. + +**Parameters:** +- `transactions` - Array of transactions to analyze + +**Returns:** Promise resolving to pattern analysis result + +**Example:** +```typescript +const transactions = await stellar.getAccountTransactions('GABC...', { + limit: 100 +}); +const analysis = await detector.analyzePattern(transactions); + +console.log('Suspicious Patterns:', analysis.suspiciousPatterns); +console.log('Risk Score:', analysis.riskScore); +``` + +--- + +## Blockchain Module + +### TransactionMonitor + +Real-time transaction monitoring with WebSocket streaming. + +#### Constructor + +```typescript +new TransactionMonitor(config: MonitoringConfig) +``` + +**Parameters:** +- `config.horizonUrl` - Stellar Horizon API URL +- `config.network` - Network ('testnet' | 'mainnet') +- `config.reconnectInterval` - Auto-reconnect interval in ms (default: 5000) +- `config.maxReconnectAttempts` - Max reconnection attempts (default: 10) +- `config.batchSize` - Processing batch size (default: 100) +- `config.alertThresholds` - Alert configuration +- `config.filters` - Transaction filters + +**Example:** +```typescript +import { TransactionMonitor } from '@chenaikit/core'; + +const monitor = new TransactionMonitor({ + horizonUrl: 'https://horizon-testnet.stellar.org', + network: 'testnet', + alertThresholds: { + highVolumeAmount: 10000, + rapidTransactionCount: 20, + rapidTransactionWindow: 300000 + }, + filters: { + accounts: ['GABC...', 'GDEF...'], + minAmount: 100 + } +}); +``` + +#### Methods + +##### start(): Promise + +Starts the transaction monitor. + +**Example:** +```typescript +await monitor.start(); +console.log('Monitor started'); +``` + +##### stop(): Promise + +Stops the transaction monitor. + +**Example:** +```typescript +await monitor.stop(); +console.log('Monitor stopped'); +``` + +##### addFilter(filter: TransactionFilter): void + +Adds a transaction filter. + +**Parameters:** +- `filter.account` - Filter by account +- `filter.assetType` - Filter by asset type +- `filter.minAmount` - Minimum transaction amount +- `filter.maxAmount` - Maximum transaction amount + +**Example:** +```typescript +monitor.addFilter({ + account: 'GABC...', + minAmount: 1000, + assetType: 'native' +}); +``` + +##### addAlertRule(rule: AlertRule): void + +Adds an alert rule. + +**Parameters:** +- `rule.type` - Alert type ('high_value' | 'fraud' | 'rapid_transactions' | 'suspicious_pattern') +- `rule.condition` - Condition to trigger alert +- `rule.action` - Action to take ('webhook' | 'email' | 'log') +- `rule.threshold` - Threshold value + +**Example:** +```typescript +monitor.addAlertRule({ + type: 'high_value', + threshold: 50000, + action: 'webhook', + webhookUrl: 'https://api.example.com/alerts' +}); +``` + +#### Events + +##### on('transaction', handler: (tx: Transaction, analysis: TransactionAnalysis) => void) + +Emitted when a new transaction is detected. + +**Example:** +```typescript +monitor.on('transaction', (tx, analysis) => { + console.log(`New transaction: ${tx.hash}`); + console.log(`Category: ${analysis.category}`); + console.log(`Risk Score: ${analysis.riskScore}`); +}); +``` + +##### on('alert', handler: (alert: Alert) => void) + +Emitted when an alert is triggered. + +**Example:** +```typescript +monitor.on('alert', (alert) => { + console.log(`Alert: ${alert.title}`); + console.log(`Severity: ${alert.severity}`); + console.log(`Details: ${alert.details}`); +}); +``` + +##### on('error', handler: (error: Error) => void) + +Emitted when an error occurs. + +**Example:** +```typescript +monitor.on('error', (error) => { + console.error('Monitor error:', error.message); +}); +``` + +--- + +## Utils Module + +### ValidationRules + +Validation utilities for forms and data. + +#### Methods + +##### email(message?: string): ValidationRule + +Creates email validation rule. + +**Example:** +```typescript +import { ValidationRules } from '@chenaikit/core'; + +const emailRule = ValidationRules.email('Invalid email address'); +const result = emailRule('user@example.com'); +// result: null (valid) +``` + +##### stellarAddress(message?: string): ValidationRule + +Creates Stellar address validation rule. + +**Example:** +```typescript +const addressRule = ValidationRules.stellarAddress('Invalid Stellar address'); +const result = addressRule('GABC...'); +// result: null if valid, error message if invalid +``` + +##### required(message?: string): ValidationRule + +Creates required field validation rule. + +**Example:** +```typescript +const requiredRule = ValidationRules.required('This field is required'); +``` + +##### minLength(length: number, message?: string): ValidationRule + +Creates minimum length validation rule. + +**Example:** +```typescript +const minRule = ValidationRules.minLength(8, 'Must be at least 8 characters'); +``` + +##### custom(validator: (value: any) => string | null): ValidationRule + +Creates custom validation rule. + +**Example:** +```typescript +const customRule = ValidationRules.custom((value) => { + if (value === 'forbidden') { + return 'This value is not allowed'; + } + return null; +}); +``` + +### ChartHelpers + +Utilities for data visualization. + +#### Methods + +##### formatChartData(data: any[], xKey: string, yKey: string): ChartData[] + +Formats data for chart libraries. + +**Example:** +```typescript +import { ChartHelpers } from '@chenaikit/core'; + +const transactions = [...]; // Array of transactions +const chartData = ChartHelpers.formatChartData( + transactions, + 'created_at', + 'amount' +); +``` + +##### aggregateByTime(data: any[], timeKey: string, valueKey: string, interval: 'hour' | 'day' | 'week'): AggregatedData[] + +Aggregates data by time intervals. + +**Example:** +```typescript +const dailyVolume = ChartHelpers.aggregateByTime( + transactions, + 'created_at', + 'amount', + 'day' +); +``` + +### ExportUtils + +Utilities for exporting data. + +#### Methods + +##### toCSV(data: any[], filename: string): void + +Exports data to CSV file. + +**Example:** +```typescript +import { ExportUtils } from '@chenaikit/core'; + +ExportUtils.toCSV(transactions, 'transactions.csv'); +``` + +##### toJSON(data: any[], filename: string): void + +Exports data to JSON file. + +**Example:** +```typescript +ExportUtils.toJSON(accountData, 'account-data.json'); +``` + +--- + +## Types + +### StellarConfig + +```typescript +interface StellarConfig { + network: 'testnet' | 'mainnet'; + horizonUrl?: string; + timeout?: number; +} +``` + +### AIConfig + +```typescript +interface AIConfig { + apiKey: string; + baseUrl?: string; + timeout?: number; + retries?: number; +} +``` + +### Account + +```typescript +interface Account { + id: string; + account_id: string; + sequence: string; + balances: Balance[]; + subentry_count: number; + thresholds: { + low_threshold: number; + med_threshold: number; + high_threshold: number; + }; + flags: { + auth_required: boolean; + auth_revocable: boolean; + auth_immutable: boolean; + }; + signers: Signer[]; +} +``` + +### Balance + +```typescript +interface Balance { + asset_type: string; + asset_code?: string; + asset_issuer?: string; + balance: string; + limit?: string; + buying_liabilities?: string; + selling_liabilities?: string; +} +``` + +### Transaction + +```typescript +interface Transaction { + id: string; + hash: string; + ledger: number; + created_at: string; + source_account: string; + source_account_sequence: string; + fee_charged: string; + operation_count: number; + envelope_xdr: string; + result_xdr: string; + result_meta_xdr: string; + successful: boolean; +} +``` + +### CreditScore + +```typescript +interface CreditScore { + score: number; + grade: 'A' | 'B' | 'C' | 'D' | 'F'; + factors: ScoreFactor[]; + history?: HistoricalScore[]; + calculatedAt: Date; +} +``` + +### ScoreFactor + +```typescript +interface ScoreFactor { + name: string; + impact: 'positive' | 'negative' | 'neutral'; + weight: number; + value: any; + description: string; +} +``` + +### FraudResult + +```typescript +interface FraudResult { + isFraud: boolean; + confidence: number; + riskScore: number; + riskFactors: RiskFactor[]; + recommendation: string; +} +``` + +### RiskFactor + +```typescript +interface RiskFactor { + type: string; + severity: 'low' | 'medium' | 'high' | 'critical'; + description: string; + evidence: any; +} +``` + +### Alert + +```typescript +interface Alert { + id: string; + type: 'high_value' | 'fraud' | 'rapid_transactions' | 'suspicious_pattern'; + title: string; + severity: 'low' | 'medium' | 'high' | 'critical'; + details: string; + transaction?: Transaction; + timestamp: Date; + acknowledged: boolean; +} +``` + +--- + +## Error Handling + +All methods may throw `ChenAIKitError`: + +```typescript +class ChenAIKitError extends Error { + constructor( + message: string, + public code: string, + public details?: any + ) { + super(message); + this.name = 'ChenAIKitError'; + } +} +``` + +### Error Codes + +- `ACCOUNT_NOT_FOUND` - Stellar account doesn't exist +- `NETWORK_ERROR` - Network request failed +- `INVALID_PARAMETER` - Invalid parameter provided +- `API_ERROR` - AI service API error +- `CONTRACT_ERROR` - Smart contract execution error +- `VALIDATION_ERROR` - Data validation failed +- `TIMEOUT_ERROR` - Request timeout +- `AUTHENTICATION_ERROR` - Authentication failed + +### Example Error Handling + +```typescript +try { + const account = await stellar.getAccount('GABC...'); +} catch (error) { + if (error instanceof ChenAIKitError) { + console.error(`Error ${error.code}: ${error.message}`); + console.error('Details:', error.details); + } else { + console.error('Unexpected error:', error); + } +} +``` + +--- + +## Examples + +### Complete Credit Scoring Example + +```typescript +import { StellarConnector, CreditScorer } from '@chenaikit/core'; + +async function analyzeCreditworthiness(accountId: string) { + // Initialize services + const stellar = new StellarConnector({ network: 'testnet' }); + const scorer = new CreditScorer({ apiKey: process.env.AI_API_KEY }); + + // Fetch account data + const account = await stellar.getAccount(accountId); + const transactions = await stellar.getAccountTransactions(accountId, { + limit: 100 + }); + + // Calculate credit score + const result = await scorer.calculateScore(account, { + includeFactors: true, + includeHistory: true + }); + + // Display results + console.log(`Credit Score: ${result.score}/1000 (Grade: ${result.grade})`); + console.log('\nScore Factors:'); + result.factors.forEach(factor => { + console.log(` ${factor.name}: ${factor.impact} (${factor.weight}%)`); + }); + + return result; +} +``` + +### Real-time Monitoring Example + +```typescript +import { TransactionMonitor, FraudDetector } from '@chenaikit/core'; + +async function monitorTransactions() { + const monitor = new TransactionMonitor({ + horizonUrl: 'https://horizon-testnet.stellar.org', + network: 'testnet', + alertThresholds: { + highVolumeAmount: 10000, + rapidTransactionCount: 20 + } + }); + + const detector = new FraudDetector({ apiKey: process.env.AI_API_KEY }); + + // Handle transactions + monitor.on('transaction', async (tx, analysis) => { + console.log(`Transaction: ${tx.hash}`); + + // Check for fraud + const fraudResult = await detector.detectFraud(tx); + if (fraudResult.isFraud) { + console.log(`āš ļø Fraud detected! Confidence: ${fraudResult.confidence}`); + } + }); + + // Handle alerts + monitor.on('alert', (alert) => { + console.log(`🚨 Alert: ${alert.title} (${alert.severity})`); + }); + + // Start monitoring + await monitor.start(); +} +``` + +--- + +## See Also + +- [Getting Started Guide](../getting-started.md) +- [Tutorials](../tutorials/) +- [Architecture Documentation](../architecture/) +- [Examples](../../examples/) diff --git a/docs/architecture/adrs/001-monorepo-structure.md b/docs/architecture/adrs/001-monorepo-structure.md new file mode 100644 index 0000000..5521630 --- /dev/null +++ b/docs/architecture/adrs/001-monorepo-structure.md @@ -0,0 +1,118 @@ +# ADR 001: Monorepo Structure with pnpm Workspaces + +## Status +Accepted + +## Context +ChenAIKit consists of multiple interconnected packages (core SDK, CLI, backend, frontend, examples) that share code and dependencies. We needed to decide on a repository structure that would: + +- Enable code sharing between packages +- Simplify dependency management +- Support independent versioning +- Facilitate coordinated releases +- Improve developer experience + +## Decision +We will use a monorepo structure managed by pnpm workspaces. + +### Repository Structure +``` +chenaikit/ +ā”œā”€ā”€ packages/ +│ ā”œā”€ā”€ core/ # Core TypeScript SDK +│ └── cli/ # CLI tool +ā”œā”€ā”€ backend/ # Backend services +ā”œā”€ā”€ frontend/ # Frontend applications +ā”œā”€ā”€ contracts/ # Soroban smart contracts +ā”œā”€ā”€ examples/ # Sample applications +ā”œā”€ā”€ docs/ # Documentation +└── tests/ # Shared test utilities +``` + +### Workspace Configuration +```json +{ + "workspaces": [ + "packages/*", + "examples/*", + "tests/*" + ] +} +``` + +## Consequences + +### Positive +- **Code Sharing**: Packages can easily import from each other using workspace protocol (`workspace:*`) +- **Dependency Management**: Single `pnpm-lock.yaml` ensures consistent versions +- **Atomic Changes**: Changes across multiple packages can be committed together +- **Simplified CI/CD**: Single repository to clone and test +- **Better Refactoring**: IDE support for cross-package refactoring +- **Faster Development**: No need to publish packages locally for testing + +### Negative +- **Build Complexity**: Need to manage build order and dependencies +- **Larger Repository**: More code to clone initially +- **CI Time**: All packages tested even if only one changes (mitigated with change detection) +- **Learning Curve**: Developers need to understand workspace concepts + +### Neutral +- **Tooling**: Requires pnpm (not npm/yarn) for workspace features +- **Scripts**: Need root-level scripts to coordinate package operations + +## Alternatives Considered + +### Multi-repo (Separate Repositories) +- **Pros**: Clear boundaries, independent releases, smaller clones +- **Cons**: Difficult code sharing, version management complexity, harder to coordinate changes +- **Rejected**: Too much overhead for our team size and release cadence + +### Lerna + npm/yarn +- **Pros**: More mature tooling, wider adoption +- **Cons**: Slower than pnpm, more complex configuration, less efficient disk usage +- **Rejected**: pnpm workspaces are simpler and faster + +### Nx Monorepo +- **Pros**: Advanced caching, task orchestration, change detection +- **Cons**: Additional complexity, opinionated structure, learning curve +- **Rejected**: Overkill for our current needs, can migrate later if needed + +## Implementation Notes + +### Package References +Packages reference each other using workspace protocol: +```json +{ + "dependencies": { + "@chenaikit/core": "workspace:*" + } +} +``` + +### Build Scripts +Root package.json includes coordinated scripts: +```json +{ + "scripts": { + "build": "pnpm -r build", + "test": "pnpm -r test", + "lint": "pnpm -r lint" + } +} +``` + +### CI/CD Strategy +- Use pnpm's built-in change detection +- Cache node_modules and build artifacts +- Run tests in parallel where possible + +## References +- [pnpm Workspaces Documentation](https://pnpm.io/workspaces) +- [Monorepo Best Practices](https://monorepo.tools/) +- [Why pnpm?](https://pnpm.io/motivation) + +## Date +2024-10-04 + +## Authors +ChenAIKit Team diff --git a/docs/architecture/adrs/002-stellar-soroban-blockchain.md b/docs/architecture/adrs/002-stellar-soroban-blockchain.md new file mode 100644 index 0000000..546d99d --- /dev/null +++ b/docs/architecture/adrs/002-stellar-soroban-blockchain.md @@ -0,0 +1,200 @@ +# ADR 002: Stellar and Soroban for Blockchain Layer + +## Status +Accepted + +## Context +ChenAIKit requires blockchain functionality for: +- Decentralized credit scoring storage +- Transparent fraud detection records +- Immutable transaction history +- Smart contract execution for business logic +- Cross-border payment capabilities + +We needed to choose a blockchain platform that provides: +- Smart contract capabilities +- Low transaction costs +- Fast finality +- Good developer experience +- Active ecosystem + +## Decision +We will use Stellar as our primary blockchain platform with Soroban for smart contracts. + +### Technology Stack +- **Stellar Network**: Layer 1 blockchain for payments and asset issuance +- **Soroban**: Smart contract platform built on Stellar +- **Horizon API**: REST API for Stellar network interaction +- **Stellar SDK**: JavaScript/TypeScript SDK for client applications +- **Rust**: Programming language for Soroban contracts + +## Rationale + +### Why Stellar? + +1. **Low Cost**: Transaction fees are ~$0.00001, making it economical for high-volume operations +2. **Fast Finality**: 3-5 second transaction confirmation +3. **Built-in DEX**: Native decentralized exchange for asset trading +4. **Asset Issuance**: Easy creation of custom tokens +5. **Compliance**: Built-in compliance features (authorized accounts, clawback) +6. **Mature Ecosystem**: 8+ years of production use + +### Why Soroban? + +1. **Modern Language**: Rust provides memory safety and performance +2. **WebAssembly**: Contracts compile to WASM for portability +3. **Stellar Integration**: Native access to Stellar accounts and assets +4. **Developer Experience**: Excellent tooling and documentation +5. **Cost Efficiency**: Optimized for low gas costs +6. **Security**: Strong type system and ownership model + +## Consequences + +### Positive +- **Low Operational Costs**: Minimal fees for transactions and contract execution +- **Fast User Experience**: Quick transaction finality improves UX +- **Rich Functionality**: Access to DEX, multi-sig, and asset features +- **Developer Productivity**: Rust's tooling and safety features +- **Ecosystem Support**: Active community and extensive documentation +- **Compliance Ready**: Built-in features for regulatory requirements + +### Negative +- **Learning Curve**: Developers need to learn Rust and Soroban +- **Ecosystem Size**: Smaller than Ethereum (but growing rapidly) +- **Contract Limitations**: Some restrictions compared to EVM chains +- **Tooling Maturity**: Soroban is newer than established platforms + +### Neutral +- **Network Effects**: Need to build on Stellar's existing ecosystem +- **Interoperability**: Limited direct bridges to other chains (can be added) + +## Alternatives Considered + +### Ethereum + Solidity +- **Pros**: Largest ecosystem, most developers, extensive tooling +- **Cons**: High gas fees ($5-50+ per transaction), slower finality (12-15s), complex development +- **Rejected**: Cost prohibitive for our use case + +### Polygon/L2 Solutions +- **Pros**: Lower fees than Ethereum, EVM compatibility +- **Cons**: Still higher fees than Stellar, additional complexity, bridge risks +- **Rejected**: Stellar provides better cost/performance ratio + +### Solana + Rust +- **Pros**: Very fast, low fees, Rust-based +- **Cons**: Network stability concerns, complex programming model, less mature tooling +- **Rejected**: Stellar offers better stability and developer experience + +### Cosmos SDK +- **Pros**: Flexible, IBC for interoperability, Rust support +- **Cons**: Need to run own chain or find suitable zone, higher operational complexity +- **Rejected**: Too much infrastructure overhead + +## Implementation Details + +### Smart Contracts +We implement three core contracts in Soroban: + +1. **Credit Score Contract** + - Store and calculate credit scores + - Access control for score updates + - Oracle integration for external data + +2. **Fraud Detection Contract** + - Pattern recognition and risk scoring + - Alert generation + - Historical fraud data storage + +3. **Governance Contract** + - Voting mechanisms + - Timelock for critical operations + - Proposal management + +### Backend Integration +```typescript +import { StellarConnector } from '@chenaikit/core'; + +const stellar = new StellarConnector({ + network: 'mainnet', + horizonUrl: 'https://horizon.stellar.org' +}); + +// Interact with contracts +const score = await stellar.invokeContract( + contractId, + 'calculate_score', + [accountAddress] +); +``` + +### Network Strategy +- **Development**: Stellar testnet for development and testing +- **Staging**: Stellar testnet with production-like data +- **Production**: Stellar mainnet (public network) + +## Migration Path + +If we need to support additional blockchains in the future: + +1. **Abstract Blockchain Layer**: Create interface for blockchain operations +2. **Adapter Pattern**: Implement adapters for each blockchain +3. **Multi-Chain Support**: Allow users to choose their preferred chain +4. **Bridge Contracts**: Enable cross-chain functionality + +```typescript +interface BlockchainAdapter { + deployContract(wasm: Buffer): Promise; + invokeContract(id: string, method: string, args: any[]): Promise; + getAccount(address: string): Promise; +} + +class StellarAdapter implements BlockchainAdapter { /* ... */ } +class EthereumAdapter implements BlockchainAdapter { /* ... */ } +``` + +## Performance Considerations + +### Transaction Throughput +- Stellar: ~1000 TPS (operations per second) +- Sufficient for our current scale +- Can batch operations for efficiency + +### Contract Execution +- Soroban contracts execute in milliseconds +- Gas costs are predictable and low +- Optimization techniques available (WASM size reduction) + +### Data Storage +- Use contract storage for critical data +- Use Horizon API for historical queries +- Cache frequently accessed data in backend + +## Security Considerations + +### Contract Security +- Comprehensive testing with Soroban SDK test utilities +- Access control on all sensitive operations +- Upgrade mechanisms for bug fixes +- External security audits before mainnet deployment + +### Key Management +- Use Stellar's multi-signature capabilities +- Hardware wallet support for production keys +- Separate keys for different environments + +### Network Security +- Use HTTPS for all Horizon API calls +- Validate all transaction signatures +- Implement rate limiting on contract calls + +## References +- [Stellar Documentation](https://developers.stellar.org/) +- [Soroban Documentation](https://soroban.stellar.org/docs) +- [Stellar Consensus Protocol](https://www.stellar.org/papers/stellar-consensus-protocol) +- [Soroban by Example](https://soroban.stellar.org/docs/examples) + +## Date +2024-10-04 + +## Authors +ChenAIKit Team diff --git a/docs/architecture/adrs/003-typescript-sdk-design.md b/docs/architecture/adrs/003-typescript-sdk-design.md new file mode 100644 index 0000000..2f751a5 --- /dev/null +++ b/docs/architecture/adrs/003-typescript-sdk-design.md @@ -0,0 +1,369 @@ +# ADR 003: TypeScript SDK Design and Architecture + +## Status +Accepted + +## Context +ChenAIKit needs a developer-friendly SDK that abstracts blockchain and AI complexity while providing: +- Type safety for better developer experience +- Modular architecture for tree-shaking +- Support for both Node.js and browser environments +- Extensibility for future features +- Clear separation of concerns + +## Decision +We will build a TypeScript-first SDK with a modular architecture organized by domain. + +### SDK Structure +``` +@chenaikit/core/ +ā”œā”€ā”€ src/ +│ ā”œā”€ā”€ stellar/ # Stellar network operations +│ ā”œā”€ā”€ ai/ # AI service integrations +│ ā”œā”€ā”€ blockchain/ # Blockchain monitoring & governance +│ ā”œā”€ā”€ utils/ # Shared utilities +│ ā”œā”€ā”€ types/ # TypeScript type definitions +│ └── index.ts # Main entry point +``` + +### Module Organization +Each domain module exports a focused API: +- **stellar/**: `StellarConnector`, `AssetManager`, `DEXIntegration` +- **ai/**: `AIService`, `CreditScorer`, `FraudDetector` +- **blockchain/**: `TransactionMonitor`, `GovernanceClient` +- **utils/**: `ValidationRules`, `ChartHelpers`, `ExportUtils` + +## Rationale + +### Why TypeScript? + +1. **Type Safety**: Catch errors at compile time, not runtime +2. **IDE Support**: Excellent autocomplete and inline documentation +3. **Refactoring**: Safe refactoring across the codebase +4. **Documentation**: Types serve as living documentation +5. **Ecosystem**: Largest JavaScript ecosystem with type definitions + +### Why Modular Architecture? + +1. **Tree Shaking**: Unused code is eliminated in production builds +2. **Clear Boundaries**: Each module has a single responsibility +3. **Independent Testing**: Modules can be tested in isolation +4. **Parallel Development**: Teams can work on different modules +5. **Gradual Adoption**: Users can import only what they need + +### Design Principles + +1. **Explicit over Implicit**: Clear, verbose APIs over magic +2. **Fail Fast**: Validate inputs early and throw descriptive errors +3. **Async by Default**: All I/O operations return Promises +4. **Immutable Data**: Avoid mutating input parameters +5. **Composable**: Small, focused functions that work together + +## Consequences + +### Positive +- **Developer Experience**: IntelliSense, type checking, and refactoring support +- **Maintainability**: Clear structure makes code easier to understand +- **Performance**: Tree-shaking reduces bundle size for web apps +- **Reliability**: Type system catches many bugs before runtime +- **Documentation**: Types provide inline documentation +- **Testing**: Easier to mock and test individual modules + +### Negative +- **Build Step**: Requires TypeScript compilation +- **Learning Curve**: Developers need TypeScript knowledge +- **Verbosity**: More code compared to plain JavaScript +- **Compilation Time**: Adds time to development workflow + +### Neutral +- **Type Definitions**: Need to maintain types for all public APIs +- **Breaking Changes**: Type changes can be breaking changes + +## API Design Patterns + +### 1. Configuration Objects +Use configuration objects instead of multiple parameters: + +```typescript +// Good +const stellar = new StellarConnector({ + network: 'testnet', + horizonUrl: 'https://horizon-testnet.stellar.org', + timeout: 30000 +}); + +// Avoid +const stellar = new StellarConnector('testnet', 'https://...', 30000); +``` + +### 2. Builder Pattern for Complex Objects +```typescript +const monitor = new TransactionMonitor(config) + .addFilter({ account: 'GABC...' }) + .addAlertRule({ + type: 'high_value', + threshold: 10000, + action: 'webhook' + }) + .on('alert', handleAlert); + +await monitor.start(); +``` + +### 3. Async/Await for I/O +```typescript +// All I/O operations are async +async function getAccountScore(accountId: string): Promise { + const account = await stellar.getAccount(accountId); + const score = await ai.calculateCreditScore(account); + return score; +} +``` + +### 4. Error Handling +```typescript +class ChenAIKitError extends Error { + constructor( + message: string, + public code: string, + public details?: any + ) { + super(message); + this.name = 'ChenAIKitError'; + } +} + +// Usage +throw new ChenAIKitError( + 'Account not found', + 'ACCOUNT_NOT_FOUND', + { accountId } +); +``` + +### 5. Event Emitters for Real-time Updates +```typescript +import { EventEmitter } from 'eventemitter3'; + +class TransactionMonitor extends EventEmitter { + on(event: 'transaction', handler: (tx: Transaction) => void): this; + on(event: 'alert', handler: (alert: Alert) => void): this; + on(event: string, handler: (...args: any[]) => void): this { + return super.on(event, handler); + } +} +``` + +## Type System Design + +### Strict Type Checking +```json +{ + "compilerOptions": { + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noUnusedLocals": true, + "noUnusedParameters": true + } +} +``` + +### Discriminated Unions +```typescript +type TransactionStatus = + | { status: 'pending'; submittedAt: Date } + | { status: 'confirmed'; confirmedAt: Date; ledger: number } + | { status: 'failed'; error: string }; + +function handleTransaction(tx: TransactionStatus) { + switch (tx.status) { + case 'pending': + console.log('Submitted at', tx.submittedAt); + break; + case 'confirmed': + console.log('Confirmed in ledger', tx.ledger); + break; + case 'failed': + console.log('Failed:', tx.error); + break; + } +} +``` + +### Generic Types for Flexibility +```typescript +interface Repository { + find(id: string): Promise; + findAll(): Promise; + create(data: Omit): Promise; + update(id: string, data: Partial): Promise; + delete(id: string): Promise; +} + +class AccountRepository implements Repository { + // Implementation +} +``` + +## Module Exports + +### Barrel Exports +Each module has an index.ts that re-exports public APIs: + +```typescript +// src/stellar/index.ts +export { StellarConnector } from './connector'; +export { AssetManager } from './assets'; +export { DEXIntegration } from './dex'; +export type { StellarConfig, Account, Balance } from './types'; +``` + +### Main Entry Point +```typescript +// src/index.ts +export * from './stellar'; +export * from './ai'; +export * from './blockchain'; +export * from './utils'; +export type * from './types'; +``` + +### Tree-Shakeable Exports +Users can import specific modules: +```typescript +// Import everything +import { StellarConnector, AIService } from '@chenaikit/core'; + +// Import specific module (better for tree-shaking) +import { StellarConnector } from '@chenaikit/core/stellar'; +import { AIService } from '@chenaikit/core/ai'; +``` + +## Browser vs Node.js Support + +### Conditional Exports +```json +{ + "exports": { + ".": { + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js", + "types": "./dist/types/index.d.ts" + }, + "./stellar": { + "import": "./dist/esm/stellar/index.js", + "require": "./dist/cjs/stellar/index.js", + "types": "./dist/types/stellar/index.d.ts" + } + } +} +``` + +### Platform-Specific Code +```typescript +// Use conditional imports for platform-specific features +const WebSocket = typeof window !== 'undefined' + ? window.WebSocket + : require('ws'); +``` + +## Testing Strategy + +### Unit Tests +- Test each module in isolation +- Mock external dependencies +- Use Jest with ts-jest + +### Integration Tests +- Test module interactions +- Use real testnet for blockchain operations +- Mock AI services with predictable responses + +### Type Tests +```typescript +// Ensure types are correct +import { expectType } from 'tsd'; + +const connector = new StellarConnector({ network: 'testnet' }); +const account = await connector.getAccount('GABC...'); + +expectType(account); +expectType(account.balances); +``` + +## Documentation Strategy + +### TSDoc Comments +```typescript +/** + * Calculates credit score for a Stellar account. + * + * @param accountId - Stellar account public key (G...) + * @returns Credit score between 0-1000 + * @throws {ChenAIKitError} If account not found or API error + * + * @example + * ```typescript + * const score = await ai.calculateCreditScore('GABC...'); + * console.log(`Score: ${score}/1000`); + * ``` + */ +async calculateCreditScore(accountId: string): Promise { + // Implementation +} +``` + +### Generated API Docs +Use TypeDoc to generate API documentation from TSDoc comments: +```bash +typedoc --out docs/api src/index.ts +``` + +## Versioning and Breaking Changes + +### Semantic Versioning +- **Major**: Breaking changes to public API +- **Minor**: New features, backward compatible +- **Patch**: Bug fixes, backward compatible + +### Deprecation Strategy +```typescript +/** + * @deprecated Use `calculateCreditScore` instead. Will be removed in v2.0.0. + */ +async getCreditScore(accountId: string): Promise { + console.warn('getCreditScore is deprecated, use calculateCreditScore'); + return this.calculateCreditScore(accountId); +} +``` + +## Alternatives Considered + +### Plain JavaScript +- **Pros**: No build step, simpler setup +- **Cons**: No type safety, poor IDE support, more runtime errors +- **Rejected**: Type safety is critical for SDK reliability + +### Flow +- **Pros**: Type checking for JavaScript +- **Cons**: Smaller ecosystem, less tooling support, declining adoption +- **Rejected**: TypeScript has better ecosystem and tooling + +### ReScript/Reason +- **Pros**: Strong type system, functional programming +- **Cons**: Steep learning curve, smaller ecosystem, unfamiliar syntax +- **Rejected**: TypeScript is more accessible to JavaScript developers + +## References +- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html) +- [TypeScript Deep Dive](https://basarat.gitbook.io/typescript/) +- [API Design Patterns](https://www.patterns.dev/) +- [TSDoc Specification](https://tsdoc.org/) + +## Date +2024-10-04 + +## Authors +ChenAIKit Team diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..2dc6c1c --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,516 @@ +# Frequently Asked Questions (FAQ) + +Common questions about ChenAIKit. + +## General Questions + +### What is ChenAIKit? + +ChenAIKit is a TypeScript toolkit for building AI-powered blockchain applications. It provides ready-to-use integrations for credit scoring, fraud detection, and smart decisioning on the Stellar blockchain. + +### Who is ChenAIKit for? + +- **Developers** building fintech applications +- **Blockchain projects** needing AI capabilities +- **Financial institutions** exploring blockchain + AI +- **Startups** building credit/lending platforms +- **Researchers** studying blockchain and AI integration + +### Is ChenAIKit free? + +Yes, ChenAIKit is open source under the MIT License. You can use it freely in commercial and non-commercial projects. + +### What blockchain does ChenAIKit support? + +Currently, ChenAIKit supports Stellar and Soroban smart contracts. We plan to add support for additional blockchains in the future. + +--- + +## Technical Questions + +### What are the system requirements? + +- **Node.js**: 18.0.0 or higher +- **pnpm**: 8.0.0 or higher +- **Rust**: 1.70+ (for smart contracts) +- **PostgreSQL**: 13+ (for backend) +- **Redis**: 6+ (for caching) + +### Can I use ChenAIKit in the browser? + +Yes! The core SDK (`@chenaikit/core`) works in both Node.js and browser environments. Some features like file system operations are Node.js only. + +### Does ChenAIKit work with TypeScript? + +Absolutely! ChenAIKit is written in TypeScript and provides full type definitions for excellent IDE support and type safety. + +### Can I use ChenAIKit with JavaScript? + +Yes, you can use ChenAIKit with plain JavaScript. The TypeScript types are optional but recommended for better developer experience. + +### What databases are supported? + +The backend uses Prisma ORM, which supports: +- PostgreSQL (recommended) +- MySQL +- SQLite (development only) +- SQL Server +- MongoDB (preview) + +### Do I need to run my own Stellar node? + +No, you can use public Horizon servers: +- Testnet: `https://horizon-testnet.stellar.org` +- Mainnet: `https://horizon.stellar.org` + +For production applications with high volume, consider running your own Horizon instance. + +--- + +## Credit Scoring Questions + +### How is the credit score calculated? + +The credit score (0-1000) is calculated using AI models that analyze: +- Account age and history +- Transaction patterns and frequency +- Balance stability +- Network activity and reputation +- Asset diversity +- Payment history + +### Can I customize the credit scoring algorithm? + +Yes! You can: +1. Adjust scoring weights in the AI service configuration +2. Add custom factors to the scoring model +3. Train your own models using the provided framework +4. Integrate external data sources + +### How accurate is the credit scoring? + +Accuracy depends on the data quality and model training. Our default models achieve: +- 85-90% accuracy on testnet data +- Continuous improvement through feedback loops +- Regular model updates and retraining + +### Can I use credit scores for lending decisions? + +Credit scores are informational tools. For lending decisions: +- Combine with traditional credit checks +- Consider regulatory requirements +- Implement proper risk management +- Consult legal and compliance teams + +--- + +## Fraud Detection Questions + +### What types of fraud can ChenAIKit detect? + +- **Transaction fraud**: Unusual transaction patterns +- **Account takeover**: Suspicious account activity +- **Money laundering**: Rapid movement of funds +- **Wash trading**: Artificial volume creation +- **Phishing**: Suspicious address patterns + +### How does fraud detection work? + +Fraud detection uses: +1. **Pattern recognition**: Identifies unusual behavior +2. **Anomaly detection**: Flags statistical outliers +3. **Risk scoring**: Assigns risk levels (0-100) +4. **Machine learning**: Learns from historical data + +### What is the false positive rate? + +Default configuration: +- False positive rate: ~5-10% +- Adjustable through threshold tuning +- Improves with more training data + +### Can I train custom fraud models? + +Yes! The fraud detection system supports: +- Custom training data +- Adjustable thresholds +- Feature engineering +- Model fine-tuning + +--- + +## Smart Contract Questions + +### What programming language are contracts written in? + +Soroban smart contracts are written in Rust, which provides: +- Memory safety +- High performance +- Strong type system +- Excellent tooling + +### Do I need to know Rust to use ChenAIKit? + +No! You can use the pre-built contracts and interact with them through the TypeScript SDK. Rust knowledge is only needed if you want to modify or create new contracts. + +### How much does it cost to deploy a contract? + +On Stellar: +- **Testnet**: Free (use testnet XLM) +- **Mainnet**: ~0.1-1 XLM (~$0.01-0.10 USD) + +Costs vary based on contract size and network fees. + +### Can contracts be upgraded? + +Yes! Our contracts include upgrade functionality: +- Admin-controlled upgrades +- Version tracking +- Data migration support +- Rollback capabilities + +### Are the contracts audited? + +Yes, our contracts have undergone security audits. See [audit-report.md](../contracts/audit-report.md) for details. + +--- + +## API Questions + +### Is there a rate limit on the API? + +Yes, rate limits depend on your tier: +- **Free**: 100 requests/hour +- **Basic**: 1,000 requests/hour +- **Pro**: 10,000 requests/hour +- **Enterprise**: Custom limits + +### How do I get an API key? + +```bash +# Using CLI +npx @chenaikit/cli auth login +npx @chenaikit/cli keys create --name "My App" + +# Or via backend API +POST /api/v1/keys +{ + "name": "My App", + "tier": "basic" +} +``` + +### What authentication methods are supported? + +- **API Keys**: For server-to-server communication +- **JWT Tokens**: For user authentication +- **OAuth 2.0**: Coming soon + +### Can I use the API from the frontend? + +For security, API keys should only be used server-side. For frontend applications: +1. Use JWT authentication +2. Proxy requests through your backend +3. Implement proper CORS configuration + +--- + +## Deployment Questions + +### How do I deploy to production? + +See our [deployment guide](./tutorials/deploying-contracts.md) for detailed instructions. + +Quick overview: +1. Build all packages: `pnpm build` +2. Deploy contracts to mainnet +3. Configure production environment variables +4. Deploy backend to your hosting provider +5. Deploy frontend to CDN/hosting + +### What hosting providers are recommended? + +**Backend:** +- Vercel +- Railway +- Heroku +- AWS/GCP/Azure +- DigitalOcean + +**Frontend:** +- Vercel +- Netlify +- Cloudflare Pages +- AWS S3 + CloudFront + +**Database:** +- Supabase +- PlanetScale +- AWS RDS +- Heroku Postgres + +### How do I handle environment variables in production? + +```bash +# Use your hosting provider's environment variable management +# Never commit .env files to git + +# Required variables: +DATABASE_URL=postgresql://... +REDIS_URL=redis://... +ACCESS_TOKEN_SECRET=... +REFRESH_TOKEN_SECRET=... +AI_API_KEY=... +STELLAR_NETWORK=mainnet +``` + +### What about scaling? + +ChenAIKit is designed to scale: +- **Horizontal scaling**: Add more backend instances +- **Caching**: Redis for frequently accessed data +- **Database**: Connection pooling and read replicas +- **CDN**: Serve frontend assets from CDN +- **Load balancing**: Distribute traffic across instances + +--- + +## Development Questions + +### How do I contribute to ChenAIKit? + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for guidelines. + +Quick start: +1. Fork the repository +2. Create a feature branch +3. Make your changes +4. Add tests +5. Submit a pull request + +### How do I report a bug? + +[Create an issue](https://github.com/nexoraorg/chenaikit/issues/new) with: +- Clear description +- Steps to reproduce +- Expected vs actual behavior +- Environment details +- Error messages/logs + +### How do I request a feature? + +[Open a feature request](https://github.com/nexoraorg/chenaikit/issues/new?template=feature_request.md) describing: +- Use case +- Proposed solution +- Alternatives considered +- Additional context + +### Where can I get help? + +- **Documentation**: [docs/](./getting-started.md) +- **Discord**: [Join our server](https://discord.gg/chenaikit) +- **GitHub Discussions**: [Ask questions](https://github.com/nexoraorg/chenaikit/discussions) +- **Email**: support@chenaikit.com + +--- + +## Integration Questions + +### Can I integrate ChenAIKit with my existing app? + +Yes! ChenAIKit is designed to be modular: +- Use only the features you need +- Integrate with existing authentication +- Connect to your database +- Customize the UI components + +### Does ChenAIKit work with React? + +Yes! We provide React components and hooks: +```typescript +import { useCreditScore, useTransactionMonitor } from '@chenaikit/frontend'; + +function MyComponent() { + const { score, loading } = useCreditScore(accountId); + return
Score: {score}
; +} +``` + +### Can I use ChenAIKit with Vue or Angular? + +The core SDK works with any framework. We provide React components, but you can: +- Use the core SDK directly +- Build your own components +- Contribute framework-specific packages + +### How do I integrate with my backend? + +```typescript +// Express.js example +import { StellarConnector, AIService } from '@chenaikit/core'; + +app.get('/api/credit-score/:accountId', async (req, res) => { + const stellar = new StellarConnector({ network: 'mainnet' }); + const ai = new AIService({ apiKey: process.env.AI_API_KEY }); + + const account = await stellar.getAccount(req.params.accountId); + const score = await ai.calculateCreditScore(account); + + res.json({ score }); +}); +``` + +--- + +## Pricing Questions + +### Is there a cost to use ChenAIKit? + +- **Open Source SDK**: Free (MIT License) +- **AI Services**: Tiered pricing based on usage +- **Blockchain Fees**: Stellar network fees (~$0.00001 per transaction) +- **Infrastructure**: Your hosting costs + +### What are the AI service pricing tiers? + +- **Free**: 100 API calls/month +- **Basic**: $29/month - 10,000 calls +- **Pro**: $99/month - 100,000 calls +- **Enterprise**: Custom pricing + +### Can I self-host everything? + +Yes! You can: +- Run your own backend +- Host your own AI models +- Use public Stellar infrastructure +- Deploy contracts yourself + +This eliminates recurring costs but requires more technical expertise. + +--- + +## Security Questions + +### Is ChenAIKit secure? + +We follow security best practices: +- Regular security audits +- Dependency vulnerability scanning +- Secure coding guidelines +- Encryption for sensitive data +- Rate limiting and DDoS protection + +See [security-guidelines.md](./security-guidelines.md) for details. + +### How are API keys stored? + +- Hashed using bcrypt +- Never logged or exposed +- Transmitted over HTTPS only +- Rotatable at any time + +### What about private keys? + +ChenAIKit never stores or transmits private keys. Users maintain control of their keys through: +- Hardware wallets +- Secure key management +- Multi-signature accounts + +### Is my data encrypted? + +- **In transit**: TLS/HTTPS encryption +- **At rest**: Database encryption (optional) +- **Sensitive fields**: Application-level encryption +- **Backups**: Encrypted backups + +--- + +## Performance Questions + +### How fast are credit score calculations? + +- **Average**: 200-500ms +- **With caching**: 10-50ms +- **Batch processing**: 100+ scores/second + +### What's the transaction monitoring latency? + +- **WebSocket streaming**: <100ms from blockchain +- **Processing**: 10-50ms per transaction +- **Alert delivery**: <1 second + +### Can ChenAIKit handle high volume? + +Yes! Designed for scale: +- Batch processing support +- Efficient caching +- Horizontal scaling +- Connection pooling + +Tested with: +- 1000+ transactions/second +- 10,000+ concurrent users +- Millions of records + +--- + +## Troubleshooting Questions + +### Why is my installation failing? + +See [Troubleshooting Guide](./troubleshooting.md#installation-issues) for common solutions. + +### Why can't I connect to Stellar? + +Check: +1. Network configuration (testnet vs mainnet) +2. Horizon URL is correct +3. Account exists and is funded +4. Internet connection is stable + +### Why are my tests failing? + +Common causes: +1. Missing environment variables +2. Database not running +3. Redis not running +4. Outdated dependencies + +Run: `pnpm install && pnpm -r build` + +--- + +## Roadmap Questions + +### What features are planned? + +See our [GitHub Projects](https://github.com/nexoraorg/chenaikit/projects) for the roadmap. + +Upcoming features: +- Multi-chain support (Ethereum, Polygon) +- Advanced ML models +- Mobile SDKs +- GraphQL API +- Real-time dashboards + +### When will feature X be released? + +Check the [roadmap](https://github.com/nexoraorg/chenaikit/projects) for estimated timelines. Dates are subject to change based on priorities and resources. + +### Can I sponsor a feature? + +Yes! Contact us at partnerships@chenaikit.com to discuss: +- Feature sponsorship +- Custom development +- Enterprise support +- Training and consulting + +--- + +## Still Have Questions? + +- šŸ“– [Read the docs](./getting-started.md) +- šŸ’¬ [Join Discord](https://discord.gg/chenaikit) +- šŸ› [Report issues](https://github.com/nexoraorg/chenaikit/issues) +- šŸ“§ [Email us](mailto:support@chenaikit.com) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..9c05ad5 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,914 @@ +# Troubleshooting Guide + +Common issues and solutions for ChenAIKit. + +## Table of Contents + +- [Installation Issues](#installation-issues) +- [Stellar Network Issues](#stellar-network-issues) +- [Smart Contract Issues](#smart-contract-issues) +- [Backend API Issues](#backend-api-issues) +- [Frontend Issues](#frontend-issues) +- [AI Service Issues](#ai-service-issues) +- [Performance Issues](#performance-issues) +- [Security Issues](#security-issues) + +--- + +## Installation Issues + +### pnpm not found + +**Problem:** `pnpm: command not found` + +**Solution:** +```bash +# Install pnpm globally +npm install -g pnpm + +# Or use npx +npx pnpm install + +# Or use corepack (Node.js 16.13+) +corepack enable +corepack prepare pnpm@latest --activate +``` + +### Workspace dependencies not resolving + +**Problem:** `Cannot find module '@chenaikit/core'` + +**Solution:** +```bash +# Clean and reinstall +rm -rf node_modules +rm pnpm-lock.yaml +pnpm install + +# Rebuild packages +pnpm -r build +``` + +### TypeScript compilation errors + +**Problem:** `error TS2307: Cannot find module` + +**Solution:** +```bash +# Ensure TypeScript is installed +pnpm add -D typescript + +# Generate Prisma client (if using backend) +cd backend +pnpm prisma:generate + +# Rebuild all packages +cd .. +pnpm -r build +``` + +### Native module build failures + +**Problem:** `gyp ERR! build error` + +**Solution:** +```bash +# Install build tools (macOS) +xcode-select --install + +# Install build tools (Ubuntu/Debian) +sudo apt-get install build-essential + +# Install build tools (Windows) +npm install --global windows-build-tools + +# Rebuild native modules +pnpm rebuild +``` + +--- + +## Stellar Network Issues + +### Account not found + +**Problem:** `ChenAIKitError: Account not found (ACCOUNT_NOT_FOUND)` + +**Causes:** +1. Account doesn't exist on the network +2. Using wrong network (testnet vs mainnet) +3. Account not yet funded + +**Solutions:** + +```typescript +// 1. Verify network configuration +const stellar = new StellarConnector({ + network: 'testnet', // or 'mainnet' + horizonUrl: 'https://horizon-testnet.stellar.org' +}); + +// 2. Create and fund testnet account +// Visit: https://laboratory.stellar.org/#account-creator?network=test + +// 3. Check if account exists before operations +try { + const account = await stellar.getAccount(accountId); +} catch (error) { + if (error.code === 'ACCOUNT_NOT_FOUND') { + console.log('Account needs to be created and funded'); + } +} +``` + +### Connection timeout + +**Problem:** `ChenAIKitError: Request timeout (TIMEOUT_ERROR)` + +**Solutions:** + +```typescript +// Increase timeout +const stellar = new StellarConnector({ + network: 'testnet', + timeout: 60000 // 60 seconds +}); + +// Check Horizon status +// Visit: https://status.stellar.org/ + +// Use alternative Horizon server +const stellar = new StellarConnector({ + network: 'testnet', + horizonUrl: 'https://horizon-testnet.stellar.org' // or other provider +}); +``` + +### Rate limiting + +**Problem:** `429 Too Many Requests` + +**Solutions:** + +```typescript +// Implement exponential backoff +async function fetchWithRetry(fn, maxRetries = 3) { + for (let i = 0; i < maxRetries; i++) { + try { + return await fn(); + } catch (error) { + if (error.response?.status === 429 && i < maxRetries - 1) { + const delay = Math.pow(2, i) * 1000; + await new Promise(resolve => setTimeout(resolve, delay)); + continue; + } + throw error; + } + } +} + +// Use with stellar operations +const account = await fetchWithRetry(() => + stellar.getAccount(accountId) +); + +// Batch requests +const accounts = await Promise.all( + accountIds.map(id => stellar.getAccount(id)) +); +``` + +### Invalid transaction + +**Problem:** `Transaction failed: tx_bad_seq` + +**Solutions:** + +```typescript +// Fetch latest sequence number +const account = await stellar.getAccount(sourceAccount); +const sequence = account.sequence; + +// Build transaction with correct sequence +const transaction = new TransactionBuilder(account, { + fee: BASE_FEE, + networkPassphrase: Networks.TESTNET +}) + .addOperation(/* ... */) + .setTimeout(30) + .build(); +``` + +--- + +## Smart Contract Issues + +### Contract deployment fails + +**Problem:** `soroban contract deploy` fails + +**Solutions:** + +```bash +# 1. Verify Rust and Soroban CLI versions +rustc --version # Should be 1.70+ +soroban --version # Should be 20.x+ + +# 2. Clean and rebuild +cd contracts/credit-score +cargo clean +cargo build --target wasm32-unknown-unknown --release + +# 3. Check WASM file exists +ls -lh target/wasm32-unknown-unknown/release/*.wasm + +# 4. Verify network configuration +soroban config network ls + +# 5. Check account balance +soroban config identity show deployer + +# 6. Fund account if needed (testnet) +soroban config identity fund deployer --network testnet +``` + +### Contract invocation fails + +**Problem:** `Error: Contract invocation failed` + +**Solutions:** + +```bash +# 1. Verify contract is initialized +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + has_score \ + --account $TEST_ACCOUNT + +# 2. Check authorization +# Ensure you're using the correct identity +soroban config identity address deployer + +# 3. Verify contract ID +echo $CONTRACT_ID + +# 4. Check contract events for errors +soroban events \ + --start-ledger \ + --id $CONTRACT_ID \ + --network testnet +``` + +### WASM optimization issues + +**Problem:** Optimized WASM is too large or fails + +**Solutions:** + +```bash +# 1. Use release profile +cargo build --target wasm32-unknown-unknown --release + +# 2. Check Cargo.toml optimization settings +[profile.release] +opt-level = "z" +lto = true +codegen-units = 1 +strip = "symbols" + +# 3. Use soroban optimize +soroban contract optimize \ + --wasm target/wasm32-unknown-unknown/release/credit_score.wasm + +# 4. Check WASM size +ls -lh target/wasm32-unknown-unknown/release/*.wasm +``` + +--- + +## Backend API Issues + +### Database connection fails + +**Problem:** `Error: Can't reach database server` + +**Solutions:** + +```bash +# 1. Check DATABASE_URL in .env +cat backend/.env | grep DATABASE_URL + +# 2. Verify PostgreSQL is running +# macOS +brew services list | grep postgresql + +# Linux +sudo systemctl status postgresql + +# Docker +docker ps | grep postgres + +# 3. Test connection +psql $DATABASE_URL + +# 4. Run migrations +cd backend +pnpm prisma:migrate + +# 5. Generate Prisma client +pnpm prisma:generate +``` + +### Redis connection fails + +**Problem:** `Error: Redis connection refused` + +**Solutions:** + +```bash +# 1. Check REDIS_URL in .env +cat backend/.env | grep REDIS_URL + +# 2. Verify Redis is running +# macOS +brew services list | grep redis + +# Linux +sudo systemctl status redis + +# Docker +docker ps | grep redis + +# 3. Test connection +redis-cli ping +# Should return: PONG + +# 4. Start Redis if not running +# macOS +brew services start redis + +# Linux +sudo systemctl start redis + +# Docker +docker run -d -p 6379:6379 redis:alpine +``` + +### JWT authentication fails + +**Problem:** `401 Unauthorized` or `Invalid token` + +**Solutions:** + +```bash +# 1. Verify secrets are set +cat backend/.env | grep TOKEN_SECRET + +# 2. Generate new secrets if needed +node -e "console.log(require('crypto').randomBytes(64).toString('hex'))" + +# 3. Update .env +ACCESS_TOKEN_SECRET= +REFRESH_TOKEN_SECRET= + +# 4. Restart backend +cd backend +pnpm dev +``` + +### API rate limiting + +**Problem:** `429 Too Many Requests` + +**Solutions:** + +```typescript +// 1. Check rate limit headers +const response = await fetch('/api/endpoint'); +console.log('Rate Limit:', response.headers.get('X-RateLimit-Limit')); +console.log('Remaining:', response.headers.get('X-RateLimit-Remaining')); +console.log('Reset:', response.headers.get('X-RateLimit-Reset')); + +// 2. Implement retry with backoff +async function apiCallWithRetry(url, options, maxRetries = 3) { + for (let i = 0; i < maxRetries; i++) { + const response = await fetch(url, options); + + if (response.status === 429) { + const resetTime = response.headers.get('X-RateLimit-Reset'); + const waitTime = resetTime ? + new Date(resetTime).getTime() - Date.now() : + Math.pow(2, i) * 1000; + + await new Promise(resolve => setTimeout(resolve, waitTime)); + continue; + } + + return response; + } + throw new Error('Max retries exceeded'); +} + +// 3. Use API key with higher tier +const response = await fetch('/api/endpoint', { + headers: { + 'X-API-Key': process.env.API_KEY + } +}); +``` + +### CORS errors + +**Problem:** `Access-Control-Allow-Origin` error + +**Solutions:** + +```bash +# 1. Check CORS configuration in backend/.env +CORS_ORIGINS=http://localhost:3000,http://localhost:3001 + +# 2. For development only, allow all origins +CORS_ALLOW_ALL=true + +# 3. Verify backend is running +curl -I http://localhost:5000/api/health + +# 4. Check browser console for exact error +# Open DevTools > Console + +# 5. Use proxy in development (frontend) +# In frontend/package.json: +{ + "proxy": "http://localhost:5000" +} +``` + +--- + +## Frontend Issues + +### React app won't start + +**Problem:** `Error: Cannot find module` or compilation errors + +**Solutions:** + +```bash +# 1. Clean and reinstall +cd frontend +rm -rf node_modules +rm package-lock.json +pnpm install + +# 2. Clear React cache +rm -rf node_modules/.cache + +# 3. Check Node version +node --version # Should be 18+ + +# 4. Verify environment variables +cat .env | grep REACT_APP_ + +# 5. Start with verbose logging +pnpm start --verbose +``` + +### API calls fail from frontend + +**Problem:** `Network Error` or `Failed to fetch` + +**Solutions:** + +```typescript +// 1. Check API URL configuration +console.log('API URL:', process.env.REACT_APP_API_URL); + +// 2. Verify backend is running +fetch('http://localhost:5000/api/health') + .then(r => r.json()) + .then(console.log); + +// 3. Check for CORS issues (see CORS section above) + +// 4. Use absolute URLs in development +const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000'; + +// 5. Add error handling +async function apiCall(endpoint) { + try { + const response = await fetch(`${API_URL}${endpoint}`); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + return await response.json(); + } catch (error) { + console.error('API call failed:', error); + throw error; + } +} +``` + +### Build fails + +**Problem:** `Build failed` or `Out of memory` + +**Solutions:** + +```bash +# 1. Increase Node memory +export NODE_OPTIONS="--max-old-space-size=4096" +pnpm build + +# 2. Clear cache +rm -rf node_modules/.cache +rm -rf build + +# 3. Check for TypeScript errors +pnpm type-check + +# 4. Build with verbose output +pnpm build --verbose + +# 5. Check disk space +df -h +``` + +--- + +## AI Service Issues + +### API key invalid + +**Problem:** `401 Unauthorized` or `Invalid API key` + +**Solutions:** + +```bash +# 1. Verify API key is set +echo $AI_API_KEY + +# 2. Check .env file +cat .env | grep AI_API_KEY + +# 3. Regenerate API key from dashboard +# Visit: https://dashboard.chenaikit.com/api-keys + +# 4. Test API key +curl -H "Authorization: Bearer $AI_API_KEY" \ + https://api.chenaikit.com/v1/health +``` + +### Credit score calculation fails + +**Problem:** `Error calculating credit score` + +**Solutions:** + +```typescript +// 1. Verify account data is complete +const account = await stellar.getAccount(accountId); +console.log('Account data:', JSON.stringify(account, null, 2)); + +// 2. Check for required fields +if (!account.balances || account.balances.length === 0) { + console.error('Account has no balances'); +} + +// 3. Add error handling +try { + const score = await ai.calculateCreditScore(account); + console.log('Score:', score); +} catch (error) { + console.error('Score calculation failed:', error.message); + console.error('Details:', error.details); +} + +// 4. Use demo mode for testing +const ai = new AIService({ + apiKey: 'demo', // Uses mock data + baseUrl: 'https://api.chenaikit.com' +}); +``` + +### Fraud detection timeout + +**Problem:** `Request timeout` during fraud detection + +**Solutions:** + +```typescript +// 1. Increase timeout +const ai = new AIService({ + apiKey: process.env.AI_API_KEY, + timeout: 120000 // 2 minutes +}); + +// 2. Reduce data size +const recentTransactions = transactions.slice(0, 50); // Limit to 50 +const result = await detector.analyzePattern(recentTransactions); + +// 3. Use batch processing +const batchSize = 20; +for (let i = 0; i < transactions.length; i += batchSize) { + const batch = transactions.slice(i, i + batchSize); + const result = await detector.analyzePattern(batch); + console.log(`Batch ${i / batchSize + 1} result:`, result); +} +``` + +--- + +## Performance Issues + +### Slow API responses + +**Problem:** API calls take too long + +**Solutions:** + +```typescript +// 1. Enable caching +import { CacheService } from '@chenaikit/backend'; + +const cache = new CacheService({ + ttl: 300, // 5 minutes + maxSize: 1000 +}); + +// Cache expensive operations +async function getCachedScore(accountId) { + const cacheKey = `score:${accountId}`; + const cached = await cache.get(cacheKey); + + if (cached) { + return cached; + } + + const score = await ai.calculateCreditScore(accountId); + await cache.set(cacheKey, score); + return score; +} + +// 2. Use pagination +const transactions = await stellar.getAccountTransactions(accountId, { + limit: 20, // Smaller page size + cursor: lastCursor +}); + +// 3. Implement request batching +const accountIds = ['GABC...', 'GDEF...', 'GHIJ...']; +const scores = await Promise.all( + accountIds.map(id => getCachedScore(id)) +); + +// 4. Add request timeout +const controller = new AbortController(); +setTimeout(() => controller.abort(), 10000); // 10s timeout + +const response = await fetch(url, { + signal: controller.signal +}); +``` + +### High memory usage + +**Problem:** Application uses too much memory + +**Solutions:** + +```typescript +// 1. Limit data retention +const monitor = new TransactionMonitor({ + // ... config + maxHistorySize: 1000 // Limit stored transactions +}); + +// 2. Use streaming for large datasets +import { Readable } from 'stream'; + +async function* streamTransactions(accountId) { + let cursor = null; + while (true) { + const page = await stellar.getAccountTransactions(accountId, { + limit: 100, + cursor + }); + + for (const tx of page) { + yield tx; + } + + if (page.length < 100) break; + cursor = page[page.length - 1].paging_token; + } +} + +// 3. Clear caches periodically +setInterval(() => { + cache.clear(); +}, 3600000); // Every hour + +// 4. Monitor memory usage +console.log('Memory usage:', process.memoryUsage()); +``` + +### Database query slow + +**Problem:** Database queries are slow + +**Solutions:** + +```sql +-- 1. Add indexes +CREATE INDEX idx_accounts_user_id ON accounts(user_id); +CREATE INDEX idx_transactions_account_id ON transactions(account_id); +CREATE INDEX idx_transactions_created_at ON transactions(created_at); + +-- 2. Analyze query performance +EXPLAIN ANALYZE SELECT * FROM accounts WHERE user_id = '...'; + +-- 3. Use connection pooling +-- In backend/.env: +DATABASE_URL="postgresql://user:pass@localhost:5432/db?connection_limit=10" +``` + +```typescript +// 4. Optimize Prisma queries +// Bad: N+1 query +const users = await prisma.user.findMany(); +for (const user of users) { + const accounts = await prisma.account.findMany({ + where: { userId: user.id } + }); +} + +// Good: Single query with include +const users = await prisma.user.findMany({ + include: { + accounts: true + } +}); + +// 5. Use select to limit fields +const accounts = await prisma.account.findMany({ + select: { + id: true, + balance: true, + // Only fields you need + } +}); +``` + +--- + +## Security Issues + +### Exposed secrets + +**Problem:** Secrets committed to git + +**Solutions:** + +```bash +# 1. Remove from git history +git filter-branch --force --index-filter \ + "git rm --cached --ignore-unmatch .env" \ + --prune-empty --tag-name-filter cat -- --all + +# 2. Rotate all exposed secrets immediately +# - Generate new API keys +# - Change database passwords +# - Regenerate JWT secrets + +# 3. Add .env to .gitignore +echo ".env" >> .gitignore +echo ".env.local" >> .gitignore + +# 4. Use environment-specific files +.env.example # Template (commit this) +.env.development # Local dev (don't commit) +.env.production # Production (don't commit) + +# 5. Use secret management +# - HashiCorp Vault +# - AWS Secrets Manager +# - Environment variables in CI/CD +``` + +### SQL injection vulnerability + +**Problem:** Potential SQL injection + +**Solutions:** + +```typescript +// Bad: String concatenation +const result = await prisma.$queryRawUnsafe( + `SELECT * FROM users WHERE email = '${email}'` +); + +// Good: Parameterized query +const result = await prisma.$queryRaw` + SELECT * FROM users WHERE email = ${email} +`; + +// Better: Use Prisma methods +const user = await prisma.user.findUnique({ + where: { email } +}); + +// Validate input +import { z } from 'zod'; + +const emailSchema = z.string().email(); +const validatedEmail = emailSchema.parse(email); +``` + +### XSS vulnerability + +**Problem:** Cross-site scripting risk + +**Solutions:** + +```typescript +// 1. Sanitize user input +import DOMPurify from 'dompurify'; + +const clean = DOMPurify.sanitize(userInput); + +// 2. Use React's built-in escaping +// Good: React escapes by default +
{userInput}
+ +// Dangerous: Bypasses escaping +
+ +// 3. Set Content Security Policy +// In backend/src/middleware/security.ts +app.use(helmet({ + contentSecurityPolicy: { + directives: { + defaultSrc: ["'self'"], + scriptSrc: ["'self'"], + styleSrc: ["'self'", "'unsafe-inline'"], + imgSrc: ["'self'", "data:", "https:"], + } + } +})); +``` + +--- + +## Getting Help + +If you can't find a solution here: + +1. **Check Documentation** + - [Getting Started](./getting-started.md) + - [API Reference](./api/core-sdk.md) + - [Tutorials](./tutorials/) + +2. **Search Issues** + - [GitHub Issues](https://github.com/nexoraorg/chenaikit/issues) + - Search for similar problems + +3. **Ask Community** + - [Discord Server](https://discord.gg/chenaikit) + - [GitHub Discussions](https://github.com/nexoraorg/chenaikit/discussions) + +4. **Report Bug** + - [Create Issue](https://github.com/nexoraorg/chenaikit/issues/new) + - Include error messages, logs, and reproduction steps + +5. **Contact Support** + - Email: support@chenaikit.com + - Include your environment details and error logs + +## Diagnostic Information + +When reporting issues, include: + +```bash +# System information +node --version +pnpm --version +rustc --version # If using contracts +soroban --version # If using contracts + +# Package versions +cat package.json | grep version + +# Environment +echo $NODE_ENV +echo $STELLAR_NETWORK + +# Logs +# Backend logs +tail -n 100 backend/logs/error.log + +# Frontend console errors +# Open DevTools > Console > Copy all errors +``` diff --git a/docs/tutorials/deploying-contracts.md b/docs/tutorials/deploying-contracts.md new file mode 100644 index 0000000..106c5c6 --- /dev/null +++ b/docs/tutorials/deploying-contracts.md @@ -0,0 +1,403 @@ +# Deploying Smart Contracts to Stellar + +This comprehensive guide walks you through deploying Soroban smart contracts to the Stellar network. You'll learn how to build, test, optimize, and deploy the ChenAIKit credit scoring contract. + +## Prerequisites + +- Rust 1.70+ installed +- Soroban CLI installed +- Stellar account with XLM for deployment +- Basic understanding of smart contracts +- 30-45 minutes + +## Step 1: Install Required Tools + +### Install Rust + +```bash +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +source $HOME/.cargo/env +``` + +### Install Soroban CLI + +```bash +cargo install --locked soroban-cli +``` + +### Add WebAssembly Target + +```bash +rustup target add wasm32-unknown-unknown +``` + +### Verify Installation + +```bash +soroban --version +# Should output: soroban 20.x.x +``` + +## Step 2: Set Up Your Environment + +### Configure Stellar Network + +```bash +# Configure testnet +soroban config network add \ + --global testnet \ + --rpc-url https://soroban-testnet.stellar.org:443 \ + --network-passphrase "Test SDF Network ; September 2015" + +# Configure mainnet (for production) +soroban config network add \ + --global mainnet \ + --rpc-url https://soroban-mainnet.stellar.org:443 \ + --network-passphrase "Public Global Stellar Network ; September 2015" +``` + +### Create or Import Identity + +```bash +# Generate new identity +soroban config identity generate deployer + +# Or import existing secret key +soroban config identity add deployer --secret-key SXXX... + +# View your public key +soroban config identity address deployer +``` + +### Fund Your Account (Testnet Only) + +```bash +# Get testnet XLM +soroban config identity fund deployer --network testnet + +# Verify balance +soroban config identity show deployer +``` + +## Step 3: Build the Contract + +Navigate to the credit score contract directory: + +```bash +cd contracts/credit-score +``` + +### Build for Development + +```bash +cargo build --target wasm32-unknown-unknown --release +``` + +The compiled WASM file will be at: +``` +target/wasm32-unknown-unknown/release/credit_score.wasm +``` + +### Optimize the Contract + +For production, optimize the WASM to reduce size and gas costs: + +```bash +# Using the provided script +./scripts/optimize.sh + +# Or manually with soroban-cli +soroban contract optimize \ + --wasm target/wasm32-unknown-unknown/release/credit_score.wasm \ + --wasm-out target/wasm32-unknown-unknown/release/credit_score_optimized.wasm +``` + +Optimization typically reduces contract size by 50-70%. + +## Step 4: Test the Contract Locally + +Before deploying, run comprehensive tests: + +```bash +# Run unit tests +cargo test + +# Run with output +cargo test -- --nocapture + +# Run specific test +cargo test test_calculate_score +``` + +### Test Contract Functions + +```bash +# Build and test +./scripts/test.sh +``` + +Expected output: +``` +running 8 tests +test test::test_calculate_and_get_score ... ok +test test::test_has_score ... ok +test test::test_authorization_required ... ok +test test::test_adjust_score_with_oracle ... ok +test test::test_calculate_score_multiple_times ... ok +test test::test_edge_case_zero_score ... ok +test test::test_get_score_returns_zero_for_new_user ... ok +test test::test_upgrade ... ok + +test result: ok. 8 passed; 0 failed +``` + +## Step 5: Deploy to Testnet + +### Deploy the Contract + +```bash +# Deploy using soroban-cli +soroban contract deploy \ + --wasm target/wasm32-unknown-unknown/release/credit_score.wasm \ + --source deployer \ + --network testnet + +# Or use the deployment script +./scripts/deploy.sh testnet +``` + +Save the contract ID from the output: +``` +Contract deployed successfully! +Contract ID: CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM +``` + +### Store Contract ID + +```bash +# Save for future use +export CONTRACT_ID=CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM + +# Or add to .env file +echo "CONTRACT_ID=$CONTRACT_ID" >> .env +``` + +## Step 6: Initialize the Contract + +After deployment, initialize the contract with an admin address: + +```bash +# Get your admin address +ADMIN_ADDRESS=$(soroban config identity address deployer) + +# Initialize contract +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + initialize \ + --admin $ADMIN_ADDRESS + +# Or use the initialization script +./scripts/initialize.sh testnet $CONTRACT_ID +``` + +## Step 7: Interact with the Contract + +### Calculate a Credit Score + +```bash +# Calculate score for an account +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + calculate_score \ + --account GABC... + +# Expected output: 750 +``` + +### Get Stored Score + +```bash +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + get_score \ + --account GABC... +``` + +### Check if Account Has Score + +```bash +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + has_score \ + --account GABC... + +# Returns: true or false +``` + +### Update Score Factors + +```bash +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + update_factors \ + --account GABC... \ + --factors_str "age:30,transactions:50,balance:high" +``` + +## Step 8: Deploy to Mainnet + +Once thoroughly tested on testnet, deploy to mainnet: + +### Fund Mainnet Account + +Ensure your deployer account has sufficient XLM: +- Minimum: 1 XLM for account creation +- Recommended: 10-20 XLM for deployment and operations + +### Deploy to Mainnet + +```bash +# Deploy +soroban contract deploy \ + --wasm target/wasm32-unknown-unknown/release/credit_score_optimized.wasm \ + --source deployer \ + --network mainnet + +# Initialize +MAINNET_CONTRACT_ID= +ADMIN_ADDRESS=$(soroban config identity address deployer) + +soroban contract invoke \ + --id $MAINNET_CONTRACT_ID \ + --source deployer \ + --network mainnet \ + -- \ + initialize \ + --admin $ADMIN_ADDRESS +``` + +### Verify Deployment + +```bash +# Test a simple read operation +soroban contract invoke \ + --id $MAINNET_CONTRACT_ID \ + --source deployer \ + --network mainnet \ + -- \ + has_score \ + --account $ADMIN_ADDRESS +``` + +## Step 9: Monitor and Maintain + +### View Contract Events + +```bash +# Get recent events +soroban events \ + --start-ledger \ + --id $CONTRACT_ID \ + --network testnet +``` + +### Upgrade Contract (If Needed) + +```bash +# Build new version +cargo build --target wasm32-unknown-unknown --release + +# Get new WASM hash +NEW_WASM_HASH=$(soroban contract install \ + --wasm target/wasm32-unknown-unknown/release/credit_score.wasm \ + --source deployer \ + --network testnet) + +# Upgrade contract +soroban contract invoke \ + --id $CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + upgrade \ + --admin $ADMIN_ADDRESS \ + --new_wasm_hash $NEW_WASM_HASH +``` + +## Best Practices + +### Security + +1. **Never commit secret keys** - Use environment variables or secure vaults +2. **Test thoroughly** - Run all tests before mainnet deployment +3. **Use optimized WASM** - Reduces costs and improves performance +4. **Implement access control** - Use admin-only functions for sensitive operations +5. **Audit contracts** - Have contracts reviewed before mainnet deployment + +### Cost Optimization + +1. **Optimize WASM size** - Smaller contracts cost less to deploy +2. **Minimize storage** - Use temporary storage when possible +3. **Batch operations** - Combine multiple operations to save on fees +4. **Use efficient data structures** - Choose appropriate storage patterns + +### Monitoring + +1. **Track contract events** - Monitor for unexpected behavior +2. **Set up alerts** - Get notified of critical events +3. **Monitor gas usage** - Optimize expensive operations +4. **Keep backups** - Store contract source and deployment info + +## Troubleshooting + +### "Insufficient balance" +- Fund your account with more XLM +- Check network fees and ensure adequate balance + +### "Contract already exists" +- Use a different identity or deploy to a different network +- Or upgrade the existing contract + +### "Authorization failed" +- Ensure you're using the correct admin address +- Verify the identity has proper permissions + +### "WASM validation failed" +- Rebuild the contract with correct target +- Ensure Rust and Soroban CLI are up to date +- Check for compilation errors + +## Next Steps + +- [Contract Architecture](../architecture/contracts.md) - Understand contract design +- [API Integration](./api-integration.md) - Connect contracts to your backend +- [Testing Guide](./testing-contracts.md) - Comprehensive testing strategies +- [Security Audit](../../contracts/audit-report.md) - Review security findings + +## Resources + +- [Soroban Documentation](https://soroban.stellar.org/docs) +- [Stellar Laboratory](https://laboratory.stellar.org/) +- [Soroban Examples](https://github.com/stellar/soroban-examples) +- [ChenAIKit Discord](https://discord.gg/chenaikit) + +## Get Help + +- šŸ› [Report Issues](https://github.com/nexoraorg/chenaikit/issues) +- šŸ’¬ [Join Discord](https://discord.gg/chenaikit) +- šŸ“§ [Email Support](mailto:support@chenaikit.com) diff --git a/docs/tutorials/first-credit-score.md b/docs/tutorials/first-credit-score.md new file mode 100644 index 0000000..913c986 --- /dev/null +++ b/docs/tutorials/first-credit-score.md @@ -0,0 +1,181 @@ +# Your First Credit Score Calculation + +This tutorial will guide you through calculating your first credit score using ChenAIKit. You'll learn how to connect to the Stellar network, fetch account data, and use AI services to calculate a credit score. + +## Prerequisites + +- Node.js 18+ installed +- Basic knowledge of TypeScript/JavaScript +- A Stellar testnet account (we'll show you how to create one) +- 15 minutes of your time + +## Step 1: Install ChenAIKit + +First, create a new project and install the core package: + +```bash +mkdir my-credit-app +cd my-credit-app +npm init -y +npm install @chenaikit/core dotenv +npm install -D typescript @types/node ts-node +``` + +Initialize TypeScript: + +```bash +npx tsc --init +``` + +## Step 2: Set Up Environment Variables + +Create a `.env` file in your project root: + +```env +# Stellar Network Configuration +STELLAR_NETWORK=testnet +HORIZON_URL=https://horizon-testnet.stellar.org + +# AI Service Configuration (optional for this tutorial) +AI_API_KEY=your_api_key_here +``` + +## Step 3: Create Your First Script + +Create a file named `calculate-score.ts`: + +```typescript +import { StellarConnector, AIService } from '@chenaikit/core'; +import dotenv from 'dotenv'; + +dotenv.config(); + +async function main() { + // Step 1: Initialize Stellar connector + console.log('šŸ”— Connecting to Stellar testnet...'); + const stellar = new StellarConnector({ + network: 'testnet', + horizonUrl: process.env.HORIZON_URL + }); + + // Step 2: Get account data + // Replace with your Stellar testnet account ID + const accountId = 'GABC...'; // Your testnet account + + console.log(`šŸ“Š Fetching account data for ${accountId}...`); + const account = await stellar.getAccount(accountId); + + console.log('Account balances:'); + account.balances.forEach(balance => { + console.log(` - ${balance.asset_type}: ${balance.balance}`); + }); + + // Step 3: Initialize AI service + console.log('\n🧠 Initializing AI service...'); + const ai = new AIService({ + apiKey: process.env.AI_API_KEY || 'demo' + }); + + // Step 4: Calculate credit score + console.log('šŸŽÆ Calculating credit score...'); + const score = await ai.calculateCreditScore(account); + + console.log(`\nāœ… Credit Score: ${score}/1000`); + + // Step 5: Get score factors + const factors = await ai.getScoreFactors(account); + console.log('\nšŸ“ˆ Score Factors:'); + factors.forEach(factor => { + console.log(` - ${factor}`); + }); +} + +main().catch(console.error); +``` + +## Step 4: Create a Testnet Account (If You Don't Have One) + +If you don't have a Stellar testnet account, create one using Stellar Laboratory: + +1. Visit [Stellar Laboratory](https://laboratory.stellar.org/#account-creator?network=test) +2. Click "Generate keypair" +3. Save your public and secret keys securely +4. Click "Get test network lumens" to fund your account + +Alternatively, use the ChenAIKit CLI: + +```bash +npx @chenaikit/cli account create --network testnet +``` + +## Step 5: Run Your Script + +```bash +npx ts-node calculate-score.ts +``` + +Expected output: + +``` +šŸ”— Connecting to Stellar testnet... +šŸ“Š Fetching account data for GABC... +Account balances: + - native: 10000.0000000 + +🧠 Initializing AI service... +šŸŽÆ Calculating credit score... + +āœ… Credit Score: 750/1000 + +šŸ“ˆ Score Factors: + - Account age: 30 days + - Transaction history: 15 transactions + - Balance stability: High + - Network activity: Moderate +``` + +## Understanding the Results + +The credit score is calculated based on several factors: + +- **Account Age**: Older accounts generally have higher scores +- **Transaction History**: More transactions indicate active usage +- **Balance Stability**: Consistent balances show financial stability +- **Network Activity**: Participation in the Stellar ecosystem + +## Next Steps + +Now that you've calculated your first credit score, try these: + +1. **Monitor Multiple Accounts**: Loop through multiple account IDs +2. **Track Score Changes**: Store scores in a database and track over time +3. **Add Fraud Detection**: Use `ai.detectFraud()` to check transactions +4. **Build a Dashboard**: Create a web interface to display scores + +## Common Issues + +### "Account not found" +- Ensure your account is funded on testnet +- Verify you're using the correct network (testnet vs mainnet) + +### "Invalid API key" +- Check your `.env` file has the correct `AI_API_KEY` +- For testing, you can use 'demo' as the API key + +### "Connection timeout" +- Check your internet connection +- Verify the Horizon URL is correct +- Try using the default testnet URL + +## Learn More + +- [API Reference](../api-reference.md) - Complete API documentation +- [Deploying Contracts Tutorial](./deploying-contracts.md) - Deploy smart contracts +- [Architecture Overview](../architecture/overview.md) - System architecture +- [Examples](../../examples/) - More complete examples + +## Get Help + +- šŸ› [Report Issues](https://github.com/nexoraorg/chenaikit/issues) +- šŸ’¬ [Join Discord](https://discord.gg/chenaikit) +- šŸ“§ [Email Support](mailto:support@chenaikit.com) diff --git a/website/.gitignore b/website/.gitignore new file mode 100644 index 0000000..b2d6de3 --- /dev/null +++ b/website/.gitignore @@ -0,0 +1,20 @@ +# Dependencies +/node_modules + +# Production +/build + +# Generated files +.docusaurus +.cache-loader + +# Misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/website/README.md b/website/README.md new file mode 100644 index 0000000..8c9ea52 --- /dev/null +++ b/website/README.md @@ -0,0 +1,111 @@ +# ChenAIKit Documentation Website + +This website is built using [Docusaurus 3](https://docusaurus.io/), a modern static website generator. + +## Installation + +```bash +pnpm install +``` + +## Local Development + +```bash +pnpm start +``` + +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. + +## Build + +```bash +pnpm build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +## Deployment + +### Using SSH + +```bash +USE_SSH=true pnpm deploy +``` + +### Not using SSH + +```bash +GIT_USER= pnpm deploy +``` + +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. + +## Search + +The documentation uses Algolia DocSearch for search functionality. To set up search: + +1. Apply for DocSearch at https://docsearch.algolia.com/apply/ +2. Once approved, update the Algolia configuration in `docusaurus.config.ts` +3. Replace `YOUR_APP_ID` and `YOUR_SEARCH_API_KEY` with your credentials + +## Customization + +### Theme + +Edit `src/css/custom.css` to customize colors and styles. + +### Logo + +Replace `static/img/logo.svg` with your logo. + +### Favicon + +Replace `static/img/favicon.ico` with your favicon. + +## Documentation Structure + +``` +docs/ +ā”œā”€ā”€ getting-started.md +ā”œā”€ā”€ tutorials/ +│ ā”œā”€ā”€ first-credit-score.md +│ └── deploying-contracts.md +ā”œā”€ā”€ api/ +│ └── core-sdk.md +ā”œā”€ā”€ architecture/ +│ ā”œā”€ā”€ overview.md +│ └── adrs/ +ā”œā”€ā”€ troubleshooting.md +└── faq.md +``` + +## Adding New Documentation + +1. Create a new `.md` file in the appropriate directory under `docs/` +2. Add frontmatter at the top: + ```md + --- + id: my-doc + title: My Document + sidebar_label: My Doc + --- + ``` +3. Update `sidebars.ts` to include the new document +4. The document will automatically appear in the sidebar + +## Markdown Features + +Docusaurus supports many Markdown features: + +- Code blocks with syntax highlighting +- Tabs +- Admonitions (notes, warnings, tips) +- MDX (JSX in Markdown) +- Mermaid diagrams +- Math equations (with plugin) + +See [Docusaurus Markdown Features](https://docusaurus.io/docs/markdown-features) for more details. + +## Contributing + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for guidelines on contributing to the documentation. diff --git a/website/docs/api-reference.md b/website/docs/api-reference.md new file mode 100644 index 0000000..5e8185d --- /dev/null +++ b/website/docs/api-reference.md @@ -0,0 +1,198 @@ +# API Reference + +Complete API reference for ChenAIKit packages. + +## @chenaikit/core + +### StellarConnector + +Main class for interacting with Stellar network. + +#### Constructor + +```typescript +new StellarConnector(config: StellarConfig) +``` + +**Parameters:** +- `config.network` - Network to connect to (`'testnet'` | `'mainnet'`) +- `config.horizonUrl` - Optional custom Horizon URL + +#### Methods + +##### getAccount(accountId: string) + +Fetches account information from Stellar network. + +**Parameters:** +- `accountId` - Stellar account ID + +**Returns:** Promise + +##### getAccountBalances(accountId: string) + +Fetches account balances. + +**Parameters:** +- `accountId` - Stellar account ID + +**Returns:** Promise + +##### getAccountTransactions(accountId: string, limit?: number) + +Fetches account transaction history. + +**Parameters:** +- `accountId` - Stellar account ID +- `limit` - Maximum number of transactions (default: 10) + +**Returns:** Promise + +### AIService + +Main class for AI operations. + +#### Constructor + +```typescript +new AIService(config: AIConfig) +``` + +**Parameters:** +- `config.apiKey` - AI service API key +- `config.baseUrl` - Optional custom base URL + +#### Methods + +##### calculateCreditScore(accountData: any) + +Calculates credit score for account data. + +**Parameters:** +- `accountData` - Account information object + +**Returns:** Promise + +##### detectFraud(transactionData: any) + +Detects fraud in transaction data. + +**Parameters:** +- `transactionData` - Transaction information object + +**Returns:** Promise + +### CreditScorer + +Specialized class for credit scoring operations. + +#### Methods + +##### calculateScore(accountData: any) + +Calculates credit score using advanced algorithms. + +**Returns:** Promise + +##### getScoreFactors(accountData: any) + +Returns factors that influenced the credit score. + +**Returns:** Promise + +### FraudDetector + +Specialized class for fraud detection operations. + +#### Methods + +##### detectAnomalies(transactionData: any) + +Detects anomalies in transaction data. + +**Returns:** Promise + +##### getRiskFactors(transactionData: any) + +Returns risk factors identified in the transaction. + +**Returns:** Promise + +## @chenaikit/cli + +Command-line interface for ChenAIKit operations. + +### Commands + +#### Account Operations + +```bash +chenaikit account balance +chenaikit account transactions +``` + +#### AI Operations + +```bash +chenaikit ai credit-score +chenaikit ai fraud-detect --transaction-id +``` + +#### Contract Operations + +```bash +chenaikit contract generate