# PayCow Non-Custodial Crypto Payment Gateway
## Master AI Coding Agent Integration Blueprint & Architecture Prompt

---

> **INSTRUCTION FOR THE AI AGENT / ASSISTANT (Cursor, Windsurf, Claude Code, ChatGPT, Antigravity, GitHub Copilot, etc.):**
> You are acting as the Principal Web3 & Payment Integration Architect for this project. Your goal is to integrate PayCow's Non-Custodial crypto payment gateway cleanly, securely, and idiomatically into this repository.
>
> **Core Architecture Knowledge:**
> PayCow is a **Non-Custodial** payment infrastructure. PayCow monitors on-chain blockchain deposits and settles payments directly into user-configured merchant destination wallets. PayCow never holds merchant private keys or custody of funds. All API calls and checkouts are served strictly over HTTPS (`https://paycow.net`). PayCow supports multi-chain settlements in USDT across **Ethereum (ERC-20)** and **TRON (TRC-20)** networks.

---

## Phase 1: Mandatory Discovery Questionnaire (Ask the Developer First)

**CRITICAL DIRECTIVE FOR THE AI AGENT:** Before writing or altering any code in this repository, you MUST interview the developer by presenting the following discovery questions and waiting for their answers:

```text
[PayCow AI Setup Assistant]
To tailor the crypto payment integration for your exact project, please answer these brief questions:

1. Business Model & Payment Logic:
   [ ] Option A: Product / Order Checkout (User buys a one-off item/service, unlock order upon payment)
   [ ] Option B: User Balance / Credits Top-up (User deposits funds to increment internal account balance)
   [ ] Option C: SaaS Subscription / Recurring Tier (Unlock tier access for 30/365 days)

2. Target Settlement Networks & Currencies:
   [ ] Option A: TRC-20 only (USDT on TRON Network - Fast, low network gas fees)
   [ ] Option B: ERC-20 only (USDT on Ethereum Mainnet - Global EVM institutional standard)
   [ ] Option C: Multi-Chain (Allow user/buyer to choose between ERC-20 and TRC-20 at checkout)

3. Tech Stack & Environment:
   - Backend Framework: (e.g. Node.js/Express, Next.js App Router, Python/FastAPI/Django, PHP/Laravel, Go, Ruby on Rails)
   - Database / ORM: (e.g. PostgreSQL/Prisma, MongoDB/Mongoose, MySQL, SQLite, Supabase)
   - Frontend: (e.g. React, Vue, Svelte, Blade/EJS, Tailwind/Vanilla CSS, Mobile App)

4. Checkout Experience:
   [ ] Direct Redirect: Redirect user to PayCow's hosted checkout page (https://paycow.net/payment/:id)
   [ ] Modal / Embedded: Open hosted checkout inside an iframe or modal dialog

5. Payment Verification & Fulfillment Handling:
   - How should your system verify payment completion? (PayCow provides server-to-server status query via GET https://paycow.net/payment/data/:sessionId or GET /api/payment/status/:id)
   - Which database table/model tracks transaction records and user balances?
```

---

## Phase 2: Mandatory Security & Setup Checklist

Before writing code or going live, verify the following 4 rules with the developer:

1. **Environment Secrets (.env) Safety**:
   - Store `PAYCOW_API_KEY` and `PAYCOW_API_SECRET` strictly in backend `.env` variables.
   - Verify `.env` is included in `.gitignore`.
   - Never expose `PAYCOW_API_SECRET` or API keys in client-side bundles (e.g. React components, public frontend JS).

2. **Merchant Wallet Setup in PayCow Dashboard**:
   - Remind the developer to log into their PayCow Merchant Dashboard (`https://paycow.net/dashboard`) and configure destination wallets for their chosen network(s):
     - For **ERC-20 (Ethereum)**: Add a valid Ethereum destination address (`0x...`, 42 characters).
     - For **TRC-20 (TRON)**: Add a valid TRON destination address (`T...`, 34 characters).
   - Payments will route on-chain directly to these merchant destination addresses.

3. **Idempotency & Replay Protection**:
   - Always provide an `idempotencyKey` (e.g., unique order ID or UUID) when calling `POST /api/payment/create`.
   - Ensure local database payment state transitions (`PENDING` -> `PAID`) are executed atomically to avoid double-crediting balances.

4. **HTTPS Enforcement**:
   - All API endpoints must be called over `https://paycow.net` (never plain HTTP in production).

---

## Phase 3: Technical API Reference & Data Contracts

### 1. Create Payment Session
- **Endpoint**: `POST https://paycow.net/api/payment/create`
- **Headers**:
  ```http
  Content-Type: application/json
  x-api-key: <PAYCOW_API_KEY>
  x-api-secret: <PAYCOW_API_SECRET>
  Idempotency-Key: <UNIQUE_IDEMPOTENCY_KEY>
  ```
- **Request Body Fields**:
  - `amount` (required, number): Payment amount in USDT (e.g. `29.99`).
  - `userId` (required, string): Customer ID, account number, or internal order reference.
  - `network` (required, string): Settlement blockchain network. Allowed values: `"ERC20"` or `"TRC20"`.
  - `currency` (optional, string): Token symbol, default `"USDT"`.
  - `addressSerialNo` (optional, string): Wallet serial ID (e.g. `"WAL-1001"`). If omitted, PayCow automatically routes to the merchant's primary destination wallet configured for that network.
  - `idempotencyKey` (optional, string): Unique key to avoid duplicate session generation.

- **Request Body Examples**:

  *TRC-20 (TRON) Example:*
  ```json
  {
    "userId": "usr_94820",
    "amount": 29.99,
    "currency": "USDT",
    "network": "TRC20",
    "addressSerialNo": "WAL-1002",
    "idempotencyKey": "order_uuid_98765"
  }
  ```

  *ERC-20 (Ethereum) Example:*
  ```json
  {
    "userId": "usr_94820",
    "amount": 29.99,
    "currency": "USDT",
    "network": "ERC20",
    "addressSerialNo": "WAL-1001",
    "idempotencyKey": "order_uuid_98766"
  }
  ```

- **Response (200 OK)**:
  ```json
  {
    "sessionId": "66ce30d74c0c51a48f2d2903",
    "paymentUrl": "https://paycow.net/payment/66ce30d74c0c51a48f2d2903",
    "paymentReference": "da11d01c2b8a97dc",
    "amountRequested": 29.99,
    "payableAmount": 29.9901,
    "amount": 29.9901,
    "depositAddress": "TJY5P... (or 0x133b4...)",
    "addressSerialNo": "WAL-1002",
    "walletLabel": "TRON Main Cold Vault",
    "expiresAt": "2026-08-27T12:00:00.000Z"
  }
  ```

> **Note on Non-Colliding Micro-Amount Allocation**:
> PayCow automatically allocates unique micro-amounts (`29.9901`, `29.9902` USDT) to avoid payment amount collisions when multiple active payments target the same deposit address and network.
> - `amountRequested`: Use this base amount (`29.99`) for internal order matching & accounting.
> - `payableAmount` / `amount`: Display this exact micro-amount (`29.9901`) on the checkout screen for customer transfer.

---

### 2. Check / Poll Payment Status
- **Endpoint**: `GET https://paycow.net/payment/data/:sessionId` (Public) or `GET https://paycow.net/api/payment/status/:sessionId` (Protected by API Key & Secret)
- **Response (200 OK)**:
  ```json
  {
    "_id": "66ce30d74c0c51a48f2d2903",
    "status": "PAID",
    "amountRequested": 29.99,
    "payableAmount": 29.9901,
    "amountReceived": 29.9901,
    "currencyInfo": "USDT",
    "depositAddress": "TJY5Pj6xWkP7m...",
    "depositNetwork": "TRC20",
    "confirmations": 20,
    "paymentReference": "da11d01c2b8a97dc",
    "txHash": "a1b2c3d4e5f6...",
    "expiresAt": "2026-08-27T12:00:00.000Z",
    "createdAt": "2026-08-27T11:30:00.000Z"
  }
  ```
  **Valid Payment Statuses**:
  - `PENDING`: Waiting for user to send funds to deposit address.
  - `DETECTED`: Transaction detected in mempool/block, awaiting confirmations.
  - `CONFIRMING`: Transaction detected on blockchain (ERC-20 requires 12 Ethereum blocks; TRC-20 requires solidified TRON blocks).
  - `PAID`: Confirmed on-chain. Funds settled directly to merchant wallet. Safe to unlock order or credit user balance.
  - `EXPIRED`: Session expired after 30 minutes without on-chain deposit.
  - `REJECTED`: Rejected by operator or invalid transaction.

---

### 3. Underpayment & Shortfall Dispute ("Awake Mode")
- **Endpoint**: `POST https://paycow.net/api/dispute/submit`
- **Purpose**: Activates **72-Hour Awake Mode** if a customer underpays by a decimal fraction (e.g. 0.0003 USDT) or loses funds to exchange withdrawal fee deductions (e.g. 0.30 - 0.40 USDT deducted by Binance/OKX).
- **Functionality**: Extends session lifetime to 72 hours, revives expired/rejected sessions back to `PENDING` so blockchain listeners keep monitoring the deposit, and sends an automated English notification email to the merchant with the shortfall calculation, TxID, and screenshot proof.
- **Request Fields** (`multipart/form-data` or `application/json`):
  - `sessionId` (string, required if `paymentReference` omitted): Payment MongoDB ID
  - `paymentReference` (string, required if `sessionId` omitted): Payment reference string
  - `reason` (string, required, min 10 chars): Detailed customer explanation
  - `issueType` (string, optional): `exchange_fee_deduction`, `network_fee_shortfall`, `fractional_underpayment`, `wrong_amount_sent`, `other`
  - `amountPaid` (number, optional): Actual amount sent
  - `txHash` (string, optional): Blockchain transaction hash / TxID
  - `contactInfo` (string, optional): Customer email or Telegram handle
  - `screenshot` (file, optional): Proof image/PDF (max 10MB)
- **Response (`201 Created`)**:
  ```json
  {
    "success": true,
    "msg": "Dispute submitted. 72-Hour Awake Mode is now active, and the merchant has been notified via email.",
    "isAwake": true,
    "awakeExpiresAt": "2026-08-30T12:00:00.000Z",
    "shortfallAmount": 0.35,
    "emailDispatched": true
  }
  ```

---

## Phase 4: Implementation Blueprint for the AI Agent

Once the developer responds to Phase 1, proceed with these exact steps:

1. **Configure Environment Variables**:
   Add to `.env`:
   ```env
   PAYCOW_API_KEY=your_api_key_here
   PAYCOW_API_SECRET=your_api_secret_here
   PAYCOW_BASE_URL=https://paycow.net
   ```

2. **Create Backend Service Module** (`paycowService`):
   - Implement `createPaymentSession({ userId, amount, currency, network, addressSerialNo, idempotencyKey })`.
   - Implement `getPaymentStatus(sessionId)`.

3. **Create Payment Route & Controller**:
   - `POST /api/checkout/crypto` (or framework equivalent):
     - Validates user auth & cart/amount.
     - Accepts requested network (`TRC20` or `ERC20`).
     - Saves initial order or deposit record with state `PENDING`.
     - Calls PayCow API (`POST /api/payment/create`) and returns `{ paymentUrl, sessionId }`.

4. **Implement Status Check & Fulfillment Logic**:
   - When payment status becomes `PAID` (via polling or upon user return verification):
     - If Product Checkout: Mark order as `PAID`, trigger digital delivery / shipment email.
     - If Balance Top-up: Increment user balance atomically in database with transaction reference lock.
     - If Subscription: Update user subscription expiry date by +30 or +365 days.

5. **Build Frontend Checkout Trigger**:
   - Create a clean "Pay with USDT (TRC-20 / ERC-20)" checkout UI.
   - On click, fetch `paymentUrl` and redirect `window.location.href = data.paymentUrl;` (or display embedded frame).

6. **Verify End-to-End**:
   - Test session creation and verify that `paymentUrl` loads the hosted checkout page with the correct network badge and deposit address.

---

## Phase 5: Webhooks Blueprint & HMAC Verification Guide

PayCow supports real-time asynchronous Webhook notifications for payment events. Webhooks eliminate the need for constant client polling and trigger instant backend fulfillment.

### 1. Supported Webhook Event Types
- `payment.detected`: Blockchain transaction observed in mempool / initial block.
- `payment.confirming`: Transaction confirmed on-chain and gaining required block depth.
- `payment.paid`: Transaction fully confirmed. Funds delivered to merchant wallet. **Trigger order fulfillment / balance credit here.**
- `payment.expired`: Payment invoice expired without receiving funds.
- `payment.rejected`: Payment manually or automatically rejected.
- `webhook.test`: Test event triggered via merchant dashboard.

> **Note on Webhook Setup**: Configured Webhook Endpoint URLs in the merchant dashboard automatically activate live real-time webhook event delivery.

### 2. Webhook Event Payload Example
```json
{
  "id": "evt_9a8b7c6d5e4f",
  "type": "payment.paid",
  "apiVersion": "2026-09-01",
  "createdAt": "2026-09-09T15:10:00.000Z",
  "data": {
    "sessionId": "66ce30d74c0c51a48f2d2903",
    "paymentReference": "da11d01c2b8a97dc",
    "userId": "usr_94820",
    "status": "PAID",
    "amountRequested": 29.99,
    "payableAmount": 29.9901,
    "amountReceived": 29.9901,
    "currency": "USDT",
    "network": "TRC20",
    "depositAddress": "TJY5Pj6xWkP7m...",
    "txHash": "a1b2c3d4e5f6...",
    "confirmations": 20
  }
}
```

### 2. HTTP Headers & Signature Verification
PayCow signs all webhook requests using HMAC-SHA256. Webhook payloads contain the following HTTP headers:

```http
PayCow-Event-Id: evt_abc123456789
PayCow-Timestamp: 1788957931
PayCow-Signature: v1=9f8e7d6c5b4a3...
Content-Type: application/json
```

### 3. Node.js Verification Example

```javascript
import crypto from 'crypto';

function verifyPayCowWebhookSignature({ rawBody, timestamp, signature, secret, toleranceSeconds = 300 }) {
  if (!rawBody || !timestamp || !signature || !secret) {
    return false;
  }

  // 1. Replay Attack Protection: Validate timestamp freshness (+/- 5 minutes)
  const now = Math.floor(Date.now() / 1000);
  const tsNumber = Number(timestamp);
  if (isNaN(tsNumber) || Math.abs(now - tsNumber) > toleranceSeconds) {
    return false;
  }

  // 2. Compute expected HMAC-SHA256 signature on exact raw body bytes
  const signedPayload = `${timestamp}.${rawBody}`;
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  const receivedSignature = signature.replace('v1=', '');

  if (expectedSignature.length !== receivedSignature.length) {
    return false;
  }

  // 3. Timing-safe byte comparison
  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature, 'hex'),
    Buffer.from(receivedSignature, 'hex')
  );
}
```

### 4. Idempotency & Retry Policy
- Webhook delivery operates on **At-Least-Once Delivery** semantics.
- Merchants MUST store `event.id` or check if the payment reference has already been processed before executing order fulfillment.
- If delivery fails or receives non-2xx status code (e.g. 500, 429, timeout), PayCow retries delivery up to 8 attempts using exponential backoff:
  - Attempt 1: Immediate
  - Attempt 2: +30 seconds
  - Attempt 3: +2 minutes
  - Attempt 4: +10 minutes
  - Attempt 5: +30 minutes
  - Attempt 6: +2 hours
  - Attempt 7: +6 hours
  - Attempt 8: +24 hours
- Retries preserve the EXACT same `eventId` (`evt_...`).

### 5. Polling Fallback & Verification
Webhooks act as the primary push mechanism. The standard polling endpoints (`GET /payment/data/:paymentId` and `GET /api/payment/status/:paymentId`) remain available for secondary verification, recovery, and offline fallback checks.
