> For the complete documentation index, see [llms.txt](https://docs.neurochain.ai/nc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.neurochain.ai/nc/neurochainai-guides/architecture/payment-flow.md).

# Payment Flow

This document details the blockchain-based payment system in NCN Network v2, including fee calculation, transaction flow, and smart contract interactions.

***

## Overview

NCN Network uses an **escrow-based payment model** where clients deposit funds before computation, and payments are distributed after validated completion.

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           Payment Flow Overview                              │
│                                                                             │
│   1. Request        2. Validate      3. Pay           4. Compute           │
│   ┌─────────┐       ┌─────────┐      ┌─────────┐      ┌─────────┐          │
│   │ Client  │──────▶│Validators│─────▶│Blockchain│─────▶│ Compute │          │
│   │         │       │ (M-of-N) │      │ (Escrow) │      │  Node   │          │
│   └─────────┘       └─────────┘      └─────────┘      └─────────┘          │
│                                                              │              │
│   8. Result         7. Validate      6. Complete     5. Sign │              │
│   ┌─────────┐       ┌─────────┐      ┌─────────┐      ┌──────▼──┐          │
│   │ Client  │◀──────│Validators│◀─────│Blockchain│◀─────│ Result  │          │
│   │         │       │ (M-of-N) │      │(Distribute)│     │         │          │
│   └─────────┘       └─────────┘      └─────────┘      └─────────┘          │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

***

## Payment Tree

Every inference request has an associated **Payment Tree** that defines how funds are distributed:

### Structure

```protobuf
message PaymentTree {
  string compute_price_wei = 1;    // Payment to compute node
  string gateway_gas_wei = 2;       // Gas reimbursement for gateway
  string validator_reward_wei = 3;  // Split among validators
  string treasury_fee_wei = 4;      // Protocol treasury
}
```

### Distribution Breakdown

| Recipient        | Purpose                        | Typical % |
| ---------------- | ------------------------------ | --------- |
| **Compute Node** | Payment for model execution    | 80%       |
| **Gateway**      | Gas costs and routing fee      | 10%       |
| **Validators**   | Consensus participation reward | 5%        |
| **Treasury**     | Protocol development fund      | 5%        |

### Example Payment Tree

For a 1 ETH total payment:

```json
{
  "compute_price_wei": "800000000000000000",   // 0.8 ETH
  "gateway_gas_wei": "100000000000000000",      // 0.1 ETH
  "validator_reward_wei": "50000000000000000",  // 0.05 ETH
  "treasury_fee_wei": "50000000000000000"       // 0.05 ETH
}
```

***

## Fee Calculation

### Compute Price

The compute price is calculated based on:

```
compute_price = base_price + (token_count × price_per_token) + (execution_time × time_rate)
```

| Factor            | Description             | Example     |
| ----------------- | ----------------------- | ----------- |
| `base_price`      | Minimum fee per request | 0.001 ETH   |
| `token_count`     | Input/output tokens     | 1000 tokens |
| `price_per_token` | Per-token rate          | 0.0001 ETH  |
| `execution_time`  | Estimated compute time  | 5 seconds   |
| `time_rate`       | Per-second rate         | 0.001 ETH/s |

### Gateway Gas

```
gateway_gas = estimated_gas × gas_price × gas_multiplier
```

Covers:

* Transaction submission
* Event monitoring
* Result relay

### Validator Reward

```
validator_reward = compute_price × validator_rate
validator_per_validator = validator_reward / num_validators
```

Split equally among participating validators.

### Treasury Fee

```
treasury_fee = total_payment × treasury_rate
```

Fixed percentage (default: 5%) for protocol development.

***

## Payment Lifecycle

### Phase 1: Fee Estimation

Before payment, clients can estimate fees:

```
Client                    Gateway                    Registry
  │                          │                          │
  │ 1. EstimateFee           │                          │
  │─────────────────────────▶│                          │
  │                          │ 2. EstimateSubnetFee     │
  │                          │─────────────────────────▶│
  │                          │                          │
  │                          │ 3. Fee + Quote ID        │
  │                          │◀─────────────────────────│
  │ 4. Estimated Fee         │                          │
  │◀─────────────────────────│                          │
```

**Response includes:**

* `fee_wei` - Total estimated fee
* `fee_quote_id` - Valid for 10 minutes
* `config_hash` - Anti-tampering hash
* `expires_at` - Quote expiration

### Phase 2: Preprocessing Validation

Validators verify request setup:

```
Gateway                    Registry                  Validators
  │                          │                          │
  │ 1. RequestPreprocessing  │                          │
  │─────────────────────────▶│                          │
  │                          │ 2. Select N validators   │
  │                          │─────────────────────────▶│
  │                          │                          │
  │                          │ 3. Validate & Sign       │
  │                          │◀─────────────────────────│
  │                          │    (M-of-N signatures)   │
  │ 4. PreprocessingValidation│                          │
  │◀─────────────────────────│                          │
```

**Validators verify:**

* Gateway is registered and reputable
* Compute node is available and capable
* Payment amounts are correctly calculated
* Request parameters are valid

### Phase 3: Payment Initiation

Client pays on blockchain:

```
Client                    Blockchain               Gateway
  │                          │                       │
  │ 1. Approve token spend   │                       │
  │─────────────────────────▶│                       │
  │                          │                       │
  │ 2. initiateInferenceRequest()                    │
  │─────────────────────────▶│                       │
  │   (amount, signatures)   │                       │
  │                          │ 3. RequestInitiated   │
  │                          │ (event)               │
  │                          │──────────────────────▶│
  │ 4. tx_hash               │                       │
  │◀─────────────────────────│                       │
  │                          │                       │
  │ 5. Confirm payment       │                       │
  │───────────────────────────────────────────────────▶│
```

**Smart contract verifies:**

* M-of-N validator signatures
* Correct payment amount
* Request not expired
* Token allowance sufficient

### Phase 4: Execution

After payment confirmation, compute proceeds:

```
Gateway                    Compute                  Registry
  │                          │                          │
  │ 1. Dispatch task         │                          │
  │─────────────────────────▶│                          │
  │   (with payment info)    │                          │
  │                          │ 2. Verify payment        │
  │                          │ 3. Execute model         │
  │                          │ 4. Sign result           │
  │ 5. InferenceResponse     │                          │
  │◀─────────────────────────│                          │
  │   (signed result)        │                          │
```

### Phase 5: Completion Validation

Validators verify computation:

```
Gateway                    Registry                  Validators
  │                          │                          │
  │ 1. RequestCompletion     │                          │
  │─────────────────────────▶│                          │
  │   (signed result)        │                          │
  │                          │ 2. Select N validators   │
  │                          │─────────────────────────▶│
  │                          │                          │
  │                          │ 3. Validate & Sign       │
  │                          │◀─────────────────────────│
  │                          │    (M-of-N signatures)   │
  │ 4. CompletionValidation  │                          │
  │◀─────────────────────────│                          │
```

**Validators verify:**

* Compute node signature is valid
* Result format is correct
* Computation time is reasonable
* Result hash matches

### Phase 6: Payment Distribution

Gateway finalizes on blockchain:

```
Gateway                    Blockchain               Recipients
  │                          │                          │
  │ 1. completeInferenceRequest()                       │
  │─────────────────────────▶│                          │
  │   (completion signatures)│                          │
  │                          │                          │
  │                          │ 2. Verify signatures     │
  │                          │ 3. Transfer to compute   │
  │                          │─────────────────────────▶│
  │                          │ 4. Transfer to gateway   │
  │                          │─────────────────────────▶│
  │                          │ 5. Transfer to validators│
  │                          │─────────────────────────▶│
  │                          │ 6. Transfer to treasury  │
  │                          │─────────────────────────▶│
  │                          │                          │
  │                          │ 7. PaymentDistributed    │
  │ 8. tx_hash               │ (event)                 │
  │◀─────────────────────────│                          │
```

***

## Smart Contract Interface

### InferencePayment Contract

#### `initiateInferenceRequest`

```solidity
function initiateInferenceRequest(
    bytes32 requestId,
    address gateway,
    address computeNode,
    uint256 computePrice,
    uint256 gatewayGas,
    uint256 validatorReward,
    uint256 treasuryFee,
    uint256 expiry,
    bytes[] calldata validatorSignatures
) external;
```

**Requirements:**

* Caller has approved token spend
* M-of-N validator signatures valid
* Expiry timestamp in future
* Request ID not already used

#### `completeInferenceRequest`

```solidity
function completeInferenceRequest(
    bytes32 requestId,
    bytes calldata computeSignature,
    bytes32 resultHash,
    bytes[] calldata validatorSignatures
) external;
```

**Requirements:**

* Request exists and is pending
* Compute node signature valid
* M-of-N validator signatures valid
* Called by original gateway

#### `handleExpiredRequest`

```solidity
function handleExpiredRequest(bytes32 requestId) external;
```

**Behavior:**

* If request expired, refund to original payer
* Anyone can call (gas incentive)

### Events

```solidity
event RequestInitiated(
    bytes32 indexed requestId,
    address indexed client,
    address indexed gateway,
    uint256 totalAmount
);

event PaymentDistributed(
    bytes32 indexed requestId,
    address computeNode,
    uint256 computePayment,
    address gateway,
    uint256 gatewayPayment
);

event RequestRefunded(
    bytes32 indexed requestId,
    address indexed client,
    uint256 amount
);
```

***

## Failure Handling

### Compute Failure

If computation fails:

1. Gateway calls `markRequestFailed` (admin function)
2. Or request expires after timeout
3. Client receives automatic refund

```
┌─────────────────────────────────────────────────────────┐
│                  Failure Recovery                        │
│                                                         │
│   Compute fails → Gateway notifies → Expiry triggers    │
│        │                │                   │           │
│        ▼                ▼                   ▼           │
│   Log failure    Mark failed (admin)   Auto-refund     │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

### Validator Rejection

If validators reject completion:

1. Gateway cannot call `completeInferenceRequest`
2. Request expires
3. Client refunded automatically

### Transaction Failure

If blockchain transaction fails:

1. Gateway retries with exponential backoff
2. After max retries, request marked failed
3. Client refunded if funds escrowed

***

## Security Considerations

### Double-Spend Prevention

* Request IDs are unique (UUID v4)
* Each request ID can only be initiated once
* Completion only possible for initiated requests

### Signature Verification

* All signatures verified on-chain
* ECDSA signatures with secp256k1
* Validators must be registered in contract

### Expiry Protection

* Preprocessing validations expire (10 min)
* Payment requests expire (configurable, default 1 hour)
* Automatic refund after expiry

### Reentrancy Protection

* `ReentrancyGuard` on all payment functions
* Checks-Effects-Interactions pattern
* No external calls before state updates

***

## Token Flow Diagram

```
                           InferencePayment Contract
                          ┌────────────────────────────┐
                          │                            │
     Client               │     Escrow Balance         │
    ┌──────┐   deposit    │    ┌────────────────┐     │
    │ NCN  │─────────────▶│    │  Request Pool  │     │
    │Tokens│              │    │                │     │
    └──────┘              │    │  req1: 1 ETH   │     │
                          │    │  req2: 0.5 ETH │     │
                          │    │  ...           │     │
                          │    └───────┬────────┘     │
                          │            │              │
                          │    on completion          │
                          │            │              │
                          │    ┌───────▼────────┐     │
                          │    │  Distribution  │     │
                          │    └───────┬────────┘     │
                          │            │              │
                          └────────────┼──────────────┘
                                       │
              ┌────────────────────────┼─────────────────────────┐
              │                        │                         │
              ▼                        ▼                         ▼
        ┌──────────┐            ┌──────────┐             ┌──────────┐
        │ Compute  │            │ Gateway  │             │Validators│
        │  0.8 ETH │            │  0.1 ETH │             │ 0.05 ETH │
        └──────────┘            └──────────┘             └──────────┘
                                                                │
                                                                ▼
                                                         ┌──────────┐
                                                         │ Treasury │
                                                         │ 0.05 ETH │
                                                         └──────────┘
```

***

## Configuration

### Gateway Payment Settings

```bash
# Contract configuration
CONTRACT_ADDRESS=0x4361115359E5C0a25c9b2f8Bb71184F010b768ea
RPC_URL=http://127.0.0.1:8545

# Transaction settings
GAS_LIMIT=500000
GAS_PRICE_MULTIPLIER=1.1
REQUIRED_CONFIRMATIONS=1
CONFIRMATION_TIMEOUT_SECS=300
```

### Pricing Configuration

```bash
# Base pricing
BASE_COMPUTE_PRICE_WEI=1000000000000000    # 0.001 ETH
PRICE_PER_TOKEN_WEI=100000000000           # 0.0001 ETH

# Fee rates
GATEWAY_FEE_RATE=0.10                       # 10%
VALIDATOR_FEE_RATE=0.05                     # 5%
TREASURY_FEE_RATE=0.05                      # 5%
```

***

## Monitoring

### Key Metrics

| Metric                         | Description              |
| ------------------------------ | ------------------------ |
| `payments_initiated_total`     | Total payments initiated |
| `payments_completed_total`     | Successfully distributed |
| `payments_refunded_total`      | Refunded payments        |
| `payment_amount_wei_total`     | Total wei processed      |
| `payment_distribution_time_ms` | Time to distribute       |

### Events to Monitor

```javascript
// Listen for payment events
contract.on("RequestInitiated", (requestId, client, gateway, amount) => {
    console.log(`Payment initiated: ${requestId} for ${amount} wei`);
});

contract.on("PaymentDistributed", (requestId, compute, computeAmount) => {
    console.log(`Payment distributed: ${requestId}`);
});
```

***

## Next Steps

* [Validation & Consensus](/nc/neurochainai-guides/architecture/validation-consensus.md) - Validator mechanism
* [Smart Contracts](/nc/neurochainai-guides/components/smart-contracts.md) - Contract details
* [Security Model](/nc/neurochainai-guides/architecture/security-model.md) - Security architecture
