# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.netauthpay.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Overview

### Introduction

NetAuth is a secure, privacy-first payment infrastructure for autonomous agents on the Solana blockchain. It enables agents to own wallets and send payments to one another using the **x402 protocol**, with all privacy management handled transparently in the backend.

#### Why NetAuth?

* **Agent-first**: Built for autonomous agent-to-agent payments, not just human users.
* **Privacy by design**: Payment details are protected through the x402 protocol and backend privacy layer.
* **Solana-native**: Fast, low-cost transactions on Solana.
* **Simple integration**: REST API and CLI; agents register once and pay via API or CLI.

#### Key Features

| Feature                     | Description                                                                               |
| --------------------------- | ----------------------------------------------------------------------------------------- |
| **Agent wallet management** | Each agent gets a dedicated Solana wallet; keys are encrypted and managed by the backend. |
| **Private payments**        | Send SOL between agents with privacy tokens; only involved parties see payment details.   |
| **Batch payments**          | Send multiple payments in one request from one agent to many recipients.                  |
| **Payment metadata**        | Attach optional key-value metadata (e.g. `invoiceId`, `taskId`) to payments.              |
| **Paginated history**       | Query payment history with `limit`, `offset`, and optional `status` filter.               |

#### Who Is This For?

* **Agent developers** integrating payments into autonomous agents.
* **Platforms** that need private, agent-to-agent payment rails on Solana.
* **Teams** building multi-agent systems that require wallets and payments.

***


# Get Started

#### Prerequisites

* **Node.js** 18 or higher
* **npm** or **yarn**
* (Optional) **Solana CLI** for local dev and key management

#### Installation

**Option A: Global install (recommended for CLI use)**

```bash
npm install -g @eternallabs/netauth
```

Then run the CLI from anywhere:

```bash
netauth --help
netauth agent register my-agent
```

**Option B: Local / project install**

```bash
git clone https://github.com/eternal-labs/net-auth.git
cd net-auth
npm install
```

Use the CLI via npm script:

```bash
npm run netauth -- --help
```

#### Configuration

1. Copy the example environment file:

   ```bash
   cp .env.example .env
   ```
2. Edit `.env` with your values:

   | Variable         | Description                                                      | Required                              |
   | ---------------- | ---------------------------------------------------------------- | ------------------------------------- |
   | `SOLANA_RPC_URL` | Solana RPC endpoint (e.g. `https://api.mainnet-beta.solana.com`) | Yes (for live)                        |
   | `NETWORK`        | `mainnet-beta`, `devnet`, or `testnet`                           | No (default: mainnet-beta)            |
   | `ENCRYPTION_KEY` | Secret used to encrypt wallet private keys                       | **Yes** (for wallet creation)         |
   | `PORT`           | HTTP port for the API server                                     | No (default: 3000)                    |
   | `X402_ENDPOINT`  | x402 protocol endpoint                                           | No (optional; fallback used if unset) |
   | `X402_API_KEY`   | API key for x402 service                                         | No (if using x402 endpoint)           |
3. **Important**: Without `ENCRYPTION_KEY`, the server will not start (wallet creation requires it). The CLI can still show help without it.

#### Running the Server

**Development (with watch):**

```bash
npm run dev
```

**Production:**

```bash
npm run build
npm start
```

The API is available at `http://localhost:3000` (or your configured `PORT`). Health check:

```bash
curl http://localhost:3000/health
```

#### Quick Start Flow

1. Start the server (with `ENCRYPTION_KEY` set).
2. Register two agents:

   ```bash
   netauth agent register alice
   netauth agent register bob
   ```
3. Check balance:

   ```bash
   netauth agent balance alice --sol
   ```
4. Send a payment:

   ```bash
   netauth payment send alice bob 0.1 --sol --memo "First payment"
   ```
5. View history:

   ```bash
   netauth payment history alice
   ```

***


# Architecture

#### High-Level Flow

```
┌─────────────┐
│   Agents    │  (CLI, API clients, other services)
└──────┬──────┘
       │
       ▼
┌─────────────────┐
│  NetAuth API    │  (Express REST + optional CLI)
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  Privacy Layer  │  (Payment records, visibility rules)
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  x402 Protocol  │  (Privacy tokens, optional external service)
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  Solana Network │  (Transactions, balances)
└─────────────────┘
```

#### Core Components

**1. Agent Service**

* Registers agents and maintains agent records.
* One agent ID per logical agent; optional existing Solana public key on registration.

**2. Wallet Service**

* Creates a Solana keypair per agent (or links an existing key).
* Encrypts private keys at rest, provides balance lookups and key material for signing (server-side only).

**3. Privacy Service**

* Creates and stores payment records.
* Assigns privacy tokens (via x402 when configured).
* Ensures only sender and recipient can see a payment’s details.
* Coordinates single and batch payment creation and processing.

**4. x402 Service**

* Integrates with the x402 protocol for privacy tokens.
* If no x402 endpoint is configured, uses a local fallback for token generation so the product still works.

**5. Payment Service**

* Builds and signs Solana transfer transactions.
* Submits transactions to the configured RPC and tracks confirmation.

**6. Encryption Service**

* Encrypts/decrypts sensitive data (e.g. wallet private keys) using AES-256-GCM.
* Required for any wallet creation or payment sending.

#### Payment Flow (Single Payment)

1. Client calls `POST /api/payments/send` (or CLI `payment send`).
2. Privacy Service creates a payment record with status `PENDING`.
3. x402 Service (or local fallback) issues a privacy token for the payment.
4. Payment Service builds a Solana transfer, signs with the sender’s key, and sends the transaction.
5. On confirmation, payment status is set to `COMPLETED` and the transaction signature is stored.
6. Only the sender and recipient can query this payment’s details (enforced by Privacy Service).

#### Data Storage

* Current implementation uses **in-memory** storage (Maps).
* For production, plan to replace with:
  * A database (e.g. PostgreSQL) for agents and payments.
  * An encrypted store for wallet data.
  * Optional cache (e.g. Redis) for sessions or rate limiting.

***


# API Reference

Base URL: `http://localhost:3000` (or your deployed URL).\
All request/response bodies are JSON. Standard HTTP status codes apply.

***

#### Agents

**Register an agent**

**`POST /api/agents/register`**

Creates a new agent and a Solana wallet (or links an existing public key if provided).

**Request body:**

```json
{
  "agentId": "string (required)",
  "publicKey": "string (optional, existing Solana public key)"
}
```

**Response:** `201 Created`

```json
{
  "id": "agent-id",
  "publicKey": "Base58SolanaPublicKey...",
  "createdAt": "ISO8601",
  "updatedAt": "ISO8601",
  "isActive": true
}
```

**Errors:** `400` if `agentId` missing; `500` if registration fails (e.g. duplicate agent).

***


# GET

**Get agent**

**`GET /api/agents/:agentId`**

Returns the agent record.

**Response:** `200 OK` — agent object; `404` if not found.

***

**Get agent balance**

**`GET /api/agents/:agentId/balance`**

Returns the agent’s wallet balance (lamports and SOL).

**Response:** `200 OK`

```json
{
  "agentId": "string",
  "balance": 1000000000,
  "solBalance": 1.0
}
```

**Errors:** `404` if agent not found; `500` on RPC or internal error.

***

**List agents**

**`GET /api/agents`**

Returns all registered agents.

**Response:** `200 OK` — array of agent objects.

***


# POST

**Send a single payment**

**`POST /api/payments/send`**

Creates one private payment from one agent to another and processes it asynchronously.

**Request body:**

```json
{
  "fromAgentId": "string (required)",
  "toAgentId": "string (required)",
  "amount": 100000000,
  "memo": "optional string",
  "metadata": { "invoiceId": "inv-1", "taskId": "task-2" }
}
```

* `amount`: integer, in **lamports** (1 SOL = 1\_000\_000\_000 lamports).
* `metadata`: optional key-value map (e.g. for invoice or task tracking).

**Response:** `202 Accepted`

```json
{
  "paymentId": "pay_...",
  "status": "pending",
  "message": "Payment initiated"
}
```

**Errors:**

* `400` — missing/invalid fields, zero/negative amount, or sender equals recipient.
* `500` — wallet or internal error.

***

#### Batch Payments

**Send multiple payments**

**`POST /api/payments/send-batch`**

Creates multiple payments from one agent to many recipients in one request. Each payment is processed asynchronously.

**Request body:**

```json
{
  "fromAgentId": "sender-agent-id",
  "payments": [
    { "toAgentId": "agent-b", "amount": 100000000, "memo": "Payment 1", "metadata": {} },
    { "toAgentId": "agent-c", "amount": 50000000 }
  ]
}
```

* `payments`: array of objects; each must have `toAgentId` and `amount` (lamports).
* `memo` and `metadata` are optional per item.
* Duplicate `toAgentId` in the same request is not allowed.

**Response:** `202 Accepted`

```json
{
  "paymentIds": ["pay_...", "pay_..."],
  "status": "accepted",
  "message": "2 payment(s) initiated"
}
```

**Errors:**

* `400` — missing/invalid fields, zero/negative amount, self-payment, or duplicate recipient.
* `500` — internal error.

***


# Payment History

**Get payment by ID**

**`GET /api/payments/:paymentId?agentId=:agentId`**

Returns a single payment. For privacy, only the sender or recipient can see it; pass `agentId` as the requesting agent.

**Response:** `200 OK` — payment object; `404` if not found or not allowed.

***

**Get payments for an agent**

**`GET /api/payments/agent/:agentId`**

Returns all payments where the agent is sender or recipient.

**Query parameters (all optional):**

| Parameter | Type   | Description                                                    |
| --------- | ------ | -------------------------------------------------------------- |
| `limit`   | number | Max number of payments to return (capped by server, e.g. 100). |
| `offset`  | number | Number of payments to skip (for pagination).                   |
| `status`  | string | Filter by `pending`, `processing`, `completed`, or `failed`.   |

* **Without** `limit`/`offset`/`status`: response is a **JSON array** of payments.
* **With** any of these: response is a **paginated object**:

```json
{
  "payments": [ ... ],
  "total": 42,
  "limit": 20,
  "offset": 0
}
```

**Response:** `200 OK`; `500` on error.

***

#### Payment Object Shape

Payments in responses use this structure:

```json
{
  "id": "pay_...",
  "fromAgentId": "string",
  "toAgentId": "string",
  "amount": 100000000,
  "transactionSignature": "SolanaTxSignature or null",
  "status": "pending | processing | completed | failed",
  "memo": "string or null",
  "metadata": { "key": "value" } or null,
  "createdAt": "ISO8601",
  "completedAt": "ISO8601 or null",
  "privacyToken": "internal use"
}
```

***


# CLI

Install globally: `npm install -g @eternallabs/netauth`.\
Then run `netauth <command> [options]`.

#### Global options

* `netauth --help` — list commands and options.
* `netauth agent --help`, `netauth payment --help`, `netauth wallet --help` — command-specific help.

***

#### Agent commands

| Command                                                | Description                                          |
| ------------------------------------------------------ | ---------------------------------------------------- |
| `netauth agent register <agentId> [--key <publicKey>]` | Register a new agent (optional existing Solana key). |
| `netauth agent info <agentId>`                         | Show agent details.                                  |
| `netauth agent balance <agentId> [--sol]`              | Show balance (lamports or SOL with `--sol`).         |
| `netauth agent list`                                   | List all agents.                                     |

***

#### Payment commands

| Command                                                             | Description                                                                   |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `netauth payment send <from> <to> <amount> [--sol] [--memo <memo>]` | Send one payment (amount in lamports unless `--sol`).                         |
| `netauth payment send-batch <from> '<json>' [--sol]`                | Send multiple payments; `json` is an array of `{ toAgentId, amount, memo? }`. |
| `netauth payment status <paymentId> [--agent <agentId>]`            | Get payment status (optional agent for privacy).                              |
| `netauth payment history <agentId> [--limit <n>]`                   | List payments for the agent.                                                  |

**Batch JSON example:**

```bash
netauth payment send-batch alice '[{"toAgentId":"bob","amount":0.1},{"toAgentId":"charlie","amount":0.05}]' --sol
```

***


# Agent Usage

This section is for developers building autonomous agents that use NetAuth.

#### Capabilities

* **Register** once per agent to get a wallet.
* **Check balance** before sending.
* **Send** single or batch payments with optional memo and metadata.
* **Query** payment status and history (only for payments you’re involved in).

#### Base URL

Use your NetAuth server URL, e.g. `http://localhost:3000` or `https://netauth.yourdomain.com`.

#### Minimal integration example (TypeScript)

```typescript
const BASE = 'http://localhost:3000';

async function registerAgent(agentId: string) {
  const res = await fetch(`${BASE}/api/agents/register`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ agentId }),
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

async function getBalance(agentId: string) {
  const res = await fetch(`${BASE}/api/agents/${agentId}/balance`);
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

async function sendPayment(
  from: string,
  to: string,
  amountLamports: number,
  memo?: string,
  metadata?: Record<string, string>
) {
  const res = await fetch(`${BASE}/api/payments/send`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ fromAgentId: from, toAgentId: to, amount: amountLamports, memo, metadata }),
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

async function sendBatch(
  from: string,
  payments: Array<{ toAgentId: string; amount: number; memo?: string; metadata?: Record<string, string> }>
) {
  const res = await fetch(`${BASE}/api/payments/send-batch`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ fromAgentId: from, payments }),
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

async function getPaymentHistory(agentId: string, limit?: number, offset?: number, status?: string) {
  const params = new URLSearchParams();
  if (limit != null) params.set('limit', String(limit));
  if (offset != null) params.set('offset', String(offset));
  if (status) params.set('status', status);
  const url = `${BASE}/api/payments/agent/${agentId}${params.toString() ? '?' + params : ''}`;
  const res = await fetch(url);
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}
```

#### Best practices

* **Register once** and store `agentId` and `publicKey`.
* **Check balance** before sending; handle insufficient balance errors.
* **Treat payments as async**: after `POST /send` or `POST /send-batch`, poll `GET /api/payments/:paymentId?agentId=...` or use history to confirm completion.
* **Store payment IDs** when you send so you can check status later.
* **Use metadata** for your own IDs (invoices, tasks) so you can reconcile payments in your system.
* **Handle errors** and non-2xx responses; respect rate limits in production.

***


# Privacy and Security

#### Privacy guarantees

* **Visibility**: Only the sender and recipient of a payment can retrieve its details via the API.
* **Privacy tokens**: Each payment is associated with a privacy token (x402 or local); tokens are used internally to preserve privacy.
* **Backend-only signing**: Private keys never leave the server; agents only see public keys and balances.

#### Security measures

* **Encryption at rest**: Wallet private keys are encrypted with AES-256-GCM using `ENCRYPTION_KEY`.
* **No key exposure**: Agents do not receive or handle private keys.
* **Validation**: All payment and batch requests are validated (amounts, no self-payment, no duplicate recipients in batch).
* **HTTPS**: Use TLS in production for the NetAuth API.
* **Secrets**: Keep `ENCRYPTION_KEY` and any x402 keys in environment variables or a secrets manager; never commit them.

#### Recommendations

* Use a strong, unique `ENCRYPTION_KEY` in production.
* Run NetAuth in a private network where only your agents/systems can call it, or protect the API with auth (e.g. API keys or auth proxy).
* Consider rate limiting and monitoring for production.
* Plan for key rotation and backup of encrypted wallet data if you persist it.

***


# Usecases

#### Use case 1: Task payment (one agent pays another)

1. Register both agents.
2. Sender checks balance.
3. Send payment with memo `"Task completion reward"` and metadata `{ "taskId": "task-123" }`.
4. Recipient (or sender) checks payment status and history to confirm.

#### Use case 2: Batch payouts (one agent pays many)

1. Sender agent has a list of recipients and amounts.
2. Call `POST /api/payments/send-batch` with `fromAgentId` and `payments: [{ toAgentId, amount }, ...]`.
3. Use returned `paymentIds` to poll status or check history with pagination.

#### Use case 3: Reconciliation with your system

* Attach `metadata` (e.g. `invoiceId`, `orderId`) on send.
* Query payment history (with optional `limit`/`offset`/`status`) and match payments to your records using `metadata` and `amount`.

#### Use case 4: CLI-only workflow

```bash
netauth agent register worker-1
netauth agent register worker-2
netauth agent balance worker-1 --sol
netauth payment send worker-1 worker-2 0.5 --sol --memo "Payout"
netauth payment history worker-1 --limit 10
```

***


# Troubleshooting

#### "ENCRYPTION\_KEY must be set"

* Set `ENCRYPTION_KEY` in your environment or `.env`.
* Required for any flow that creates wallets or sends payments.
* The CLI can still show `--help` without it (services load lazily).

#### "Wallet not found" / "Agent not found"

* Ensure the agent was registered first (`POST /api/agents/register` or `netauth agent register <id>`).
* If the server restarts and you use in-memory storage, all agents and wallets are lost; re-register or move to persistent storage.

#### "Insufficient balance"

* The sender’s Solana wallet does not have enough lamports.
* Fund the wallet (e.g. via airdrop on devnet or a transfer from another wallet) or reduce the payment amount.

#### Payment stuck in "pending" or "processing"

* Payments are processed asynchronously. Wait a few seconds and check again.
* If the server crashed or the Solana RPC failed, the payment may stay in `processing` or fail; check server logs and RPC health.
* Query `GET /api/payments/:paymentId?agentId=...` to see current status and transaction signature (if completed).

#### x402 warnings in logs

* If `X402_ENDPOINT` or `X402_API_KEY` is not set, the system uses a local privacy-token fallback.
* Payments still work; only external x402 features are disabled. Configure x402 when you need the full protocol.

#### CLI returns 404 or connection refused

* Ensure the NetAuth server is running and reachable.
* If using the CLI against a remote server, set the base URL in your client (e.g. via a wrapper or env) or use the API directly with the correct base URL.

#### Pagination: wrong total or missing payments

* With in-memory storage, data is lost on restart.
* `total` reflects the current in-memory count; if you use filters (`status`), `total` is the count of matching payments before pagination.

***


# Summary

### Summary

NetAuth provides a **privacy-first payment layer** for autonomous agents on Solana: agent registration, wallet management, single and batch payments, optional metadata, and paginated history. Use the **REST API** or **CLI** to integrate; agents never see private keys, and only sender and recipient can see payment details. Configure `ENCRYPTION_KEY` and (optionally) x402 for production, and run the server behind HTTPS and access control for security.

For more, see the [GitHub repository](https://github.com/eternal-labs/net-auth) and the [skills.md](https://github.com/eternal-labs/net-auth/blob/main/skills.md) agent integration guide.


# License

MIT

***

**Built with ❤️ by the netAuth community**


