Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/bin/cairo-metrics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,5 @@ Results stored in SQLite include:

## Future Work

- Incremental compilation benchmarks (requires cairo compiler support)
- Incremental compilation benchmarks (patch logic implemented, awaiting cairo compiler support)
- Additional metrics beyond walltime
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
diff --git a/workspace/fulfillment/src/fulfillment.cairo b/workspace/fulfillment/src/fulfillment.cairo
--- a/workspace/fulfillment/src/fulfillment.cairo
+++ b/workspace/fulfillment/src/fulfillment.cairo
@@ -28,6 +28,7 @@ pub mod Fulfillment {
pub fn constructor(
ref self: ContractState, owner: ContractAddress, expiration_time: Timestamp,
) {
+ let _bench0: felt252 = 0;
self.expiration_time.write(expiration_time);
self.owner.write(owner);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
diff --git a/workspace/vault/src/protocol_vault.cairo b/workspace/vault/src/protocol_vault.cairo
--- a/workspace/vault/src/protocol_vault.cairo
+++ b/workspace/vault/src/protocol_vault.cairo
@@ -108,6 +108,7 @@ pub mod ProtocolVault {
recipient: ContractAddress,
initial_price: u64,
) -> u256 {
+ let _bench1: felt252 = 1;
self.roles.initialize(:governance_admin);
self.replaceability.initialize(:upgrade_delay);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
path = "crates/bin/cairo-metrics/benchmarks/perpetual/project"
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: Auto Update Workflow
permissions:
contents: write
pull-requests: write

on:
push:
branches: [dev]

jobs:
autoupdate:
name: autoupdate
runs-on: ubuntu-22.04
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: docker://chinthakagodawita/autoupdate-action:v1
env:
PR_FILTER: "labelled"
PR_LABELS: "autoupdate"
PR_READY_STATE: "ready_for_review"
MERGE_CONFLICT_ACTION: "ignore"
MERGE_MSG: "Branch was auto-updated."
EXCLUDED_LABELS: "autoupdate-rebase"
autoupdate-rebase:
name: autoupdate-rebase
runs-on: ubuntu-latest
steps:
- uses: peter-evans/rebase@v3
with:
base: dev
include-labels: |
autoupdate-rebase
exclude-labels: |
autoupdate
exclude-drafts: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
name: CI

on:
pull_request:

jobs:
cairo_tests:
runs-on: namespace-profile-2xlarge-ubuntu-24-04-amd64
steps:
- uses: actions/checkout@v4
- uses: foundry-rs/setup-snfoundry@v3
with:
starknet-foundry-version: "0.49.0"

- uses: software-mansion/setup-scarb@v1
with:
scarb-version: "2.12.2"

- name: Build Contracts
run: scarb build

- name: Install cairo-coverage
run: |
curl -L https://raw.githubusercontent.com/software-mansion/cairo-coverage/main/scripts/install.sh | sh

- name: Run test and coverage
run: scarb test -w --coverage

- name: Check formatting
run: scarb fmt -w --check
python_tests:
runs-on: namespace-profile-2xlarge-ubuntu-24-04-amd64
steps:
- uses: actions/checkout@v4

- name: Install asdf
run: scripts/install_asdf.sh

- name: Install starknet-devnet
run: |
asdf plugin add starknet-devnet
asdf install starknet-devnet 0.6.1
asdf global starknet-devnet 0.6.1

- uses: software-mansion/setup-scarb@v1
with:
scarb-version: "2.12.2"

- name: Build Contracts
run: scarb --release build

- uses: actions/setup-python@v4
with:
python-version: '3.10'
cache: 'pip'

- run: pip install -r requirements.txt

- name: Run Python Tests
id: run_tests
run: scripts/python_tests.sh
72 changes: 72 additions & 0 deletions crates/bin/cairo-metrics/benchmarks/perpetual/project/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
node_modules
dist
.pnp
.pnp.js

# testing
coverage

# next.js
.next/
out/
build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# turbo
.turbo

# IDE
.idea
.vscode
.cursorignore

.history

# Vite
**/vite.config.ts.timestamp-*

# run-rs
data

# mocha
coverage/
.nyc_output/

# building tests as part of build
.mocharc.buildtests.js
tsconfig.buildtests.json

# autoenv
.in
.out

#scarb
target

#foundry
.snfoundry_cache
.snfoundry_versioned_programs
snfoundry_trace
coverage_report

#python
venv/
__pycache__
182 changes: 182 additions & 0 deletions crates/bin/cairo-metrics/benchmarks/perpetual/project/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
# AGENTS.md - Starknet Perpetual Protocol

## What is this?

**Starknet Perpetual** is a decentralized perpetual futures trading protocol on Starknet (Cairo 2.x):

- Trade synthetic assets (BTC-PERP, ETH-PERP) with leverage, no expiration
- Vault integration (ERC4626) for yield-bearing collateral
- Oracle-based pricing with funding rate mechanisms

**Full Documentation:** [docs/spec.md](docs/spec.md)

## Architecture

Component-based design in [`core.cairo`](workspace/apps/perpetuals/contracts/src/core/core.cairo):

```text
Core Contract
├── Assets Component - Asset management, prices, funding
├── Positions Component - Position tracking, balances
├── Deposit Component - Two-phase deposit flow
├── Vault Component - Protocol vault integration (deposit/withdraw vault shares)
├── Request Approvals - User-signed requests
└── Access Control - Operator, Roles, Pausable, Upgrades
```

Components expose public interfaces (`#[abi(embed_v0)]`) and internal traits. See [`core.cairo`](workspace/apps/perpetuals/contracts/src/core/core.cairo) for implementation patterns.

**Vault Integration:** Users can deposit collateral into `ProtocolVault` (ERC4626) to receive vault shares. The vault's total assets are calculated from the vault position's Total Value. Shares are traded as collateral within the perpetuals system, earning yield while used for trading.

```text
Protocol Vault (workspace/vault/src/protocol_vault.cairo)
└── ERC4626 Vault - Yield-bearing collateral via vault shares
• Implements ERC4626 standard
• Total Assets is the perps vault position TV ( Total Value)
• Only perps contract can deposit/redeem
```

## Critical: TV/TR Risk Management

**Most important concept in the codebase.** Every position change must maintain position health.

**Formulas:**

- Total Value (TV) = Collateral + Σ(Asset Values)
- Total Risk (TR) = Σ(|Asset Value| × Risk Factor)

**Position States:**

- **Healthy**: `TV ≥ TR` ✅ Position is safe
- **Liquidatable**: `0 < TV < TR` ⚠️ Can be liquidated
- **Deleveragable**: `TV < 0` 🔴 Negative value, insurance fund intervenes

See [`value_risk_calculator.cairo`](workspace/apps/perpetuals/contracts/src/core/value_risk_calculator.cairo) for the implementation.

**Risk Factors:** Increase with position size (tiered) to prevent concentration risk.

**Healthier Validation:** Position changes must be "healthy or healthier" - if unhealthy after change, must improve TV/TR ratio AND reduce TR.

**Funding Mechanism:** Positions pay/receive funding to anchor synthetic prices to spot: `funding_delta = (old_index - new_index) × balance`

## Development Patterns

### Position Modification Pattern

All position changes follow: validate (pause/nonce/assets) → signature check → build diff → TV/TR validation → apply → emit event. See functions in `core.cairo` like `withdraw()`, `trade()`, `liquidate()`.

### Request-Execute Pattern

User operations use two phases to prevent frontrunning:

1. User signs request → registers on-chain (`withdraw_request()`, `transfer_request()`)
2. Operator executes with signature validation (`withdraw()`, `transfer()`)

### Enrichment Pipeline

Position diffs get enriched with prices and risk factors for TV/TR validation:

- `PositionDiff` → `enrich_asset()` → `AssetEnrichedPositionDiff` → `enrich_collateral()` → `PositionDiffEnriched`
- **Performance note:** Enrichment is expensive (especially funding). Only use when validating position health.

## Development Workflow

⚠️ **CRITICAL: Always run `scarb test` after any changes**

Before committing or considering work complete:

1. Run `scarb build` to ensure code compiles
2. Run `scarb test` to verify all tests pass
3. For position logic changes, run specific test suites:
- `scarb test unit_tests` - Quick feedback
- `scarb test flow_tests` - Full integration validation
- `scarb test test_name` - Target specific functionality
4. update the relevant sections in the [docs/spec.md](docs/spec.md)

## Testing

```text
src/tests/
├── unit_tests/ - Component-level tests
├── flow_tests/ - Integration tests
│ └── multi_trade_regression_tests.cairo - Regression suite
└── performance_tests/ - Gas optimization
```

**Run tests:**

```bash
scarb build # Compile
scarb test # All tests
scarb test flow_tests # Integration only
```

**When changing position logic:** Test TV/TR edge cases, funding application, and add regression tests.

## Quick Reference

### File Structure

```text
workspace/apps/perpetuals/contracts/src/core/
├── core.cairo - Main contract
├── interface.cairo - ICore public interface
├── value_risk_calculator.cairo - TV/TR calculations ⭐
├── components/ - Modular components (assets, positions, vault, etc.)
└── types/ - Core types

workspace/vault/src/
└── protocol_vault.cairo - ERC4626 vault for yield-bearing collateral
```

### Commands

```bash
scarb build # Compile
scarb test # Run tests
```

### Key Constants

- `FEE_POSITION`: `PositionId { value: 0 }`
- `INSURANCE_FUND_POSITION`: `PositionId { value: 1 }`
- `EPSILON`: `1` (10^-6 USD for fair deleverage checks)

## Security

### Critical Invariants

1. Positions must be healthy or healthier after changes
2. Orders cannot exceed signed amounts (fulfillment tracking)
3. Funding must be applied before position updates
4. Prices must be validated and recent

### High-Risk Areas

Changes to these require extensive testing:

- `value_risk_calculator.cairo` - Core risk logic
- Funding application in positions component
- Risk factor calculations in assets component
- `protocol_vault.cairo` - Vault integration and ERC4626 hooks

### Operator Role

Executes signed user intents, processes deposits, performs liquidations, updates prices/funding. **Cannot steal funds** - only executes pre-signed user intents.

## Resources

### Cairo & Starknet Ecosystem

- **Cairo Book**: [https://www.starknet.io/cairo-book/](https://www.starknet.io/cairo-book/) - Official Cairo language guide and syntax reference
- **Starknet Foundry (snforge)**: [https://foundry-rs.github.io/starknet-foundry/](https://foundry-rs.github.io/starknet-foundry/) - Testing framework for Starknet smart contracts
- **Scarb**: [https://docs.swmansion.com/scarb/](https://docs.swmansion.com/scarb/) - Build toolchain and package manager for Cairo
- **Openzeppelin Cairo Contracts**: [https://docs.openzeppelin.com/contracts-cairo](https://docs.openzeppelin.com/contracts-cairo)

### Project Documentation

- **Protocol Spec**: [docs/spec.md](docs/spec.md) - Detailed technical specification

---

**Cairo:** 2.x (Edition 2024_07) | **Starknet:** 2.12.2 | **Last Updated:** 2025-10-22
Loading
Loading