Mirra
Mirra APIScripts

Script Examples

Scripts enable you to build serverless functions that execute custom logic in response to events, schedules, or API calls. These examples demonstrate common patterns for building production-ready scripts.

Tracking Ticker Mentions

This example demonstrates event-driven execution with entity extraction. The script subscribes to Telegram messages and voice transcripts containing ticker symbols, then logs each mention to memory.

Script Code

export async function handler(event, context) {
  // Check if event contains ticker entities
  if (!event.entities?.tickers) {
    return { success: true, message: 'No tickers found' };
  }
  
  // Log each ticker mention
  for (const ticker of event.entities.tickers) {
    await mirra.memory.create({
      type: 'ticker_mention',
      content: `${ticker.symbol} mentioned: ${event.messageText}`,
      metadata: {
        ticker: ticker.symbol,
        confidence: ticker.confidence,
        source: event.source,
        timestamp: event.timestamp
      }
    });
  }
  
  return {
    success: true,
    tickersTracked: event.entities.tickers.length
  };
}

Subscription Configuration

{
  "conditions": [
    {
      "field": "entities.tickers",
      "operator": "exists"
    }
  ]
}

Telegram Auto-Responder

This example shows basic message handling and response. The script receives Telegram messages and sends an acknowledgment reply.

Script Code

export async function handler(event, context) {
  // Verify event type
  if (event.type !== 'telegram.message') {
    return { success: false, error: 'Not a Telegram message' };
  }
  
  // Send response
  await mirra.telegram.sendMessage({
    chatId: event.telegramChatId,
    text: `Received: ${event.messageText}`
  });
  
  return { success: true };
}

Calendar Event Logger

This example demonstrates calendar integration. The script logs new calendar events to memory with structured metadata.

Script Code

export async function handler(event, context) {
  // Verify event type
  if (event.type !== 'calendar.event_created') {
    return { success: false, error: 'Not a calendar event' };
  }
  
  // Create memory entry
  await mirra.memory.create({
    type: 'calendar_event',
    content: event.calendarSummary,
    metadata: {
      eventId: event.calendarEventId,
      startTime: event.calendarStartTime,
      endTime: event.calendarEndTime,
      location: event.calendarLocation,
      attendees: event.calendarAttendees
    }
  });
  
  return { success: true };
}

Data Processing Pipeline

This example shows manual script execution for data transformation. The script processes an array of items, adding timestamps and processing flags.

Script Code

export async function handler(event, context) {
  // Validate input
  if (!event.data || !Array.isArray(event.data)) {
    return { success: false, error: 'Invalid input: expected data array' };
  }
  
  // Process each item
  const result = event.data.map(item => ({
    ...item,
    processed: true,
    processedAt: new Date().toISOString(),
    processedBy: context.scriptId
  }));
  
  return {
    success: true,
    itemsProcessed: result.length,
    result
  };
}

Cryptocurrency Price Tracking

This example builds a price tracking script that monitors cryptocurrency prices and generates alerts when significant price movements occur.

Script Code

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
  };
}

Execution

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
    }
  }'

JSON Data Transformation

This example shows how to build a data transformation script that applies a series of operations to JSON data.

Script Code

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.


Webhook Event Handler

This example demonstrates a webhook handler script that processes different types of incoming events.

Script Code

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);
}

Scheduled Task Script

This example shows how to build a scheduled task script that runs periodically using cron scheduling.

Script Code

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.


Error Handling Best Practices

This example demonstrates error handling for production scripts.

Script Code

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. Always log errors for monitoring and alerting purposes.


Best Practices

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
}

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

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