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

# PayAI

> Integrate PayAI facilitator for x402 payment processing

PayAI is a hosted facilitator service that simplifies x402 payment processing. Instead of running your own facilitator infrastructure, you can use PayAI's endpoints to handle payment verification and settlement.

## Prerequisites

* Node.js and npm installed
* A SKALE Chain endpoint
* Basic understanding of x402 protocol

## Configuration

### Environment Variables

Create a `.env` file with PayAI configuration:

```bash theme={null}
# Facilitator Router Address
RECEIVING_ADDRESS=0xFacilitatorReceivingAddress

# Payment token configuration
PAYMENT_TOKEN_ADDRESS=0x2e08028E3C4c2356572E096d8EF835cD5C6030bD
PAYMENT_TOKEN_NAME="Bridged USDC (SKALE Bridge)"

# SKALE network configuration
NETWORK_CHAIN_ID=324705682
```

## Integration with PayAI

<Tabs>
  <Tab title="Server Setup">
    ```typescript theme={null}
    import { Hono } from "hono";
    import { serve } from "@hono/node-server";
    import { paymentMiddleware, x402ResourceServer } from "@x402/hono";
    import { ExactEvmScheme } from "@x402/evm/exact/server";
    import { HTTPFacilitatorClient } from "@x402/core/server";
    import type { Network } from "@x402/core/types";
    import "dotenv/config";

    const app = new Hono();

    async function main() {
      // Point to PayAI facilitator
      const facilitatorUrl = "https://facilitator.payai.network";
      const receivingAddress = process.env.RECEIVING_ADDRESS as `0x${string}`;
      const paymentTokenAddress = process.env.PAYMENT_TOKEN_ADDRESS as `0x${string}`;
      const paymentTokenName = process.env.PAYMENT_TOKEN_NAME ;
      const networkChainId = process.env.NETWORK_CHAIN_ID;
      const network: Network = `eip155:${networkChainId}`;

      // Initialize PayAI facilitator client
      const facilitatorClient = new HTTPFacilitatorClient({ 
        url: facilitatorUrl 
      });
      
      const resourceServer = new x402ResourceServer(facilitatorClient);
      resourceServer.register("eip155:*", new ExactEvmScheme());

      // Apply payment middleware
      app.use(
        paymentMiddleware(
          {
            "GET /api/data": {
              accepts: [
                {
                  scheme: "exact",
                  network: network,
                  payTo: receivingAddress,
                  price: {
                    amount: "10000", // 0.01 tokens
                    asset: paymentTokenAddress,
                    extra: {
                      name: paymentTokenName,
                      version: "1",
                    },
                  },
                },
              ],
              description: "Premium data access",
              mimeType: "application/json",
            },
          },
          resourceServer
        )
      );

      // Protected endpoint
      app.get("/api/data", (c) => {
        return c.json({
          message: "Premium data unlocked via PayAI!",
          timestamp: new Date().toISOString(),
        });
      });

      const port = 3000;
      serve({ fetch: app.fetch, port }, () => {
        console.log(`Server running on http://localhost:${port}`);
        console.log(`Using PayAI facilitator: ${facilitatorUrl}`);
      });
    }

    main().catch(console.error);
    ```
  </Tab>

  <Tab title="Client Setup">
    ```typescript theme={null}
    import { x402Client, x402HTTPClient } from "@x402/core/client";
    import { ExactEvmScheme } from "@x402/evm";
    import { privateKeyToAccount } from "viem/accounts";
    import "dotenv/config";

    async function main() {
      // Setup wallet
      const account = privateKeyToAccount(
        process.env.PRIVATE_KEY as `0x${string}`
      );

      // Create x402 client
      const evmScheme = new ExactEvmScheme(account);
      const coreClient = new x402Client().register("eip155:*", evmScheme);
      const httpClient = new x402HTTPClient(coreClient);

      // Access PayAI-protected resource
      const url = "http://localhost:3000/api/data";
      const response = await fetch(url);

      if (response.status === 402) {
        console.log("Payment required, processing via PayAI...");

        const responseBody = await response.json();
        const paymentRequired = httpClient.getPaymentRequiredResponse(
          (name: string) => response.headers.get(name),
          responseBody
        );

        const paymentPayload = await httpClient.createPaymentPayload(
          paymentRequired
        );
        
        const paymentHeaders = httpClient.encodePaymentSignatureHeader(
          paymentPayload
        );

        const paidResponse = await fetch(url, {
          headers: { ...paymentHeaders },
        });

        const data = await paidResponse.json();
        console.log("Data received:", data);
      }
    }

    main();
    ```
  </Tab>
</Tabs>

## Troubleshooting

### Connection Issues

If you cannot connect to PayAI:

1. Verify the facilitator URL is correct
2. Check network connectivity
3. Ensure API credentials are valid
4. Review firewall settings

### Payment Failures

Common causes and solutions:

| Issue                 | Solution                                |
| --------------------- | --------------------------------------- |
| Invalid signature     | Verify wallet configuration and signing |
| Insufficient balance  | Ensure payer has enough tokens          |
| Network mismatch      | Check chain ID matches configuration    |
| Expired authorization | Increase `maxTimeoutSeconds`            |

## Resources

* [PayAI Documentation](https://docs.payai.network/x402/supported-networks)
* [x402 Protocol Specification](https://x402.org)

***

<Note>
  This entity -- PayAI -- is deployed and activley supporting SKALE. These are 3rd party services that may have their own terms and conditions and privacy polices. Use these services at your own risk. AI and agents is a highly experimental space; the 3rd party software solutions may have bugs or be unaudited. You and your agents and your customers use all 3rd party services chosen at your own risk and per their terms.
</Note>
