Mirra
Developer Resources

Script Examples

Scripts are serverless functions that execute custom logic in response to events, schedules, or API calls. These examples demonstrate common patterns for building production-ready scripts, from simple data processing to complex event-driven workflows.

Each example includes complete, runnable code with explanations of key concepts and deployment instructions.

Examples

Tracking cryptocurrency price changes

This example demonstrates how to build a price tracking script that monitors cryptocurrency prices and generates alerts when significant price movements occur. The script fetches current prices, calculates 24-hour percentage changes, and filters results based on a configurable threshold.

JavaScript

export async function handler(event) {
  const { symbols, threshold } = event;
  
  // Fetch current prices for all symbols
  const prices = await Promise.all(
    symbols.map(symbol => fetchPrice(symbol))
  );
  
  // Calculate 24-hour price changes
  const changes = prices.map((price, i) => ({
    symbol: symbols[i],
    price: price.current,
    change24h: price.change24h,
    changePercent: ((price.current - price.prev24h) / price.prev24h) * 100
  }));
  
  // Filter for significant price movements
  const alerts = changes.filter(c => 
    Math.abs(c.changePercent) >= threshold
  );
  
  return {
    timestamp: new Date().toISOString(),
    prices: changes,
    alerts: alerts.length > 0 ? alerts : null
  };
}

Deployment

Deploy the script using the POST /api/sdk/v1/scripts endpoint:

curl -X POST https://api.fxn.world/api/sdk/v1/scripts \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Price Tracker",
    "description": "Tracks crypto prices and alerts on changes",
    "runtime": "nodejs18",
    "code": "...",
    "config": {
      "timeout": 30,
      "memory": 256
    }
  }'

Result

The script returns an object containing all price data and any alerts for symbols that exceeded the threshold. This pattern is useful for monitoring markets, triggering notifications, or feeding data to dashboards.

Transforming JSON data with dynamic operations

This example shows how to build a data transformation script that applies a series of operations to JSON data. The script supports filtering, mapping, and reducing operations, making it useful for ETL pipelines and data processing workflows.

JavaScript

export async function handler(event) {
  const { data, transformations } = event;
  
  let result = data;
  
  // Apply each transformation in sequence
  for (const transform of transformations) {
    switch (transform.type) {
      case 'filter':
        result = result.filter(transform.predicate);
        break;
      case 'map':
        result = result.map(transform.mapper);
        break;
      case 'reduce':
        result = result.reduce(transform.reducer, transform.initial);
        break;
    }
  }
  
  return { transformed: result };
}

Result

The script processes the input data through each transformation step and returns the final result. This pattern enables flexible data processing without modifying the script code—simply pass different transformation configurations in the event payload.

Processing webhook events

This example demonstrates a webhook handler script that processes different types of incoming events. The script uses a switch statement to route events to appropriate handler functions, making it easy to add new event types as your integration grows.

JavaScript

export async function handler(event) {
  const { type, payload } = event;
  
  // Route to appropriate handler based on event type
  switch (type) {
    case 'payment.completed':
      await handlePayment(payload);
      break;
    case 'user.created':
      await sendWelcomeEmail(payload);
      break;
    default:
      console.log('Unhandled event:', type);
  }
  
  return { processed: true };
}
 
async function handlePayment(payload) {
  // Process payment confirmation
  console.log('Payment processed:', payload.amount);
}
 
async function sendWelcomeEmail(payload) {
  // Send welcome email to new user
  console.log('Welcome email sent to:', payload.email);
}

Result

The script processes the webhook event and returns a confirmation. This pattern is ideal for integrating with third-party services that send webhook notifications, such as payment processors, CRM systems, or messaging platforms.

Running scheduled tasks

This example shows how to build a scheduled task script that runs periodically using cron scheduling. The script fetches data, processes it, and sends notifications—a common pattern for monitoring, reporting, and data synchronization tasks.

JavaScript

export async function handler(event) {
  const now = new Date();
  
  // Fetch latest data from your source
  const data = await fetchLatestData();
  
  // Process and summarize the data
  const summary = {
    timestamp: now.toISOString(),
    recordsProcessed: data.length,
    summary: calculateSummary(data)
  };
  
  // Send notification with results
  await notifyWebhook(summary);
  
  return summary;
}

Result

The script executes on schedule (e.g., every 5 minutes) and returns a summary of the processed data. Configure the schedule when creating the script using cron syntax. This pattern is useful for periodic data collection, health checks, and automated reporting.

Handling errors gracefully

This example demonstrates error handling best practices for production scripts. Always wrap risky operations in try-catch blocks and return structured error responses that help with debugging and monitoring.

JavaScript

export async function handler(event) {
  try {
    const result = await riskyOperation(event);
    return { success: true, result };
  } catch (error) {
    console.error('Operation failed:', error);
    return { 
      success: false, 
      error: error.message,
      timestamp: new Date().toISOString()
    };
  }
}

Result

The script returns a structured response indicating success or failure. This pattern ensures your scripts fail gracefully and provide useful error information for debugging. Always log errors for monitoring and alerting purposes.

Testing Scripts

Executing a script

Test your script by sending a request to the execute endpoint:

curl -X POST https://api.fxn.world/api/sdk/v1/scripts/SCRIPT_ID/execute \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "data": {
      "symbols": ["BTC", "ETH", "SOL"],
      "threshold": 5
    }
  }'

The response includes the script's return value and execution metadata such as duration and memory usage.

Monitoring execution history

Check execution history and performance metrics:

curl https://api.fxn.world/api/sdk/v1/scripts/SCRIPT_ID/executions \
  -H "Authorization: Bearer YOUR_API_KEY"

This endpoint returns a list of recent executions with timestamps, status codes, and error messages for failed executions.

Best Practices

Resource optimization

Configure your scripts for optimal performance and cost:

  • Timeout values: Set timeouts based on expected execution time (default: 30 seconds)
  • Memory allocation: Start with 256 MB and increase if needed
  • Caching: Cache frequently accessed data to reduce API calls
  • Batching: Batch multiple API requests using Promise.all() to reduce latency

Input validation

Validate input parameters at the start of your handler function:

export async function handler(event) {
  if (!event.symbols || !Array.isArray(event.symbols)) {
    return { error: 'symbols must be an array' };
  }
  
  if (typeof event.threshold !== 'number') {
    return { error: 'threshold must be a number' };
  }
  
  // Process validated input
}

Testing checklist

Before deploying to production:

  1. Validate all input parameters and edge cases
  2. Test error scenarios and timeout conditions
  3. Verify resource limits (memory, timeout)
  4. Check output format matches expected schema
  5. Test with production-like data volumes

See also

On this page