JavaScript/TypeScript Integration Guide Home > Developers > JavaScript/TypeScript Integration guide to integrating with Noderr Protocol using JavaScript/TypeScript with production-ready code examples.

REST API Client javascript import axios from 'axios'; const noderrClient = axios.create({ baseURL: 'https://api.noderr.xyz/v1', timeout: 10000, headers: { 'Authorization': `Bearer ${process.env.NODERR_API_KEY}` } }); // Fetch vault information async function getVault(vaultId) { try { const response = await noderrClient.get(`/vaults/${vaultId}`); return response.data; } catch (error) { console.error('Failed to fetch vault:', error.message); throw error; } } // Deposit to vault async function depositToVault(vaultId, amount) { try { const response = await noderrClient.post(`/vaults/${vaultId}/deposit`, { amount: amount }); return response.data; } catch (error) { console.error('Deposit failed:', error.message); throw error; } } // Get user portfolio async function getUserPortfolio(userId) { try { const response = await noderrClient.get(`/users/${userId}/portfolio`); return response.data; } catch (error) { console.error('Failed to fetch portfolio:', error.message); throw error; } } // Withdraw from vault async function withdrawFromVault(vaultId, shares) { try { const response = await noderrClient.post(`/vaults/${vaultId}/withdraw`, { shares: shares }); return response.data; } catch (error) { console.error('Withdrawal failed:', error.message); throw error; } }

Smart Contract Interaction javascript import { ethers } from 'ethers'; import VAULT_ABI from './abis/Vault.json'; // Initialize provider and signer const provider = new ethers.providers.JsonRpcProvider( process.env.RPC_URL ); const signer = new ethers.Wallet( process.env.PRIVATE_KEY, provider ); // Create contract instance const vaultAddress = '0x...'; const vault = new ethers.Contract(vaultAddress, VAULT_ABI, signer); // Get vault balance async function getVaultBalance(userAddress) { try { const balance = await vault.balanceOf(userAddress); return ethers.utils.formatUnits(balance, 18); } catch (error) { console.error('Failed to get balance:', error); throw error; } } // Deposit to vault async function depositToVault(amount) { try { const token = new ethers.Contract( await vault.asset(), ['function approve(address spender, uint256 amount) returns (bool)'], signer ); const approveTx = await token.approve( vaultAddress, ethers.utils.parseUnits(amount, 18) ); await approveTx.wait(); const depositTx = await vault.deposit( ethers.utils.parseUnits(amount, 18), signer.address ); const receipt = await depositTx.wait(); return receipt; } catch (error) { console.error('Deposit failed:', error); throw error; } } // Withdraw from vault async function withdrawFromVault(shares) { try { const withdrawTx = await vault.withdraw( ethers.utils.parseUnits(shares, 18), signer.address, signer.address ); const receipt = await withdrawTx.wait(); return receipt; } catch (error) { console.error('Withdrawal failed:', error); throw error; } } // Monitor transaction status async function monitorTransaction(txHash) { try { const receipt = await provider.waitForTransaction(txHash); if (receipt.status === 1) { console.log('Transaction confirmed'); return receipt; } else { throw new Error('Transaction reverted'); } } catch (error) { console.error('Failed to monitor transaction:', error); throw error; } }

Error Handling javascript // Custom error class class NoderrError extends Error { constructor(message, code, details) { super(message); this.code = code; this.details = details; this.timestamp = new Date(); } } // Retry logic with exponential backoff async function retryWithBackoff(fn, maxRetries = 3, baseDelay = 1000) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await fn(); } catch (error) { if (attempt === maxRetries - 1) throw error; const delay = baseDelay * Math.pow(2, attempt); console.log(`Retry attempt ${attempt + 1} after ${delay}ms`); await new Promise(resolve => setTimeout(resolve, delay)); } } } // Timeout handling function withTimeout(promise, timeoutMs) { return Promise.race([ promise, new Promise((_, reject) => setTimeout( () => reject(new NoderrError('Operation timeout', 'TIMEOUT', {})), timeoutMs ) ) ]); } // Comprehensive error handler async function safeApiCall(apiFunction, context = {}) { try { return await withTimeout(apiFunction(), 10000); } catch (error) { if (error.code === 'TIMEOUT') { console.error('API call timed out'); } else if (error.response?.status === 429) { console.error('Rate limited'); } else if (error.response?.status === 401) { console.error('Authentication failed'); } else { console.error('Unexpected error:', error.message); } throw new NoderrError(error.message, error.code, context); } }

Rate Limiting Handling javascript class RateLimitedClient { constructor(maxRequests = 100, windowMs = 60000) { this.maxRequests = maxRequests; this.windowMs = windowMs; this.requests = []; } async executeRequest(fn) { const now = Date.now(); this.requests = this.requests.filter(time => now - time < this.windowMs); if (this.requests.length >= this.maxRequests) { const oldestRequest = this.requests[0]; const waitTime = this.windowMs - (now - oldestRequest); console.log(`Rate limit reached. Waiting ${waitTime}ms`); await new Promise(resolve => setTimeout(resolve, waitTime)); return this.executeRequest(fn); } this.requests.push(Date.now()); return fn(); } } const client = new RateLimitedClient(100, 60000); async function apiCall() { return client.executeRequest(() => noderrClient.get('/data')); }

Authentication Flow javascript class AuthManager { constructor() { this.token = localStorage.getItem('noderr_token'); this.refreshToken = localStorage.getItem('noderr_refresh_token'); this.tokenExpiry = parseInt(localStorage.getItem('noderr_token_expiry') || '0'); } async login(email, password) { const response = await axios.post('https://api.noderr.xyz/auth/login', { email, password }); this.setTokens(response.data); return response.data; } setTokens(data) { this.token = data.accessToken; this.refreshToken = data.refreshToken; this.tokenExpiry = Date.now() + (data.expiresIn * 1000); localStorage.setItem('noderr_token', this.token); localStorage.setItem('noderr_refresh_token', this.refreshToken); localStorage.setItem('noderr_token_expiry', this.tokenExpiry.toString()); } async refreshAccessToken() { const response = await axios.post('https://api.noderr.xyz/auth/refresh', { refreshToken: this.refreshToken }); this.setTokens(response.data); return this.token; } async logout() { localStorage.removeItem('noderr_token'); localStorage.removeItem('noderr_refresh_token'); localStorage.removeItem('noderr_token_expiry'); this.token = null; this.refreshToken = null; } isTokenExpired() { return Date.now() > this.tokenExpiry - 60000; } async getValidToken() { if (this.isTokenExpired()) { await this.refreshAccessToken(); } return this.token; } } const authManager = new AuthManager(); noderrClient.interceptors.request.use(async (config) => { const token = await authManager.getValidToken(); config.headers.Authorization = `Bearer ${token}`; return config; });

Best Practices Summary 1. Always use try-catch blocks for async operations 2. Implement retry logic with exponential backoff 3. Set appropriate timeouts for all API calls 4. Handle rate limiting gracefully with queuing 5. Manage authentication tokens securely 6. Log errors with context for debugging 7. Validate responses before using data 8. Use TypeScript for type safety in production --- See Also:REST API Documentation | GraphQL API Documentation | Smart Contract Integration --- See Also: - Noderr White Paper v7.1 - Noderr Lite Paper v3.1 - Noderr Protocol Documentation

results matching ""

    No results matching ""