UNPKG

@agentdao/core

Version:

Core functionality, skills, and ready-made UI components for AgentDAO - Web3 subscriptions, content generation, social media, help support, live chat, RSS fetching, web search, and agent pricing integration

255 lines (254 loc) 9.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.basicPricingIntegration = basicPricingIntegration; exports.accessControlExample = accessControlExample; exports.dynamicPricingDisplay = dynamicPricingDisplay; exports.enforceUsageLimits = enforceUsageLimits; exports.featureBasedAccess = featureBasedAccess; exports.paymentProcessing = paymentProcessing; exports.createAccessControlMiddleware = createAccessControlMiddleware; exports.PricingDisplayComponent = PricingDisplayComponent; const AgentPricingSDK_1 = require("../AgentPricingSDK"); // Example 1: Basic usage in a deployed agent async function basicPricingIntegration() { // Initialize the SDK with your agent ID const agentId = 123; // Replace with your actual agent ID const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); try { // Get the full pricing configuration const config = await pricingSDK.getPricingConfig(); console.log('Agent pricing config:', config); // Check if agent is available for hire const isAvailable = await pricingSDK.isAvailableForHire(); console.log('Agent available for hire:', isAvailable); // Get pricing plans const plans = await pricingSDK.getPricingPlans(); console.log('Available plans:', plans); // Get accepted tokens const tokens = await pricingSDK.getAcceptedTokens(); console.log('Accepted tokens:', tokens); } catch (error) { console.error('Error fetching pricing config:', error); } } // Example 2: Access control in a deployed agent async function accessControlExample() { const agentId = 123; const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); // Simulate a user request with their plan/token const userPlan = 'monthly'; const userToken = 'ADAO'; try { // Validate user access const accessResult = await pricingSDK.validateAccess(userPlan, userToken); if (accessResult.hasAccess) { console.log('User has access to the agent'); // Proceed with agent functionality return true; } else { console.log('Access denied:', accessResult.reason); console.log('Required plan:', accessResult.requiredPlan); console.log('Required token:', accessResult.requiredToken); // Redirect to pricing page or show upgrade message return false; } } catch (error) { console.error('Error validating access:', error); return false; } } // Example 3: Dynamic pricing display in agent UI async function dynamicPricingDisplay() { const agentId = 123; const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); try { const plans = await pricingSDK.getPricingPlans(); const tokens = await pricingSDK.getAcceptedTokens(); // Generate pricing UI dynamically const pricingUI = Object.entries(plans).map(([planId, plan]) => ({ id: planId, name: plan.name, price: plan.price, features: plan.features || [], acceptedTokens: Object.keys(tokens) })); console.log('Pricing UI data:', pricingUI); return pricingUI; } catch (error) { console.error('Error generating pricing UI:', error); return []; } } // Example 4: Usage limits enforcement async function enforceUsageLimits(userId) { const agentId = 123; const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); try { const usageLimits = await pricingSDK.getUsageLimits(); const rateLimits = await pricingSDK.getRateLimits(); // Check if user has exceeded their limits // This would typically involve checking against a database const userUsage = await getUserUsage(userId, agentId); if (usageLimits.requests_per_month && userUsage.requests >= usageLimits.requests_per_month) { throw new Error('Monthly request limit exceeded'); } if (rateLimits.requests_per_minute && userUsage.recentRequests >= rateLimits.requests_per_minute) { throw new Error('Rate limit exceeded'); } return true; } catch (error) { console.error('Usage limit check failed:', error); return false; } } // Example 5: Feature-based access control async function featureBasedAccess() { const agentId = 123; const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); try { // Check if specific features are enabled const hasAnalytics = await pricingSDK.hasFeature('analytics'); const hasPrioritySupport = await pricingSDK.hasFeature('priority_support'); const hasCustomIntegrations = await pricingSDK.hasFeature('custom_integrations'); // Enable/disable features based on configuration if (hasAnalytics) { enableAnalytics(); } if (hasPrioritySupport) { enablePrioritySupport(); } if (hasCustomIntegrations) { enableCustomIntegrations(); } return { analytics: hasAnalytics, prioritySupport: hasPrioritySupport, customIntegrations: hasCustomIntegrations }; } catch (error) { console.error('Error checking features:', error); return { analytics: false, prioritySupport: false, customIntegrations: false }; } } // Example 6: Payment processing integration async function paymentProcessing(userPlan, userToken) { const agentId = 123; const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); try { const config = await pricingSDK.getPricingConfig(); const plans = await pricingSDK.getPricingPlans(); const tokens = await pricingSDK.getAcceptedTokens(); // Get plan details const plan = plans[userPlan]; if (!plan) { throw new Error('Invalid plan'); } // Get token details const token = tokens[userToken]; if (!token) { throw new Error('Invalid token'); } // Calculate payment amounts const planPrice = plan.price; const platformFee = config.pricing.platform_commission_rate / 100; const platformAmount = planPrice * platformFee; const developerAmount = planPrice - platformAmount; // Process payment (this would integrate with your payment system) const paymentResult = await processPayment({ amount: planPrice, token: userToken, tokenAddress: token.address, platformAmount, developerAmount, developerWallet: config.pricing.payment_wallet_address }); return paymentResult; } catch (error) { console.error('Payment processing failed:', error); throw error; } } // Example 7: Express.js middleware for access control function createAccessControlMiddleware(agentId) { const pricingSDK = new AgentPricingSDK_1.AgentPricingSDK(agentId); return async (req, res, next) => { try { // Extract user plan/token from request (headers, query params, etc.) const userPlan = req.headers['x-user-plan']; const userToken = req.headers['x-user-token']; // Validate access const accessResult = await pricingSDK.validateAccess(userPlan, userToken); if (!accessResult.hasAccess) { return res.status(403).json({ error: 'Access denied', reason: accessResult.reason, requiredPlan: accessResult.requiredPlan, requiredToken: accessResult.requiredToken }); } // Add pricing info to request for downstream use req.pricingConfig = await pricingSDK.getPricingConfig(); next(); } catch (error) { console.error('Access control middleware error:', error); return res.status(500).json({ error: 'Internal server error' }); } }; } // Example 8: React component for pricing display // Note: This is a conceptual example - in a real React app, you'd need to import React function PricingDisplayComponent({ agentId }) { // This would be implemented in a real React component // const [pricingConfig, setPricingConfig] = React.useState<any>(null); // const [loading, setLoading] = React.useState(true); // React.useEffect(() => { // const fetchPricing = async () => { // try { // const pricingSDK = new AgentPricingSDK(agentId); // const config = await pricingSDK.getPricingConfig(); // setPricingConfig(config); // } catch (error) { // console.error('Error fetching pricing:', error); // } finally { // setLoading(false); // } // }; // // fetchPricing(); // }, [agentId]); console.log('PricingDisplayComponent would render pricing for agent:', agentId); return null; } // Helper functions (these would be implemented in your actual application) async function getUserUsage(userId, agentId) { // Implementation would check your database for user usage return { requests: 0, recentRequests: 0 }; } async function processPayment(paymentDetails) { // Implementation would integrate with your payment system return { success: true, transactionId: 'tx_123' }; } function enableAnalytics() { // Implementation would enable analytics features } function enablePrioritySupport() { // Implementation would enable priority support features } function enableCustomIntegrations() { // Implementation would enable custom integration features } function handlePurchase(planId) { // Implementation would handle plan purchase }