> ## Documentation Index
> Fetch the complete documentation index at: https://docs.snagsolutions.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions

> Write and deploy serverless JavaScript functions on Snag Stratus. Schedule via cron, trigger via webhooks, or chain to onchain subscriptions for custom reward logic.

<head>
  <script type="application/ld+json">
    {JSON.stringify({
            "@context": "https://schema.org",
            "@graph": [
              {
                "@type": "TechArticle",
                "headline": "Functions",
                "description": "Write and deploy serverless JavaScript functions on Snag Stratus. Schedule via cron, trigger via webhooks, or chain to onchain subscriptions for custom reward logic.",
                "author": {"@type": "Organization", "name": "Snag Solutions", "url": "https://www.snagsolutions.io/"},
                "publisher": {"@type": "Organization", "name": "Snag Solutions", "url": "https://www.snagsolutions.io/", "logo": {"@type": "ImageObject", "url": "https://assets.snagsolutions.io/public/docs/snag-logo-dark-no-bg.svg"}},
                "mainEntityOfPage": "https://docs.snagsolutions.io/stratus/functions"
              },
              {
                "@type": "BreadcrumbList",
                "itemListElement": [
                  {"@type": "ListItem", "position": 1, "name": "Home", "item": "https://docs.snagsolutions.io/welcome"},
                  {"@type": "ListItem", "position": 2, "name": "Stratus", "item": "https://docs.snagsolutions.io/stratus/stratus-overview"},
                  {"@type": "ListItem", "position": 3, "name": "Functions", "item": "https://docs.snagsolutions.io/stratus/functions"},
                  {"@type": "ListItem", "position": 4, "name": "Functions"}
                ]
              }
            ]
          })}
  </script>
</head>

<Tip>
  **Using an AI coding assistant?** Connect Cursor, Claude, or Copilot to Snag Docs for context-aware help. [Learn how](/ai-coding-assistant).
</Tip>

## Overview

Stratus functions enable developers to write and execute JavaScript functions in a serverless environment. These functions:

* Scale horizontally
* Run in isolated VMs
* Have web access for external integrations
* Support complex logic combinations

<Note>
  Functions can interact with external services, allowing you to integrate with your own database, subgraphs, and other services.
</Note>

## Invocation Types

<CardGroup cols={3}>
  <Card title="Schedule" icon="calendar">
    Execute functions on a cron schedule with minimum 1-minute resolution
  </Card>

  <Card title="Webhook" icon="webhook">
    Invoke functions via HTTP POST requests using API keys
  </Card>

  <Card title="Subscription" icon="bell">
    Trigger functions automatically when subscribed events occur
  </Card>
</CardGroup>

### Schedule Invocation

<Note>
  While there's no maximum schedule limit, the minimum resolution is 1 minute. Schedules with smaller intervals will fail.
</Note>

### Webhook Invocation

To invoke functions via webhook:

1. Create a Stratus-scoped API key in the admin panel
2. Use the unique webhook URL assigned to your function

<CodeGroup>
  ```bash Webhook Example theme={null}
  curl --request POST \
    --url https://admin.snagsolutions.io/api/stratus/functions/<functionID>/invoke \
    --header 'Content-Type: application/json' \
    --header 'X-API-KEY: <stratus_api_key>' \
    --data '{
      "organizationId": "org-1234",
      "websiteId": "site-5678",
      "input": {
        "foo": 123,
        "bar": "example value"
      }
    }'
  ```
</CodeGroup>

### Subscription Invocation

<Note>
  Functions linked to subscriptions execute automatically when subscription events fire. Unlike webhooks, subscription-based invocations receive a single payload per event.
</Note>

## Writing Functions

### Basic Structure

All Stratus functions must follow these rules:

<Steps>
  <Step title="Export Single Handler">
    Only one handler function can be exported per file
  </Step>

  <Step title="Use Async Function">
    Handlers must be asynchronous
  </Step>

  <Step title="Include Required Parameters">
    Functions must accept `input` and `output` parameters
  </Step>
</Steps>

```javascript Basic Template theme={null}
module.exports.handler = async (input, output) => {
  // Your function logic here
};
```

### The Output Class

The `output` parameter provides methods for managing function results and actions:

<ResponseField name="setResult" type="function">
  Sets the function result data (called once before buildOutput)

  ```typescript theme={null}
  setResult(resultObject: Record<string, any>): void
  ```
</ResponseField>

<ResponseField name="setError" type="function">
  Logs a failure and stops future executions

  ```typescript theme={null}
  setError(error: string): void
  ```
</ResponseField>

<ResponseField name="addTransaction" type="function">
  Adds a transaction to the execution queue (requires relayer connection)

  ```typescript theme={null}
  addTransaction(tx: Pick<SendTransactionParameters, 'to' | 'data' | 'value'>): void
  ```
</ResponseField>

<ResponseField name="buildOutput" type="function">
  Finalizes and returns the function output (required)

  ```typescript theme={null}
  buildOutput(): Record<string, any>
  ```
</ResponseField>

## Executing Transactions

<Note>
  To execute transactions, your function must be connected to a relayer in your account.
</Note>

### Transaction Rules

* Maximum 500 transactions per function run
* Transactions execute in the order they're added
* All transactions use the connected relayer

## Approved Modules

<Warning>
  Only pre-approved npm modules can be used in Stratus functions. Contact Snag Solutions if you need additional modules.
</Warning>

Currently approved modules:

* [`axios`](https://axios-http.com/)
* [`lodash`](https://lodash.com/docs)
* [`viem`](https://viem.sh/)
* `ioRedis`
* `upstash/redis`

## Example Function

```javascript theme={null}
const axios = require('axios');

module.exports.handler = async (input, output) => {
  try {
    // Make an external API call
    const response = await axios.get('https://api.example.com/data');
    
    // Set the result
    output.setResult({ 
      data: response.data,
      timestamp: Date.now()
    });

    // Add a transaction if needed
    output.addTransaction({
      to: '0x123...',
      data: '0x456...',
      value: '0'
    });

    // Return the built output
    return output.buildOutput();
  } catch (error) {
    output.setError(`Function failed: ${error.message}`);
    return output.buildOutput();
  }
};
```

<Card title="Need Additional Modules?" icon="puzzle-piece">
  Contact Snag Solutions if you need access to additional npm modules for your Stratus functions.
</Card>

## Related pages

<CardGroup cols={2}>
  <Card title="Function Syntax" icon="code" href="/stratus/syntax">
    Reference guide for exports, parameters, and module imports.
  </Card>

  <Card title="Function Templates" icon="copy" href="/stratus/function-templates">
    Pre-built templates for airdrops, token gating, and rewards.
  </Card>

  <Card title="Subscriptions" icon="bell" href="/stratus/subscriptions">
    Trigger functions automatically from onchain events.
  </Card>

  <Card title="Loyalty Overview" icon="stars" href="/loyalty/loyalty-overview">
    Configure the loyalty program that functions can interact with.
  </Card>
</CardGroup>
