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; } }javascript import { ApolloClient, InMemoryCache, gql, HttpLink } from '@apollo/client'; const client = new ApolloClient({ link: new HttpLink({ uri: 'https://api.noderr.xyz/graphql', headers: { Authorization: `Bearer ${process.env.NODERR_API_KEY}` } }), cache: new InMemoryCache() }); // Query vault details const GET_VAULT = gql` query GetVault($id: ID!) { vault(id: $id) { id name totalAssets apy strategies { id name allocation } } } `; async function fetchVault(id) { try { const result = await client.query({ query: GET_VAULT, variables: { id } }); return result.data.vault; } catch (error) { console.error('GraphQL query failed:', error); throw error; } } // Query user governance votes const GET_USER_VOTES = gql` query GetUserVotes($userId: ID!) { user(id: $userId) { id votes { proposalId vote votingPower timestamp } } } `; // Query performance metrics const GET_VAULT_PERFORMANCE = gql` query GetVaultPerformance($vaultId: ID!, $period: String!) { vaultPerformance(vaultId: $vaultId, period: $period) { returns volatility sharpeRatio maxDrawdown } } `; // Query governance proposals const GET_PROPOSALS = gql` query GetProposals($status: String!) { proposals(status: $status) { id title description votesFor votesAgainst endTime } } `;javascript import { WebSocketLink } from '@apollo/client/link/ws'; const wsLink = new WebSocketLink({ uri: 'wss://api.noderr.xyz/graphql', options: { reconnect: true, connectionParams: { authToken: process.env.NODERR_API_KEY } } }); // Subscribe to price updates const PRICE_SUBSCRIPTION = gql` subscription OnPriceUpdate($assetId: ID!) { priceUpdated(assetId: $assetId) { assetId price change24h timestamp } } `; function subscribeToPrices(assetId, onUpdate) { const subscription = client.subscribe({ query: PRICE_SUBSCRIPTION, variables: { assetId } }); subscription.subscribe({ next: (data) => onUpdate(data.data.priceUpdated), error: (error) => console.error('Subscription error:', error), : () => console.log('Subscription ') }); return subscription; } // Subscribe to vault APY changes const APY_SUBSCRIPTION = gql` subscription OnApyChange($vaultId: ID!) { apyChanged(vaultId: $vaultId) { vaultId newApy previousApy timestamp } } `; // Subscribe to governance events const GOVERNANCE_SUBSCRIPTION = gql` subscription OnGovernanceEvent { governanceEvent { type proposalId voter vote timestamp } } `; // Subscribe to transaction events const TRANSACTION_SUBSCRIPTION = gql` subscription OnTransaction($userId: ID!) { transactionCreated(userId: $userId) { id type amount status timestamp } } `;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; } }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); } }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')); }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; });