Docs/Integration & APIs
On this page

API Documentation

← ML Integration | Deployment Guide →

Table of Contents

Contract APIs

The Contract APIs provide direct interaction with the Riskify smart contracts, enabling developers to create and manage pools, transfer risk, and monitor metrics.

Pool Management

System diagram
Diagram source
sequenceDiagram
    participant Client
    participant Factory
    participant Pool
    participant Oracle

    Note over Client,Oracle: Pool Creation Process
    
    Client->>Factory: createPool()
    Factory->>Pool: initialize()
    Pool->>Oracle: setupOracle()
    Oracle->>Pool: confirm()
    Pool->>Factory: register()
    Factory->>Client: return poolId

    Note over Client,Oracle: Pool Creation Complete

    %% Styling
    rect rgb(245, 245, 245, 0.8)
        Note over Client,Oracle: Pool Creation Process
    end
    rect rgb(240, 240, 240, 0.8)
        Note over Client,Oracle: Pool Creation Complete
    end

Pool Management Flow Explanation:

  1. Client Request: A client initiates the pool creation process by calling the factory contract
  2. Factory Initialization: The factory contract creates a new pool instance and initializes it
  3. Oracle Setup: The pool contract sets up the risk oracle for price feeds and risk assessment
  4. Oracle Confirmation: The oracle confirms the setup and returns configuration details
  5. Pool Registration: The pool registers itself with the factory for tracking and management
  6. Pool ID Return: The factory returns the unique pool ID to the client for future interactions

This flow ensures that pools are properly initialized with all necessary components and registered in the system for management and monitoring.

IPoolBase Interface

interface IPoolBase {
    function createPool(PoolConfig calldata config) external returns (uint256);
    function participate(uint256 poolId, uint256 amount) external returns (bool);
    function withdraw(uint256 poolId, uint256 amount) external returns (bool);
    function getPoolMetrics(uint256 poolId) external view returns (
        uint256 capacity,
        uint256 utilized,
        uint256 riskScore
    );
}

IPoolBase Interface Explanation: This interface defines the core functionality for all pool types:

  • createPool: Creates a new pool with the specified configuration
  • participate: Allows users to participate in a pool by depositing funds
  • withdraw: Enables users to withdraw their funds from a pool
  • getPoolMetrics: Retrieves key metrics about a pool's performance and status

IStructuredPool Interface

interface IStructuredPool {
    function configureTranches(
        uint256 poolId,
        TrancheConfig[] calldata configs
    ) external;
    
    function investInTranche(
        uint256 poolId,
        uint256 trancheId,
        uint256 amount
    ) external returns (bool);
}

IStructuredPool Interface Explanation: This interface extends the base pool functionality for structured pools:

  • configureTranches: Sets up the tranche structure with specific risk/reward profiles
  • investInTranche: Allows users to invest in a specific tranche within the pool

Risk Management

System diagram
Diagram source
graph TB
    %% Styling
    classDef risk fill:#4a5568,stroke:#2d3748,color:white,stroke-width:2px,font-weight:bold
    classDef validation fill:#718096,stroke:#4a5568,color:white,stroke-width:2px,font-weight:bold
    classDef node fill:#f7fafc,stroke:#e2e8f0,color:#2d3748,stroke-width:1px

    subgraph RiskAPIFlow["Risk API Flow"]
        direction TB
        RC["Risk Calculation"]
        RP["Risk Propagation"]
        RV["Risk Validation"]
        RM["Risk Monitoring"]
    end

    subgraph Validation["Validation"]
        direction TB
        SV["Solvency Verification"]
        CV["Collateral Validation"]
        TV["Transaction Validation"]
    end

    RiskAPIFlow --> Validation

    %% Apply styles
    class RiskAPIFlow risk
    class Validation validation
    class RC,RP,RV,RM,SV,CV,TV node

Risk Management Flow Explanation:

  • Risk API Flow: The core risk management processes:
    • Risk Calculation: Determines risk metrics based on pool composition and market conditions
    • Risk Propagation: Manages how risk flows between different pools and participants
    • Risk Validation: Verifies the accuracy and reliability of risk calculations
    • Risk Monitoring: Tracks risk metrics in real-time and triggers alerts when thresholds are breached
  • Validation: Security checks that ensure risk operations are valid:
    • Solvency Verification: Confirms that pools maintain sufficient reserves
    • Collateral Validation: Ensures that collateral meets requirements for risk exposure
    • Transaction Validation: Verifies that transactions meet protocol rules and constraints

This comprehensive risk management system ensures that all risk operations are properly calculated, validated, and monitored for security and reliability.

IRiskScore Interface

interface IRiskScore {
    function calculateRisk(
        uint256 poolId,
        uint256 amount,
        bytes calldata riskData
    ) external view returns (
        uint256 riskScore,
        uint256 confidence
    );

    function validateRisk(
        uint256 poolId,
        uint256 riskScore,
        bytes calldata proof
    ) external returns (bool);
}

IRiskScore Interface Explanation: This interface provides risk calculation and validation functionality:

  • calculateRisk: Computes a risk score for a specific pool and amount, returning both the score and a confidence level
  • validateRisk: Verifies that a risk score is valid using a cryptographic proof

ISolvencyVerifier Interface

interface ISolvencyVerifier {
    function verifyReserves(
        uint256 poolId,
        bytes calldata proof,
        uint256 currentCollateral,
        uint256 requiredCollateral
    ) external view returns (bool);
}

ISolvencyVerifier Interface Explanation: This interface ensures that pools maintain sufficient reserves:

  • verifyReserves: Checks if a pool has enough collateral to cover its risk exposure, using a cryptographic proof for verification

ML Service APIs

The ML Service APIs provide access to the machine learning models that power risk assessment, pricing, and optimization in the Riskify Protocol.

Price Oracle API

Request Format

{
    "poolId": "uint256",
    "amount": "uint256",
    "timestamp": "uint256",
    "riskParameters": {
        "baseRisk": "uint256",
        "temporalRisk": "uint256",
        "correlationRisk": "uint256"
    }
}

Price Oracle Request Explanation: This request format defines the parameters needed for price calculation:

  • poolId: The unique identifier of the pool
  • amount: The amount of risk being priced
  • timestamp: The time for which the price is being calculated
  • riskParameters: Risk metrics that influence pricing:
    • baseRisk: The fundamental risk level
    • temporalRisk: Time-dependent risk factors
    • correlationRisk: Risk from correlations with other assets

Response Format

{
    "price": "uint256",
    "components": {
        "basePrice": "uint256",
        "riskPremium": "uint256",
        "temporalAdjustment": "uint256"
    },
    "confidence": "uint256",
    "timestamp": "uint256"
}

Price Oracle Response Explanation: This response format provides comprehensive pricing information:

  • price: The final calculated price
  • components: Breakdown of price components:
    • basePrice: The fundamental price before adjustments
    • riskPremium: Additional cost for risk exposure
    • temporalAdjustment: Time-based price adjustments
  • confidence: A measure of the price reliability
  • timestamp: The time when the price was calculated

Risk Assessment API

Request Format

{
    "poolId": "uint256",
    "positions": [{
        "amount": "uint256",
        "duration": "uint256",
        "collateral": "uint256"
    }],
    "riskParameters": {
        "maxLoss": "uint256",
        "confidenceLevel": "uint256"
    }
}

Risk Assessment Request Explanation: This request format defines the parameters for risk assessment:

  • poolId: The unique identifier of the pool
  • positions: Array of positions to assess:
    • amount: The size of the position
    • duration: The time horizon for the position
    • collateral: The collateral backing the position
  • riskParameters: Configuration for risk assessment:
    • maxLoss: The maximum acceptable loss
    • confidenceLevel: The required confidence level for the assessment

Response Format

{
    "riskScore": "uint256",
    "components": {
        "baseRisk": "uint256",
        "temporalRisk": "uint256",
        "correlationRisk": "uint256"
    },
    "validationMetrics": {
        "solvencyScore": "uint256",
        "collateralRatio": "uint256"
    }
}

Risk Assessment Response Explanation: This response format provides comprehensive risk assessment:

  • riskScore: The overall risk score
  • components: Breakdown of risk components:
    • baseRisk: Fundamental risk metrics
    • temporalRisk: Time-dependent risk factors
    • correlationRisk: Risk from correlations
  • validationMetrics: Metrics that validate the assessment:
    • solvencyScore: Measure of pool solvency
    • collateralRatio: Ratio of collateral to risk exposure

Integration APIs

The Integration APIs provide a higher-level interface for common operations, abstracting away the complexity of direct contract interactions.

Pool Creation

System diagram
Diagram source
sequenceDiagram
    participant Client
    participant API
    participant Factory
    participant Oracle

    Note over Client,Oracle: Pool Creation via API
    
    Client->>API: POST /pools/create
    API->>Factory: createPool()
    Factory->>Oracle: setupOracle()
    Oracle->>Factory: confirm()
    Factory->>API: return poolId
    API->>Client: poolCreated

    Note over Client,Oracle: Pool Creation Complete

    %% Styling
    rect rgb(245, 245, 245, 0.8)
        Note over Client,Oracle: Pool Creation via API
    end
    rect rgb(240, 240, 240, 0.8)
        Note over Client,Oracle: Pool Creation Complete
    end

Pool Creation Flow Explanation:

  1. Client Request: A client sends a POST request to the API with pool creation parameters
  2. API Processing: The API processes the request and calls the factory contract
  3. Factory Creation: The factory creates a new pool and initializes it
  4. Oracle Setup: The factory sets up the risk oracle for the pool
  5. Oracle Confirmation: The oracle confirms the setup
  6. Pool ID Return: The factory returns the pool ID to the API
  7. Client Response: The API returns a response to the client with the pool creation status

This flow simplifies pool creation by handling the complexity of contract interactions behind a REST API.

Request Format

{
    "poolType": "STRUCTURED | CROSS | PASSIVE",
    "config": {
        "capacity": "uint256",
        "minParticipation": "uint256",
        "maxParticipation": "uint256"
    },
    "tranches": [{
        "attachmentPoint": "uint256",
        "exhaustionPoint": "uint256",
        "capacity": "uint256"
    }]
}

Pool Creation Request Explanation: This request format defines the parameters for pool creation:

  • poolType: The type of pool to create (STRUCTURED, CROSS, or PASSIVE)
  • config: General pool configuration:
    • capacity: The maximum capacity of the pool
    • minParticipation: The minimum participation amount
    • maxParticipation: The maximum participation amount
  • tranches: Array of tranche configurations (for structured pools):
    • attachmentPoint: The point at which the tranche begins to absorb losses
    • exhaustionPoint: The point at which the tranche is fully exhausted
    • capacity: The capacity of the tranche

Response Format

{
    "poolId": "uint256",
    "status": "CREATED | PENDING | ACTIVE",
    "transaction": {
        "hash": "bytes32",
        "blockNumber": "uint256"
    },
    "config": {
        "capacity": "uint256",
        "utilized": "uint256"
    }
}

Pool Creation Response Explanation: This response format provides information about the created pool:

  • poolId: The unique identifier of the created pool
  • status: The current status of the pool (CREATED, PENDING, or ACTIVE)
  • transaction: Information about the blockchain transaction:
    • hash: The transaction hash
    • blockNumber: The block number in which the transaction was included
  • config: Configuration information about the pool:
    • capacity: The maximum capacity of the pool
    • utilized: The current utilization of the pool

Risk Transfer

Request Format

{
    "sourcePoolId": "uint256",
    "targetPoolId": "uint256",
    "amount": "uint256",
    "riskMetrics": {
        "score": "uint256",
        "capacity": "uint256"
    }
}

Risk Transfer Request Explanation: This request format defines the parameters for risk transfer:

  • sourcePoolId: The ID of the pool transferring risk
  • targetPoolId: The ID of the pool receiving risk
  • amount: The amount of risk to transfer
  • riskMetrics: Risk metrics for the transfer:
    • score: The risk score of the transfer
    • capacity: The capacity of the target pool

Response Format

{
    "transferId": "uint256",
    "status": "PENDING | COMPLETED | FAILED",
    "metrics": {
        "sourceCapacity": "uint256",
        "targetCapacity": "uint256",
        "riskScore": "uint256"
    }
}

Risk Transfer Response Explanation: This response format provides information about the risk transfer:

  • transferId: The unique identifier of the transfer
  • status: The current status of the transfer (PENDING, COMPLETED, or FAILED)
  • metrics: Metrics about the transfer:
    • sourceCapacity: The remaining capacity of the source pool
    • targetCapacity: The remaining capacity of the target pool
    • riskScore: The risk score after the transfer

WebSocket APIs

The WebSocket APIs provide real-time updates on risk metrics, market data, and system events, enabling responsive applications.

Risk Metrics Stream

// Subscribe to risk metrics
ws.send(JSON.stringify({
    type: 'subscribe',
    channel: 'risk_metrics',
    poolIds: [1, 2, 3],
    metrics: ['riskScore', 'capacity', 'utilization']
}));

// Receive updates
ws.onmessage = (event) => {
    const update = JSON.parse(event.data);
    console.log('Risk update:', update);
};

Risk Metrics Stream Explanation: This WebSocket API enables real-time monitoring of risk metrics:

  • Subscription: Clients subscribe to specific pools and metrics:
    • type: The type of subscription ('subscribe')
    • channel: The channel to subscribe to ('risk_metrics')
    • poolIds: Array of pool IDs to monitor
    • metrics: Array of metrics to receive updates for
  • Updates: Clients receive real-time updates when metrics change:
    • The update contains the latest values for the requested metrics
    • Updates are pushed to clients as soon as they occur

This real-time data stream enables applications to respond immediately to changes in risk metrics.

Market Data Stream

// Subscribe to market data
ws.send(JSON.stringify({
    type: 'subscribe',
    channel: 'market_data',
    pools: ['*'],
    metrics: ['price', 'volume', 'liquidity']
}));

// Receive updates
ws.onmessage = (event) => {
    const update = JSON.parse(event.data);
    console.log('Market update:', update);
};

Market Data Stream Explanation: This WebSocket API provides real-time market data:

  • Subscription: Clients subscribe to market data for specific pools:
    • type: The type of subscription ('subscribe')
    • channel: The channel to subscribe to ('market_data')
    • pools: Array of pool IDs to monitor ('*' for all pools)
    • metrics: Array of market metrics to receive updates for
  • Updates: Clients receive real-time updates when market data changes:
    • The update contains the latest values for the requested metrics
    • Updates are pushed to clients as soon as they occur

This real-time market data enables applications to provide up-to-date information to users.

Error Handling

The API uses a standardized error response format to provide clear information about errors.

Error Response Format

{
    "error": {
        "code": "string",
        "message": "string",
        "details": "object",
        "timestamp": "uint256"
    }
}

Error Response Explanation: This error response format provides comprehensive information about errors:

  • code: A unique error code that identifies the type of error
  • message: A human-readable description of the error
  • details: Additional information about the error (if available)
  • timestamp: The time when the error occurred

This standardized format ensures consistent error handling across all API endpoints.

Common Error Codes

Code Description
INVALID_REQUEST Invalid request parameters
POOL_NOT_FOUND Pool ID not found
INSUFFICIENT_BALANCE Insufficient balance for operation
UNAUTHORIZED Unauthorized access
VALIDATION_FAILED Risk validation failed

Error Codes Explanation: These common error codes help clients identify and handle specific error conditions:

  • INVALID_REQUEST: The request parameters are invalid or missing
  • POOL_NOT_FOUND: The specified pool ID does not exist
  • INSUFFICIENT_BALANCE: The account does not have sufficient balance for the operation
  • UNAUTHORIZED: The request is not authorized for the current user
  • VALIDATION_FAILED: The risk validation failed for the requested operation

Rate Limits

The API implements rate limits to ensure fair usage and prevent abuse.

Endpoint Rate Limit Window
Pool Creation 10 1 minute
Risk Assessment 100 1 minute
Market Data 1000 1 minute
WebSocket Unlimited N/A

Rate Limits Explanation: These rate limits define the maximum number of requests allowed within a specific time window:

  • Pool Creation: Limited to 10 requests per minute to prevent excessive pool creation
  • Risk Assessment: Limited to 100 requests per minute for risk calculations
  • Market Data: Limited to 1000 requests per minute for market data retrieval
  • WebSocket: No rate limit for WebSocket connections, as they use a different protocol

These limits ensure that the API remains responsive and available for all users.

Next Steps


Need help? Join our Discord | Read our Documentation

Search concepts, APIs, pools, and integration guides.