# SessionPaymentStaking

**Status:** Design\
**Module:** Payment Layer\
**Integration:** `SessionV2`, `SessionPayment`, `NodePayment`, `Validator`\
**Purpose:** Implements stake-based payment velocity and network-funded sessions.

***

The `SessionPaymentStaking` contract introduces a **Stake-to-Use payment model** that allows developers to access Cortensor’s inference services based on their **staking commitment**, rather than requiring upfront per-task deposits.

It preserves **full backward compatibility** with the existing `SessionPayment` pipeline while adding **rate limiting**, **stake-based velocity control**, and **network-funded session allocation**.

***

### **Core Problem Solved**

#### **Traditional Challenge**

* Users must prepay for each session or task.
* Costs are unpredictable — difficult to plan and budget.
* High friction discourages frequent or small task submissions.
* Stake size does not affect access speed or task velocity.

#### **Stake-to-Use Solution**

* Network admin deposits $COR into a **shared funding pool**.
* Users **stake tokens** to unlock **usage velocity credits**.
* Sessions are automatically funded from the pool, not user wallets.
* **Rate limiting** enforces fairness and prevents abuse.
* Creates predictable usage and smooth cash flow for developers.

***

### **Architecture Components**

#### **1. Network Deposit Pool**

```solidity
uint256 public totalNetworkAdminDeposits;
uint256 public totalNetworkDepositPoolBalance;
```

**Purpose:**\
Central funding source for all staking-based sessions.

**Management:**\
Admin-controlled, tracks lifetime deposits and current balances.

**Funding:**\
Supports both ERC20 $COR and native tokens.

***

#### **2. Session Payment Type Tracking**

```solidity
mapping(uint256 => bool) public isSessionStakingPayment;
```

**Purpose:**\
Indicates which sessions use the staking model versus direct payment.

**Integration:**\
Referenced by `SessionV2` for routing logic.

**Effect:**\
Enables dual payment coexistence (direct pay & stake-to-use).

***

#### **3. Rate Limiting System**

```solidity
mapping(address => uint256) public userWindowStart;
mapping(address => uint256) public userWindowConsumed;
mapping(address => uint256) public userWindowLimit;
mapping(address => uint256) public userLastUpdate;

uint256 public windowDuration = 86400; // 24 hours
```

**Purpose:**\
Prevents abuse and smooths access velocity.

**Algorithm:**\
Sliding window with auto-reset.

**Configuration:**\
Admin can adjust limits, durations, and ratios.

***

#### **4. Staking Integration**

```solidity
mapping(address => uint256) public userStakingBalance;
mapping(address => uint256) public userStakingExpirationDate;

uint256 public stakingToLimitRatio = 1000;
uint256 public minimumWindowLimit = 10;
```

**Purpose:**\
Converts staking amount into daily velocity limits.

**Formula:**

```
windowLimit = max((stakingAmount * stakingToLimitRatio) / 1e18, minimumWindowLimit)
```

**Safeguards:**\
Minimum limits guarantee basic access even with small stakes.

***

### **Payment Flow Integration**

#### **Traditional Payment Flow (Unchanged)**

1. `User → depositToSession()` → Session balance.
2. `Session → payFromSessionToNetwork()` → Network credit.
3. `Network → allocateNodePayments()` → Node distribution.
4. `Nodes → withdrawNodePayment()` → Final token transfer.

***

#### **New Stake-to-Use Flow**

1. **Admin** → `depositToNetworkDeposit()` → Shared pool.
2. **SessionV2** → `checkAndUpdateRateLimit()` → Validate stake velocity.
3. **SessionV2** → `depositToSessionFromNetworkDeposit()` → Fund session.
4. **Normal settlement continues** via existing flow.

***

#### **Dual Model Coexistence**

| **Type**     | **Funding Source**   | **Mechanism**                |
| ------------ | -------------------- | ---------------------------- |
| Direct Pay   | User deposits        | Per-session payments         |
| Stake-to-Use | Network deposit pool | Rate-limited staking credits |

Both models **share identical accounting and payout** logic for seamless transition.

***

### **Key Functional Components**

#### **Network Pool Management**

```solidity
function depositToNetworkDeposit(uint256 amount) public;
function depositToNetworkDepositNative() public payable;
```

**Purpose:**\
Funds the shared network deposit pool.

**Access:**\
Public (typically admin).

**Events:**\
`DepositToNetworkDeposit(sender, amount, tokenType)`

***

#### **Session Funding**

```solidity
function depositToSessionFromNetworkDeposit(uint256 sessionId, uint256 amount)
    public onlyAdmin sessionExists(sessionId)
```

**Purpose:**\
Transfers credits from the network pool to a session.

**Validation:**\
Checks existence and amount constraints.

**Event:**\
`DepositToSessionFromNetworkDeposit(sessionId, amount, poolBalance, totalSessionBalances)`

***

#### **Staking Management**

```solidity
function setStakingInfo(address _user, uint256 _amount, uint256 _expirationDate) external onlyAdmin;
```

**Purpose:**\
Defines user stake amount, expiry, and derived velocity.

**Automation:**\
Auto-calculates `userWindowLimit`.

**Event:**\
`UserWindowLimitUpdated(user, newLimit)`

***

#### **Rate Limiting**

```solidity
function checkAndUpdateRateLimit(address _user, uint256 _amount) public returns (bool allowed);
function canConsumeAmount(address _user, uint256 _amount) public view returns (bool allowed, uint256 remaining);
```

**Purpose:**\
Enforces stake-based access velocity.

**Integration:**\
Used by `SessionV2` before session funding.

**Events:**\
`RateLimitConsumed`, `RateLimitExceeded`, `RateLimitWindowReset`.

***

### **Rate Limiting Algorithm**

#### **Window Lifecycle**

* **Initialization:** New window created upon first session request.
* **Auto-reset:** Resets after `windowDuration` (default 24h).
* **Tracking:** Records each session consumption.
* **Overflow:** Rejects over-limit requests.

#### **Limit Formula**

```solidity
windowLimit = max(
    (stakingAmount * stakingToLimitRatio) / 1e18,
    minimumWindowLimit
)
```

**Example:**\
5 COR × 1000 = 5000 tasks/day.\
Minimum: 10 tasks/day baseline.

***

#### **Event Triggers**

* `RateLimitWindowReset` — new window started.
* `RateLimitConsumed` — task consumption recorded.
* `RateLimitExceeded` — rate cap breach detected.
* `UserWindowLimitUpdated` — new limit after stake update.

***

### **Integration with SessionV2**

#### **Session Creation Flow**

```solidity
if (paymentType == PaymentType.StakeToUse) {
    (bool allowed, ) = stakingContract.canConsumeAmount(user, estimatedCost);
    require(allowed, "Rate limit exceeded");

    stakingContract.depositToSessionFromNetworkDeposit(sessionId, estimatedCost);
    stakingContract.checkAndUpdateRateLimit(user, estimatedCost);

    stakingContract.isSessionStakingPayment[sessionId] = true;
}
```

#### **Task Submission Flow**

```solidity
if (isSessionStakingPayment[sessionId]) {
    // Already funded by staking pool
    // Proceed with normal settlement
} else {
    // Direct payment required
}
```

***

### **Administrative Controls**

#### **Pool Management**

* **Funding:** `depositToNetworkDeposit()`
* **Monitoring:** via `totalNetworkDepositPoolBalance`
* **Emergency Withdrawals:** Admin-only fail-safes

#### **Rate Limit Configurations**

* `setStakingToLimitRatio()` — adjust stake-to-velocity rate.
* `setMinimumWindowLimit()` — ensure minimum access.
* `setWindowDuration()` — modify time window.
* `setUserWindowLimit()` — override specific user access.

#### **Staking Updates**

* `setStakingInfo()` — batch updates, cron-compatible.
* **Auto-expiration:** expired stakes revert to minimum access.

***

### **Event System & Monitoring**

| **Category** | **Event**                          | **Purpose**                   |
| ------------ | ---------------------------------- | ----------------------------- |
| Financial    | DepositToNetworkDeposit            | Pool funding tracking         |
| Financial    | DepositToSessionFromNetworkDeposit | Session allocation            |
| Rate Limit   | RateLimitConsumed                  | Track per-user velocity usage |
| Rate Limit   | RateLimitExceeded                  | Detect overuse or abuse       |
| Rate Limit   | RateLimitWindowReset               | Window lifecycle tracking     |
| Staking      | UserWindowLimitUpdated             | Stake-based velocity updates  |

**Dashboard Integration:**\
All events are indexable for:

* User velocity visualization
* Pool health monitoring
* Session funding history

***

### **Security & Audit Features**

#### **Access Control**

* Role-based permissions (`Admin`, `Session`, `User`)
* Function-specific modifiers
* Emergency administrative overrides

#### **Double-Entry Accounting**

* Tracks total pool balance vs. session allocations.
* Maintains historical auditing via `totalNetworkAdminDeposits`.

#### **Rate Limiting Security**

* Sliding window prevents burst usage.
* Minimum limits ensure fair baseline.
* Expiry automatically handled.
* Full event logging for auditing.

***

### **Benefits & Advantages**

| **Audience**       | **Benefit**                                                              |
| ------------------ | ------------------------------------------------------------------------ |
| **Developers**     | Predictable cost model, no per-task payments, velocity scales with stake |
| **Network**        | Sustainable liquidity, reduced abuse, predictable inflows                |
| **Infrastructure** | Zero disruption to existing payments, fully backward compatible          |

***

### **Summary**

`SessionPaymentStaking` extends Cortensor’s payment layer into a **stake-powered usage model**, replacing frictional prepayments with predictable, rate-limited access.\
It integrates directly with `SessionV2` and existing payment flows while remaining **modular, auditable, and upgrade-safe**, enabling the next evolution of **staking-as-utility** within the Cortensor network.
