flocoin-wallet-sdk
v0.2.1
Published
JavaScript/TypeScript SDK for FLOcoin Wallet System with JWT authentication for EventFlo internal development
Maintainers
Readme
FLOcoin Wallet SDK
A comprehensive TypeScript/JavaScript SDK for integrating with the FLOcoin Wallet system. This SDK provides complete wallet management, FLOcoin token operations, NFT management, and EventFlo platform integration.
🚀 Quick Start
Installation
npm install flocoin-wallet-sdkBasic Usage
import { FLOWalletSDK } from 'flocoin-wallet-sdk';
// Initialize SDK (no API key needed for internal EventFlo development)
const wallet = new FLOWalletSDK({
environment: 'production', // 'development', 'staging', or 'production'
});
// Authenticate user
const otpResult = await wallet.sendOTP('+1234567890');
const authResult = await wallet.verifyOTP('+1234567890', '123456', otpResult.sessionId);
// Create wallet
const newWallet = await wallet.createWallet({
derivationPath: "m/44'/60'/0'/0/0"
});
// Transfer FLOcoin
const transaction = await wallet.transfer({
walletId: newWallet.id,
toAddress: '0x742d35cc9027ebf7cf6c1b9a71478e7f685b5ac7',
amount: '10.5',
tokenType: 'flocoin',
});🌐 API Endpoints
The SDK connects to different environments based on configuration:
Development
- Base URL:
https://9u084f8bw5.execute-api.ap-southeast-2.amazonaws.com/dev - Region: ap-southeast-2 (Sydney)
- Use for: Local development and testing
Staging
- Base URL:
https://1vm4ohqzp9.execute-api.ap-southeast-2.amazonaws.com/dev - Region: ap-southeast-2 (Sydney)
- Use for: Pre-production testing
Production
- Base URL:
https://z5pk43lrk9.execute-api.ap-southeast-2.amazonaws.com/prod - Region: ap-southeast-2 (Sydney)
- Use for: Live applications
📖 Table of Contents
- Features
- Configuration
- Authentication
- Wallet Management
- Transactions
- NFT Management
- Blockchain Operations
- Event System
- Error Handling
- TypeScript Support
- Testing
- Examples
- API Reference
✨ Features
Core Functionality
- 🔐 Phone-based Authentication - SMS OTP verification with JWT tokens
- 💼 HD Wallet Management - BIP-44 derivation with AWS KMS encryption
- 💰 FLOcoin Operations - Transfer, balance checking, transaction history
- 🎫 NFT Management - EventFlo ticket NFTs with metadata support
- ⛓️ Blockchain Integration - BASE network with gas optimization
- 📱 Mobile-First Design - Optimized for mobile applications
Developer Experience
- 🎯 TypeScript First - Complete type definitions and IntelliSense
- 🔄 Event-Driven - Real-time updates with custom event handlers
- 🛡️ Error Handling - Comprehensive error types and recovery
- 🧪 Well Tested - 90%+ test coverage with integration tests
- 📚 Great Documentation - Detailed guides and examples
⚙️ Configuration
SDK Configuration Options
interface SDKConfig {
baseURL?: string; // Custom API endpoint
environment?: 'development' | 'staging' | 'production';
timeout?: number; // Request timeout (default: 30000ms)
retries?: number; // Retry attempts (default: 3)
}Environment Setup
const wallet = new FLOWalletSDK({
environment: process.env.NODE_ENV === 'production' ? 'production' : 'development',
timeout: 30000,
});🔐 Authentication
The SDK uses phone-based authentication with SMS OTP verification.
Send OTP
const otpResult = await wallet.sendOTP('+1234567890');
console.log('Session ID:', otpResult.sessionId);Verify OTP
const authResult = await wallet.verifyOTP(
'+1234567890',
'123456', // OTP from SMS
otpResult.sessionId
);
console.log('User:', authResult.user);
console.log('Access Token:', authResult.token);Token Management
// Check authentication status
if (wallet.isAuthenticated()) {
console.log('User is authenticated');
}
// Manual token management
wallet.setAccessToken('your-access-token');
wallet.setRefreshToken('your-refresh-token');
// Automatic token refresh is handled by the SDKLogout
await wallet.logout();
console.log('User logged out');💼 Wallet Management
Create Wallet
// Basic wallet creation
const wallet = await sdk.createWallet({
phoneNumber: '+1234567890',
});
// With EventFlo user ID
const wallet = await sdk.createWallet({
phoneNumber: '+1234567890',
userId: 'eventflo-user-123',
});Import Wallet
const importedWallet = await sdk.importWallet({
phoneNumber: '+1234567890',
mnemonic: 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',
derivationIndex: 0, // Optional, defaults to 0
});Get Wallet Information
const walletInfo = await sdk.getWallet('wallet-id');
console.log('Address:', walletInfo.address);HD Wallet Address Derivation
// Derive additional addresses from the same wallet
const derivedAddress = await sdk.deriveAddress('wallet-id', 1);
console.log('New Address:', derivedAddress.address);
console.log('Derivation Path:', derivedAddress.path);Balance Checking
// Get wallet balance
const balance = await sdk.getBalance('wallet-id');
console.log('FLOcoin:', balance.flocoin);
console.log('ETH:', balance.eth);
console.log('USD Value:', balance.usd);
// Get balance for any address (no authentication required)
const addressBalance = await sdk.getAddressBalance('0x742d35cc9027ebf7cf6c1b9a71478e7f685b5ac7');💸 Transactions
Transfer Tokens
// FLOcoin transfer
const transaction = await sdk.transfer({
walletId: 'wallet-id',
toAddress: '0x742d35cc9027ebf7cf6c1b9a71478e7f685b5ac7',
amount: '10.5',
tokenType: 'flocoin', // Optional, defaults to 'flocoin'
});
// ETH transfer
const ethTransaction = await sdk.transfer({
walletId: 'wallet-id',
toAddress: '0x742d35cc9027ebf7cf6c1b9a71478e7f685b5ac7',
amount: '0.1',
tokenType: 'eth',
});Transaction History
// Get all transactions
const transactions = await sdk.getTransactions('wallet-id');
// With pagination
const paginatedTransactions = await sdk.getTransactions('wallet-id', {
limit: 10,
offset: 20,
});
console.log('Transactions:', paginatedTransactions.transactions);
console.log('Total Count:', paginatedTransactions.pagination.count);Wait for Confirmation
if (transaction.txHash) {
// Wait for 2 confirmations (default)
const confirmedTx = await sdk.waitForTransaction(transaction.txHash);
// Wait for custom confirmations with timeout
const confirmedTx = await sdk.waitForTransaction(
transaction.txHash,
3, // confirmations
300000 // timeout in ms
);
console.log('Transaction confirmed:', confirmedTx);
}🎫 NFT Management
List NFTs
// Get all NFTs for a wallet
const nfts = await sdk.getNFTs('wallet-id');
// With pagination
const paginatedNFTs = await sdk.getNFTs('wallet-id', {
limit: 20,
offset: 0,
});
console.log(`Found ${nfts.length} NFTs`);Get NFT Details
// Get specific NFT
const nft = await sdk.getNFT('wallet-id', 'nft-id');
console.log('NFT Name:', nft.metadata?.name);
console.log('Description:', nft.metadata?.description);
console.log('Attributes:', nft.metadata?.attributes);NFT Metadata
// Get metadata by contract and token ID
const metadata = await sdk.getNFTMetadata(
'0xcontractaddress',
'1' // token ID
);
console.log('Event Name:', metadata.eventId);
console.log('Ticket Type:', metadata.ticketType);
console.log('Attributes:', metadata.attributes);Transfer NFTs
const transferTx = await sdk.transferNFT(
'wallet-id',
'nft-id',
'0x742d35cc9027ebf7cf6c1b9a71478e7f685b5ac7'
);
console.log('NFT transfer initiated:', transferTx);
// Wait for confirmation
const confirmed = await sdk.waitForTransaction(transferTx.txHash);⛓️ Blockchain Operations
Token Information
const tokenInfo = await sdk.getTokenInfo();
console.log('Name:', tokenInfo.name); // "FLOcoin"
console.log('Symbol:', tokenInfo.symbol); // "FLO"
console.log('Decimals:', tokenInfo.decimals); // 18Gas Estimation
const gasEstimate = await sdk.estimateGas(
'0xfromaddress',
'0xtoaddress',
'100.0',
'flocoin'
);
console.log('Gas Limit:', gasEstimate.gasLimit);
console.log('Gas Price:', gasEstimate.gasPrice);
console.log('Estimated Cost:', gasEstimate.estimatedCostEth, 'ETH');Current Gas Price
const gasPrice = await sdk.getGasPrice();
console.log('Current Gas Price:', gasPrice.gasPriceGwei, 'gwei');Transaction Status
const status = await sdk.getTransactionStatus('0xtxhash');
console.log('Status:', status.status); // 'pending', 'confirmed', or 'failed'
console.log('Confirmations:', status.confirmations);
console.log('Block Number:', status.blockNumber);🎧 Event System
The SDK provides a comprehensive event system for real-time updates.
Available Events
// Wallet events
sdk.on('wallet:created', (wallet) => {
console.log('New wallet created:', wallet.address);
});
// Transaction events
sdk.on('transaction:started', (transaction) => {
console.log('Transaction started:', transaction.txHash);
});
sdk.on('transaction:confirmed', (transaction) => {
console.log('Transaction confirmed:', transaction.txHash);
});
sdk.on('transaction:failed', (transaction) => {
console.log('Transaction failed:', transaction.txHash);
});
// Balance events
sdk.on('balance:updated', (balance) => {
console.log('Balance updated:', balance.flocoin, 'FLO');
});
// Error events
sdk.on('error', (error) => {
console.error('SDK Error:', error.code, error.message);
});Event Management
// Add event listener
const handler = (wallet) => console.log('Wallet created:', wallet);
sdk.on('wallet:created', handler);
// Remove event listener
sdk.off('wallet:created', handler);
// Events are automatically emitted by the SDK
const wallet = await sdk.createWallet({ phoneNumber: '+1234567890' });
// 'wallet:created' event will be emitted automatically🛡️ Error Handling
Error Types
The SDK provides comprehensive error handling with specific error codes:
interface SDKError extends Error {
code: string;
statusCode?: number;
details?: any;
}Common Error Codes
try {
const wallet = await sdk.createWallet({ phoneNumber: 'invalid' });
} catch (error) {
switch (error.code) {
case 'INVALID_PHONE_NUMBER':
console.error('Phone number format is invalid');
break;
case 'WALLET_EXISTS':
console.error('Wallet already exists for this phone number');
break;
case 'RATE_LIMITED':
console.error('Too many requests, please try again later');
break;
case 'UNAUTHORIZED':
console.error('Authentication required');
break;
case 'INSUFFICIENT_BALANCE':
console.error('Not enough balance for this transaction');
break;
case 'NETWORK_ERROR':
console.error('Network connectivity issue');
break;
case 'TIMEOUT':
console.error('Request timed out');
break;
default:
console.error('Unexpected error:', error.message);
}
}Global Error Handling
// Listen for all errors
sdk.on('error', (error) => {
// Log to your error tracking service
console.error('SDK Error:', {
code: error.code,
message: error.message,
statusCode: error.statusCode,
});
});🎯 TypeScript Support
The SDK is built with TypeScript and provides complete type definitions.
Import Types
import {
FLOWalletSDK,
SDKConfig,
SDKWallet,
SDKBalance,
SDKTransaction,
SDKNFT,
NFTMetadata,
AuthenticationResult,
TransferOptions,
SDKError
} from 'flocoin-wallet-sdk';Type-Safe Configuration
const config: SDKConfig = {
environment: 'production',
timeout: 30000,
};
const wallet = new FLOWalletSDK(config);Generic Error Handling
const handleSDKError = (error: SDKError) => {
// TypeScript knows about all error properties
console.error(`Error ${error.code}: ${error.message}`);
if (error.statusCode) {
console.error(`HTTP Status: ${error.statusCode}`);
}
};🧪 Testing
The SDK includes comprehensive test coverage (90%+) with both unit and integration tests.
Running Tests
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
# Run tests in CI mode
npm run test:ciTest Categories
- Authentication Tests (15 test cases)
- Wallet Management Tests (20 test cases)
- Blockchain Integration Tests (12 test cases)
- NFT Functionality Tests (15 test cases)
- Event System Tests (8 test cases)
- Error Handling Tests (10 test cases)
Mock Testing
// The SDK includes comprehensive mocks for testing
import { FLOWalletSDK } from 'flocoin-wallet-sdk';
// Mock the SDK in your tests
jest.mock('flocoin-wallet-sdk');
const mockSDK = FLOWalletSDK as jest.MockedClass<typeof FLOWalletSDK>;📝 Examples
EventFlo Integration
// Auto-create wallet on user signup
async function onUserSignup(phoneNumber: string, eventFloUserId: string) {
const userWallet = await wallet.createWallet({
phoneNumber,
userId: eventFloUserId,
});
return userWallet;
}
// Process ticket purchase payment
async function processTicketPayment(userWalletId: string, ticketPrice: string) {
const transaction = await wallet.transfer({
walletId: 'eventflo-treasury-wallet-id',
toAddress: userWalletId,
amount: ticketPrice,
tokenType: 'flocoin',
});
return transaction;
}Real-time Balance Monitoring
// Set up real-time balance monitoring
wallet.on('balance:updated', (balance) => {
updateUI({
flocoin: balance.flocoin,
eth: balance.eth,
usd: balance.usd,
});
});
// Trigger balance update
setInterval(async () => {
await wallet.getBalance(walletId);
}, 30000); // Check every 30 secondsComplete Transaction Flow
async function completeTransactionFlow() {
try {
// 1. Check balance
const balance = await wallet.getBalance(walletId);
if (parseFloat(balance.flocoin) < parseFloat(amount)) {
throw new Error('Insufficient balance');
}
// 2. Estimate gas costs
const gasEstimate = await wallet.estimateGas(
walletAddress,
recipientAddress,
amount,
'flocoin'
);
// 3. Show confirmation to user
const confirmed = await showConfirmation({
amount,
recipient: recipientAddress,
estimatedGas: gasEstimate.estimatedCostEth,
});
if (!confirmed) return;
// 4. Execute transfer
const transaction = await wallet.transfer({
walletId,
toAddress: recipientAddress,
amount,
tokenType: 'flocoin',
});
// 5. Wait for confirmation
const confirmed = await wallet.waitForTransaction(transaction.txHash);
console.log('Transaction completed successfully!');
return confirmed;
} catch (error) {
console.error('Transaction failed:', error);
throw error;
}
}📚 API Reference
Authentication Methods
| Method | Description | Returns |
|--------|-------------|---------|
| sendOTP(phoneNumber) | Send OTP to phone number | Promise<OTPResult> |
| verifyOTP(phoneNumber, otp, sessionId) | Verify OTP and authenticate | Promise<AuthenticationResult> |
| refreshAccessToken() | Refresh access token | Promise<{token, refreshToken}> |
| logout() | Logout user | Promise<void> |
| getCurrentUser() | Get current user info | Promise<SDKUser> |
Wallet Methods
| Method | Description | Returns |
|--------|-------------|---------|
| createWallet(options) | Create new wallet | Promise<SDKWallet> |
| getWallet(walletId) | Get wallet by ID | Promise<SDKWallet> |
| getBalance(walletId) | Get wallet balance | Promise<SDKBalance> |
| transfer(options) | Transfer tokens | Promise<SDKTransaction> |
| getTransactions(walletId, pagination?) | Get transaction history | Promise<TransactionListResult> |
| deriveAddress(walletId, index) | Derive HD wallet address | Promise<DerivedAddress> |
| importWallet(options) | Import wallet from mnemonic | Promise<SDKWallet> |
NFT Methods
| Method | Description | Returns |
|--------|-------------|---------|
| getNFTs(walletId, pagination?) | Get wallet NFTs | Promise<SDKNFT[]> |
| getNFT(walletId, nftId) | Get specific NFT | Promise<SDKNFT> |
| transferNFT(walletId, nftId, toAddress) | Transfer NFT | Promise<SDKTransaction> |
| getNFTMetadata(contractAddress, tokenId) | Get NFT metadata | Promise<NFTMetadata> |
Blockchain Methods
| Method | Description | Returns |
|--------|-------------|---------|
| getTokenInfo() | Get FLOcoin token info | Promise<TokenInfo> |
| getAddressBalance(address) | Get balance for any address | Promise<SDKBalance> |
| getTransactionStatus(txHash) | Get transaction status | Promise<TransactionStatus> |
| estimateGas(from, to, amount, tokenType?) | Estimate gas costs | Promise<GasEstimate> |
| getGasPrice() | Get current gas price | Promise<{gasPrice, gasPriceGwei}> |
| waitForTransaction(txHash, confirmations?, timeout?) | Wait for confirmation | Promise<TransactionStatus> |
Utility Methods
| Method | Description | Returns |
|--------|-------------|---------|
| setAccessToken(token) | Set access token manually | void |
| setRefreshToken(token) | Set refresh token manually | void |
| getAccessToken() | Get current access token | string \| undefined |
| isAuthenticated() | Check authentication status | boolean |
| on(event, handler) | Add event listener | void |
| off(event, handler) | Remove event listener | void |
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
git clone https://github.com/flocoin/wallet-system.git
cd wallet-system/packages/sdk-js
npm install
npm testPull Request Process
- Fork the repository
- Create a feature branch
- Add tests for your changes
- Ensure all tests pass
- Submit a pull request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
- 📖 Documentation
- 🐛 Issue Tracker
- 💬 Discord Community
- 📧 Email: [email protected]
🎯 Roadmap
- ✅ Phone-based authentication
- ✅ FLOcoin token operations
- ✅ EventFlo NFT integration
- ✅ TypeScript support
- ✅ Comprehensive testing
- 🔄 Multi-chain support (coming soon)
- 🔄 Flutter SDK (in development)
- 🔄 React Native components (planned)
Built with ❤️ by the FLOcoin Team
