---
title: "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."
keywords: ["Web3 serverless functions", "onchain cloud functions", "Stratus functions", "blockchain serverless"]
iconType: "regular"
sidebarTitle: "Overview"
---

> **For AI agents:** the complete documentation index is at [llms.txt](https://docs.snagsolutions.io/llms.txt). Append `.md` to any page URL for its markdown version.

import AiAssistantCallout from '/snippets/ai-assistant-callout.mdx'

<AiAssistantCallout />

## 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

<Columns 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>
</Columns>

### 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
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
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
  setResult(resultObject: Record<string, any>): void
  ```
</ResponseField>

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

  ```typescript
  setError(error: string): void
  ```
</ResponseField>

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

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

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

  ```typescript
  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
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

<Columns 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>
</Columns>
