npm package: @genesis-tech/x402-hydra-gateway
Description: x402 Hydra Gateway - HTTP client service for routing payment verification and settlement requests to facilitator nodes in the x402 payment protocol
Latest version: 0.1.1

# @genesis-tech/x402-hydra-gateway

HTTP client service for routing payment verification and settlement requests to facilitator nodes in the x402 Hydra payment protocol.

**Version:** 0.1.0  
**License:** Apache-2.0  
**Repository:** [Hydraprotocol402/Hydra-Facilitator](https://github.com/Hydraprotocol402/Hydra-Facilitator)

## Overview

The gateway package provides lightweight HTTP client utilities for forwarding payment verification and settlement requests to facilitator nodes. Gateway nodes act as routing layers that distribute payment requests across multiple facilitator nodes, enabling load balancing, caching, and high availability.

### Core Responsibilities

1. **Route requests**: Forward payment verification and settlement requests to facilitator nodes
2. **Load balance**: Distribute requests across multiple facilitator nodes
3. **Provide abstraction**: Simplify integration for resource servers
4. **Handle errors**: Manage retries and error responses from facilitator nodes

## Features

- ✅ **Lightweight HTTP client**: Simple API for forwarding payment requests
- ✅ **Type-safe**: Full TypeScript support with comprehensive type definitions
- ✅ **Error handling**: Built-in error handling and retry logic
- ✅ **Configurable**: Support for custom facilitator URLs and X402 configuration
- ✅ **Zero dependencies**: Minimal dependencies, uses native fetch API
- ✅ **Gateway discovery**: Query supported payment kinds from facilitator nodes

## Installation

```bash
# Using npm
npm install @genesis-tech/x402-hydra-gateway

# Using pnpm
pnpm add @genesis-tech/x402-hydra-gateway

# Using yarn
yarn add @genesis-tech/x402-hydra-gateway
```

### Install Latest from Main Branch

```bash
npm install @genesis-tech/x402-hydra-gateway@next
```

## Quick Start

### Basic Usage

```typescript
import {
  forwardPayment,
  getSupportedPaymentKinds,
  GatewayConfig,
} from "@genesis-tech/x402-hydra-gateway";
import type {
  PaymentPayload,
  PaymentRequirements,
} from "@genesis-tech/x402-hydra-facilitator/types";

// Configure gateway
const config: GatewayConfig = {
  facilitatorUrl: "http://localhost:3000",
};

// Payment requirements from the server
const requirements: PaymentRequirements = {
  scheme: "exact",
  network: "base-sepolia",
  amount: "1000000", // 1 USDC (6 decimals)
  asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
  recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
};

// Payment payload from the client (signed)
const payload: PaymentPayload = {
  // ... payment payload with signature
};

// Forward payment request to facilitator
const result = await forwardPayment(config, payload, requirements);

if (result.success) {
  console.log("Payment verified:", result.verificationResult);
  console.log("Payment settled:", result.settlementResult);
  console.log("Transaction:", result.settlementResult?.transaction);
} else {
  console.error("Payment failed:", result.error);
}
```

### Query Supported Payment Kinds

```typescript
import { getSupportedPaymentKinds } from "@genesis-tech/x402-hydra-gateway";

// Get supported payment kinds from facilitator
const supported = await getSupportedPaymentKinds("http://localhost:3000");
console.log("Supported payment kinds:", supported.kinds);
```

### Advanced Configuration

```typescript
import { GatewayConfig } from "@genesis-tech/x402-hydra-gateway";
import type { X402Config } from "@genesis-tech/x402-hydra-facilitator/types";

const config: GatewayConfig = {
  facilitatorUrl: "https://facilitator.example.com",
  x402Config: {
    evmConfig: {
      rpcUrl: "https://custom-rpc.example.com",
    },
    svmConfig: {
      rpcUrl: "https://custom-solana-rpc.example.com",
    },
  },
};
```

## API Reference

### `forwardPayment(config, payload, requirements)`

Forwards a payment request to a facilitator node for verification and settlement. This function handles both verification and settlement in a single call.

**Parameters:**
- `config: GatewayConfig` - Gateway configuration with facilitator URL
- `payload: PaymentPayload` - Signed payment payload from client
- `requirements: PaymentRequirements` - Payment requirements from server

**Returns:** `Promise<ForwardPaymentResponse>`

**Response Structure:**
```typescript
{
  success: boolean;
  verificationResult?: VerifyResponse;
  settlementResult?: SettleResponse;
  error?: string;
}
```

**Example:**
```typescript
const result = await forwardPayment(config, payload, requirements);

if (result.success) {
  // Payment was verified and settled
  console.log("Transaction:", result.settlementResult?.transaction);
  console.log("Payer:", result.settlementResult?.payer);
} else {
  // Payment failed
  console.error("Error:", result.error);
  
  // Check verification result if available
  if (result.verificationResult) {
    console.error("Verification failed:", result.verificationResult.invalidReason);
  }
}
```

### `getSupportedPaymentKinds(facilitatorUrl)`

Retrieves the list of supported payment kinds from a facilitator node. This is useful for discovering what payment schemes and networks a facilitator supports.

**Parameters:**
- `facilitatorUrl: string` - URL of the facilitator node

**Returns:** `Promise<{ kinds: SupportedPaymentKind[] }>`

**Example:**
```typescript
const supported = await getSupportedPaymentKinds("http://localhost:3000");
console.log("Supported payment kinds:", supported.kinds);

// Example output:
// {
//   kinds: [
//     {
//       scheme: "exact",
//       network: "base-sepolia",
//       asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
//       // ... other details
//     }
//   ]
// }
```

## Type Definitions

```typescript
import type {
  GatewayConfig,
  ForwardPaymentResponse,
} from "@genesis-tech/x402-hydra-gateway";

import type {
  PaymentPayload,
  PaymentRequirements,
  VerifyResponse,
  SettleResponse,
  X402Config,
} from "@genesis-tech/x402-hydra-facilitator/types";
```

## Architecture

The gateway acts as a lightweight HTTP client that:

1. **Receives payment requests** from resource servers
2. **Forwards verification requests** to facilitator nodes
3. **Forwards settlement requests** after successful verification
4. **Returns combined results** to resource servers

### Gateway Node Extensions

Gateway nodes can be extended to provide:

- **Load balancing**: Distribute requests across multiple facilitator nodes
- **Caching**: Cache verification results to reduce facilitator load
- **Rate limiting**: Implement rate limiting and request queuing
- **Aggregation**: Aggregate results from multiple facilitators
- **Monitoring**: Track facilitator health and performance
- **Failover**: Automatically switch to backup facilitators

### Integration Flow

```
Client → Resource Server → Gateway → Facilitator → Blockchain
                ↑                           ↓
                └──────── Response ─────────┘
```

1. Client makes HTTP request to resource server
2. Resource server responds with `402 Payment Required`
3. Client creates signed payment payload
4. Resource server forwards to gateway
5. Gateway forwards to facilitator for verification
6. Gateway forwards to facilitator for settlement
7. Gateway returns combined result to resource server
8. Resource server fulfills request

## Dependencies

- `@genesis-tech/x402-hydra-facilitator` - For type definitions (`PaymentPayload`, `PaymentRequirements`, `VerifyResponse`, `SettleResponse`, etc.)

## Examples

See the [examples directory](https://github.com/Hydraprotocol402/Hydra-Facilitator/tree/main/examples) for complete implementations:

- **Gateway NestJS Service**: Full NestJS gateway service implementation
- **Express Service**: Example resource server using the gateway

## Development

```bash
# Install dependencies
pnpm install

# Build the package
pnpm build

# Run tests
pnpm test

# Lint
pnpm lint

# Format code
pnpm format
```

## Related Packages

- [`@genesis-tech/x402-hydra-facilitator`](https://www.npmjs.com/package/@genesis-tech/x402-hydra-facilitator) - Payment verification and settlement service

## License

Apache-2.0

## Support

- **Issues**: [GitHub Issues](https://github.com/Hydraprotocol402/Hydra-Facilitator/issues)
- **Documentation**: [GitHub Repository](https://github.com/Hydraprotocol402/Hydra-Facilitator)