# Smart Contracts

NCN Network v2 uses Solidity smart contracts deployed on Ethereum-compatible blockchains for payment handling and validator management.

***

## Overview

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         NCN Smart Contracts                                  │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                    InferencePayment Contract                       │     │
│   │                                                                   │     │
│   │   • Escrow-based payment system                                   │     │
│   │   • Validator signature verification                              │     │
│   │   • Multi-party payment distribution                              │     │
│   │   • Automatic refunds on expiry                                   │     │
│   │                                                                   │     │
│   │   Functions:                                                      │     │
│   │   - initiateInferenceRequest()                                    │     │
│   │   - completeInferenceRequest()                                    │     │
│   │   - handleExpiredRequest()                                        │     │
│   │   - markRequestFailed()                                           │     │
│   │                                                                   │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                       NCNToken Contract                            │     │
│   │                                                                   │     │
│   │   • ERC20 token for payments                                      │     │
│   │   • Standard transfer/approve functions                           │     │
│   │                                                                   │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                  NCNValidatorRegistry Contract                     │     │
│   │                                                                   │     │
│   │   • On-chain validator registration                               │     │
│   │   • Stake management                                              │     │
│   │   • Slashing functionality                                        │     │
│   │                                                                   │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

***

## Deployed Contracts

### Forknet Testnet

| Contract              | Address                                      | Status     |
| --------------------- | -------------------------------------------- | ---------- |
| **InferencePayment**  | `0x4361115359E5C0a25c9b2f8Bb71184F010b768ea` | ✅ Deployed |
| **NCNToken**          | `0x38E2565e8905BeAf83C34b266592465C22A2f108` | ✅ Deployed |
| **ValidatorRegistry** | `0x4F11D4cBE08A5aBa052C368C8477412af63a56f3` | ✅ Deployed |

### Network Configuration

| Setting      | Value                              |
| ------------ | ---------------------------------- |
| **Network**  | Forknet Testnet                    |
| **Chain ID** | 828 (Agglayer connected)           |
| **RPC URL**  | `https://testnet-rpc-1.forknet.io` |

***

## Contract Documentation

### [Inference Payment](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/inference-payment.md)

Main payment contract:

* Payment initiation with validator signatures
* Payment distribution on completion
* Expiry handling and refunds
* Admin functions

### [NCN Token](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/ncn-token.md)

ERC20 payment token:

* Standard ERC20 interface
* Testnet faucet (if available)

### [Validator Registry](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/validator-registry.md)

On-chain validator management:

* Validator registration with stake
* Slashing mechanism
* Stake withdrawal

### [Deployment](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/deployment.md)

Contract deployment guide:

* Local deployment
* Testnet deployment
* Mainnet considerations

### [ABI Reference](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/abi-reference.md)

Contract ABI documentation:

* Function signatures
* Event definitions
* Type encodings

***

## Quick Start

### Prerequisites

Install Foundry:

```bash
curl -L https://foundry.paradigm.xyz | bash
foundryup
```

### Build Contracts

```bash
cd contracts

# Install dependencies
forge install

# Build
forge build

# Run tests
forge test -vvv
```

### Deploy to Local Network

```bash
# Start local Anvil network
anvil

# Deploy (new terminal)
forge script script/Deploy.s.sol --rpc-url http://127.0.0.1:8545 --broadcast
```

***

## InferencePayment Contract

### Core Functions

#### `initiateInferenceRequest`

Initiates a payment request with escrow.

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

**Parameters:**

* `requestId` - Unique request identifier
* `gateway` - Gateway address
* `computeNode` - Compute node address
* `computePrice` - Payment to compute node (wei)
* `gatewayGas` - Payment to gateway (wei)
* `validatorReward` - Payment to validators (wei)
* `treasuryFee` - Protocol fee (wei)
* `expiry` - Expiry timestamp
* `validatorSignatures` - M-of-N validator signatures

#### `completeInferenceRequest`

Completes a request and distributes payment.

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

**Parameters:**

* `requestId` - Request to complete
* `computeSignature` - Compute node's result signature
* `resultHash` - SHA256 hash of result
* `validatorSignatures` - Completion validator signatures

#### `handleExpiredRequest`

Refunds expired requests.

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

### 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
);

event RequestFailed(
    bytes32 indexed requestId,
    string reason
);
```

***

## Integration

### JavaScript/TypeScript

```typescript
import { ethers } from 'ethers';

const CONTRACT_ADDRESS = '0x4361115359E5C0a25c9b2f8Bb71184F010b768ea';
const CONTRACT_ABI = [...]; // See ABI reference

// Connect to contract
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
const signer = new ethers.Wallet(PRIVATE_KEY, provider);
const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer);

// Initiate request
const tx = await contract.initiateInferenceRequest(
    requestId,
    gateway,
    computeNode,
    computePrice,
    gatewayGas,
    validatorReward,
    treasuryFee,
    expiry,
    validatorSignatures
);
await tx.wait();
```

### Rust (ethers-rs)

```rust
use ethers::prelude::*;

// Generate contract bindings
abigen!(
    InferencePayment,
    "contracts/out/InferencePayment.sol/InferencePayment.json"
);

// Connect to contract
let provider = Provider::<Http>::try_from(RPC_URL)?;
let wallet = LocalWallet::from_str(PRIVATE_KEY)?;
let client = SignerMiddleware::new(provider, wallet);
let contract = InferencePayment::new(CONTRACT_ADDRESS.parse()?, Arc::new(client));

// Initiate request
let tx = contract.initiate_inference_request(
    request_id,
    gateway,
    compute_node,
    compute_price,
    gateway_gas,
    validator_reward,
    treasury_fee,
    expiry,
    validator_signatures,
).send().await?.await?;
```

***

## Security

### Implemented Protections

| Protection                 | Description                 |
| -------------------------- | --------------------------- |
| **ReentrancyGuard**        | Prevents reentrancy attacks |
| **Signature Verification** | ECDSA signature validation  |
| **Expiry Checks**          | Time-bound requests         |
| **Access Control**         | Function-level permissions  |
| **Pausable**               | Emergency pause capability  |

### Security Considerations

1. **Private Key Management**: Never expose private keys
2. **Signature Replay**: Unique request IDs prevent replay
3. **Front-running**: Time-bound signatures mitigate
4. **Oracle Dependency**: Validators provide trust
5. **Upgrade Path**: Consider proxy patterns for mainnet

***

## Testing

### Run Tests

```bash
cd contracts

# Run all tests
forge test -vvv

# Run specific test
forge test --match-test testInitiateInferenceRequest -vvv

# Gas report
forge test --gas-report
```

### Test Coverage

```bash
forge coverage
```

### Test Files

| File                         | Coverage     |
| ---------------------------- | ------------ |
| `InferencePayment.t.sol`     | 95%          |
| `NCNValidatorRegistry.t.sol` | 90%          |
| `SignatureDebug.t.sol`       | Helper tests |

***

## Gas Costs

### Estimated Gas Usage

| Function                   | Gas (approx) |
| -------------------------- | ------------ |
| `initiateInferenceRequest` | \~150,000    |
| `completeInferenceRequest` | \~200,000    |
| `handleExpiredRequest`     | \~80,000     |

### Optimization Tips

1. Batch multiple requests
2. Use calldata for signatures
3. Minimize storage writes
4. Consider L2 deployment

***

## Contract Verification

### Verify on Etherscan

```bash
forge verify-contract \
    --chain-id 42161 \
    --compiler-version v0.8.20 \
    --constructor-args $(cast abi-encode "constructor(address,address,uint256)" $TOKEN $TREASURY $MIN_SIGS) \
    $CONTRACT_ADDRESS \
    src/InferencePayment.sol:InferencePayment \
    --etherscan-api-key $ETHERSCAN_API_KEY
```

***

## Related Documentation

* [Inference Payment](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/inference-payment.md) - Detailed payment contract docs
* [Deployment](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/deployment.md) - Deployment guide
* [ABI Reference](https://github.com/NeuroChainAi/docs-guides/blob/main/components/smart-contracts/abi-reference.md) - Contract ABIs
* [Payment Flow](/nc/neurochainai-guides/architecture/payment-flow.md) - Payment architecture


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.neurochain.ai/nc/neurochainai-guides/components/smart-contracts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
