# Redlynr x402 Paid Workflow for n8n

Call the [Redlynr](https://redlynr.com) agent guardrail API from n8n using x402 per-call USDC payments on Base mainnet. No subscriptions, no accounts — pay $0.001 per call directly from your wallet.

---

## n8n Cloud Compatibility

**This workflow does not run on n8n Cloud.** n8n Cloud does not allow external npm modules in Code nodes, and this workflow requires `ethers` for EIP-712 payment signing. Self-hosted n8n is required.

---

## Prerequisites

- Self-hosted n8n running via Docker
- An Ethereum wallet with USDC on Base mainnet (minimum a few cents to start)
- Your wallet's private key

> **There is no Redlynr API key.** Redlynr uses x402 — a pay-per-call protocol where payment is made directly from your Ethereum wallet via USDC on Base mainnet. The `PRIVATE_KEY` field in this workflow holds **your own wallet's private key**, which signs each $0.001 USDC payment. Redlynr never issues or manages keys on your behalf.

---

## Security Note on the Private Key

After importing this workflow, you will paste your private key directly into the **Customer Configuration** node. This is standard practice for n8n self-hosted workflows — n8n stores all workflow data encrypted in its database. The workflow JSON you received contains only a placeholder (`0x_your_private_key_here`), not a real key.

**Never share or export this workflow after filling in your private key.** Treat it the same as any other file containing a wallet key.

---

## Installation

### 1. Add the ethers package to your n8n container

Run these two commands after every container restart, or bake them into a startup script:

```bash
# Install ethers globally
docker exec -u root <your-n8n-container> npm install -g ethers

# Copy ethers into the task runner's module path
RUNNER_PATH=$(docker exec <your-n8n-container> sh -c "ls /usr/local/lib/node_modules/n8n/node_modules/.pnpm/ | grep '@n8n+task-runner'")
docker exec -u root <your-n8n-container> sh -c \
  "cp -r /usr/local/lib/node_modules/ethers \
   /usr/local/lib/node_modules/n8n/node_modules/.pnpm/${RUNNER_PATH}/node_modules/@n8n/task-runner/node_modules/ethers"
```

Replace `<your-n8n-container>` with your container name (e.g. `n8n-data-n8n-1`).

### 2. Update your docker-compose.yml

Add these environment variables to your n8n service:

```yaml
services:
  n8n:
    environment:
      # ... your existing env vars ...
      - NODE_FUNCTION_ALLOW_BUILTIN=crypto
      - NODE_FUNCTION_ALLOW_EXTERNAL=ethers
      - N8N_RUNNERS_ENABLED=true
      - N8N_RUNNERS_MODE=internal
      - N8N_RUNNERS_STDLIB_ALLOW=crypto
      - N8N_RUNNERS_EXTERNAL_ALLOW=ethers
```

### 3. Restart n8n and reinstall ethers

```bash
docker-compose down && docker-compose up -d
# Then re-run the two install commands from Step 1
```

### 4. Import the workflow

In n8n: **Workflows → Import from file** → select `redlynr_x402_paid_workflow.json`.

### 5. Set your private key

Open the **Customer Configuration** node and replace `0x_your_private_key_here` with your wallet's private key.

---

## Wallet Setup

Your wallet needs USDC on Base mainnet. Each Redlynr call costs $0.001 USDC. To fund the wallet:

1. Bridge USDC to Base mainnet via [Coinbase](https://coinbase.com), [Bridge](https://bridge.xyz), or any Base-compatible bridge
2. Verify your balance at `https://basescan.org/token/0x833589fcd6edb6e08f4c7c32d4f71b54bda02913?a=<your-wallet-address>`

Your tenant namespace is derived automatically from your wallet address (`n8n-` + first 10 characters, lowercased). Registration is free and happens automatically on first run.

---

## Configuration Fields

All configuration is in the **Customer Configuration** node. Open it and edit these values:

| Field | Required | Description |
|---|---|---|
| `PRIVATE_KEY` | Yes | Your Ethereum wallet private key. Signs the $0.001 USDC payment per call. Must correspond to a wallet holding USDC on Base mainnet. |
| `AGENT_ID` | Yes | Identifier for this agent. Used for pause/retry tracking. Change if running multiple distinct agents. Default: `"n8n_agent"` |
| `CHAIN_ID` | Yes | Identifier for this agent task or session. **Change this between separate tasks** so Redlynr tracks each independently. Default: `"n8n_chain_001"` |
| `CHAIN_TYPE` | Yes | Type of agent chain. Must be `"interactive"`, `"batch"`, or `"scheduled"`. Always set this explicitly — auto-detection often misclassifies n8n workflows as batch, which raises step limits to 100 and suppresses expected slow_down/stop signals. |
| `DEPTH` | Yes | Nesting level. `0` = top-level orchestrator, `1` = first-generation sub-agent. Default: `0` |
| `STEP_COST` | Yes | Estimated cost of this agent step in USD. Used for cost budget tracking. Default: `0.001` |
| `IS_RETRY` | Yes | Set `true` if this call is retrying a previously failed step. Redlynr tracks retry budget against this. Default: `false` |
| `IS_NOVEL_TARGET` | Optional | Set `false` if this tool call uses identical arguments to a recent call (the agent is repeating itself). `true` = genuinely new inputs. Wire your own tracking logic here if available. Default: `true` |
| `TOOL_FIXATION_SIGNAL` | Optional | Integer: how many of the last N calls used the same tool. `0` = no fixation detected. Wire your own tracking logic here if available. Default: `0` |

---

## Production Triggers

The **Manual Trigger** node is for testing only. In production, replace it with the trigger that fits your agent architecture:

**Webhook** — your orchestrator calls this workflow via HTTP each time it needs a guardrail check. Use an n8n Webhook node as the entry point and have your orchestrator POST the agent context to it. Wire the Webhook output directly into Customer Configuration.

**AI Agent node** — if you are building your agent inside n8n using the AI Agent node, insert this workflow as a sub-workflow called via the Execute Workflow node. The AI Agent fires it before each tool call and acts on the decision returned.

**Execute Workflow (called from a parent workflow)** — use the Execute Workflow node in your parent n8n workflow to call this one as a sub-workflow. Pass `CHAIN_ID`, `IS_RETRY`, and other per-call fields as input parameters so each call reflects the current agent state.

**Schedule Trigger** — for scheduled batch pipelines, replace Manual Trigger with a Schedule Trigger. Set `CHAIN_TYPE` to `"scheduled"` in Customer Configuration.

In all cases, the Customer Configuration node should be updated to derive `CHAIN_ID`, `IS_RETRY`, `IS_NOVEL_TARGET`, and `TOOL_FIXATION_SIGNAL` dynamically from your agent's runtime state rather than using the hardcoded defaults.

---

## Decision Routing

The **Route on Decision** node routes to one of three handlers based on Redlynr's response:

**PROCEED — Continue Agent**: Redlynr confirmed this step is within policy. Wire your agent's next action after this node. The output includes the full `checks` object with step count, cost spent, chain depth, and volume metrics.

**SLOW_DOWN — Wait and Retry**: The agent is approaching a limit. The node waits `wait_seconds` (from the response) then passes through. Wire back to **Call Redlynr** if you want to continue, or treat this as a signal to wrap up the current chain. The `reason` field indicates which limit is being approached: `step_cap_warning`, `cost_budget_warning`, or `volume_pressure`.

**STOP — Halt Agent**: A hard limit has been hit. The agent chain must halt. The `reason` field indicates which limit was exceeded: `step_cap_exceeded`, `cost_budget_exceeded`, `chain_depth_exceeded`, `retries_exhausted`, `volume_pressure_blocked`, or `agent_paused`.

---

## Policy Defaults

Redlynr applies these defaults until you configure a custom policy via `POST /policy`:

| Chain Type | Step Limit | Warn At | Cost Limit |
|---|---|---|---|
| interactive | 20 steps | 75% (step 15) | $50 tenant / $0.30 chain |
| batch | 100 steps | 75% (step 75) | $50 tenant / $0.30 chain |
| scheduled | 50 steps | 75% (step 37) | $50 tenant / $0.30 chain |

To set a custom policy, call `POST https://redlynr.com/policy` with your `tenant_id` and `owner_token`. Your `owner_token` is returned once on first registration — check your n8n execution logs for the first run to retrieve it.

---

## Troubleshooting

**`PRIVATE_KEY not set`**: Open the Customer Configuration node and replace the `0x_your_private_key_here` placeholder with your actual wallet private key.

**`Module 'ethers' is disallowed`**: The `NODE_FUNCTION_ALLOW_EXTERNAL=ethers` env var is missing from docker-compose, or the `N8N_RUNNERS_EXTERNAL_ALLOW=ethers` var is missing. Check both are present and restart n8n.

**`Cannot find module 'ethers'`**: The npm install + copy step from Step 1 needs to be re-run. This is required after every container restart since the task runner's node_modules directory is ephemeral.

**`Payment rejected (402)`**: Your wallet has insufficient USDC on Base mainnet, or the private key in `PRIVATE_KEY` does not correspond to a funded wallet.

**Always getting `proceed` even after many calls**: Check that `CHAIN_TYPE` is set to `"interactive"` and that you are using the same `CHAIN_ID` across runs. If `CHAIN_TYPE` is blank, Redlynr may auto-detect the chain as `"batch"` and apply a 100-step limit.
