Docs/Integration & APIs
On this page

Integration Guide

Overview

This guide provides detailed instructions for integrating with the Riskify protocol. It covers pool creation, risk transfer, and interaction patterns for different pool types.

Prerequisites

  1. Environment Setup

    # Install dependencies
    npm install @riskify/core
    npm install @riskify/pools
    npm install @riskify/ml
    
  2. Configuration

    import { RiskifyConfig } from '@riskify/core';
    
    const config = new RiskifyConfig({
      networkId: 1,
      providerUrl: 'https://mainnet.infura.io/v3/YOUR-PROJECT-ID',
      poolFactoryAddress: '0x...',
      mlOptimizerAddress: '0x...',
    });
    

Pool Creation

1. Structured Pool

import { StructuredPoolFactory, TrancheConfig } from '@riskify/pools';

// Define tranche configuration
const trancheConfig: TrancheConfig[] = [
  {
    name: 'Senior',
    targetAPY: 500, // 5%
    maxCapacity: ethers.utils.parseEther('1000000'),
    minStakeTime: 7 * 24 * 3600, // 7 days
  },
  {
    name: 'Mezzanine',
    targetAPY: 1000, // 10%
    maxCapacity: ethers.utils.parseEther('500000'),
    minStakeTime: 14 * 24 * 3600, // 14 days
  },
  {
    name: 'Junior',
    targetAPY: 2000, // 20%
    maxCapacity: ethers.utils.parseEther('250000'),
    minStakeTime: 30 * 24 * 3600, // 30 days
  },
];

// Create structured pool
const poolFactory = new StructuredPoolFactory(config);
const tx = await poolFactory.createPool({
  name: 'Example Structured Pool',
  symbol: 'ESP',
  tranches: trancheConfig,
  riskParameters: {
    maxLeverage: 2000, // 20x
    targetCollateralRatio: 1200, // 120%
    liquidationThreshold: 1100, // 110%
  },
});

const receipt = await tx.wait();
const poolId = receipt.events?.find(e => e.event === 'PoolCreated')?.args?.poolId;

2. Cross Pool

import { CrossPoolFactory, CrossPoolConfig } from '@riskify/pools';

// Define cross pool configuration
const crossPoolConfig: CrossPoolConfig = {
  name: 'Example Cross Pool',
  symbol: 'ECP',
  maxCapacity: ethers.utils.parseEther('2000000'),
  targetAPY: 1500, // 15%
  minStakeTime: 14 * 24 * 3600, // 14 days
  riskParameters: {
    maxConcentration: 2000, // 20%
    targetCorrelation: 5000, // 50%
    rebalanceThreshold: 1000, // 10%
  },
};

// Create cross pool
const poolFactory = new CrossPoolFactory(config);
const tx = await poolFactory.createPool(crossPoolConfig);
const receipt = await tx.wait();
const poolId = receipt.events?.find(e => e.event === 'PoolCreated')?.args?.poolId;

3. Passive Pool

import { PassivePoolFactory, PassivePoolConfig } from '@riskify/pools';

// Define passive pool configuration
const passivePoolConfig: PassivePoolConfig = {
  name: 'Example Passive Pool',
  symbol: 'EPP',
  maxCapacity: ethers.utils.parseEther('5000000'),
  targetAPY: 800, // 8%
  minStakeTime: 30 * 24 * 3600, // 30 days
  riskParameters: {
    maxDrawdown: 1000, // 10%
    rewardRate: 500, // 5%
    utilizationTarget: 8000, // 80%
  },
};

// Create passive pool
const poolFactory = new PassivePoolFactory(config);
const tx = await poolFactory.createPool(passivePoolConfig);
const receipt = await tx.wait();
const poolId = receipt.events?.find(e => e.event === 'PoolCreated')?.args?.poolId;

Risk Transfer

1. Direct Transfer

import { RiskPropagation } from '@riskify/core';

const riskPropagation = new RiskPropagation(config);

// Transfer risk between pools
const tx = await riskPropagation.propagateRisk({
  sourcePoolId: sourceId,
  targetPoolId: targetId,
  amount: ethers.utils.parseEther('100000'),
  data: '0x', // Optional additional data
});

await tx.wait();

2. Bundle Transfer

import { BundlePropagation } from '@riskify/core';

const bundlePropagation = new BundlePropagation(config);

// Create and transfer risk bundle
const tx = await bundlePropagation.propagateBundle({
  sourcePoolId: sourceId,
  targetPoolId: targetId,
  amounts: [
    ethers.utils.parseEther('50000'),
    ethers.utils.parseEther('30000'),
    ethers.utils.parseEther('20000'),
  ],
  tokenIds: [1, 2, 3],
  data: '0x',
});

await tx.wait();

Pool Interaction Patterns

1. Stake Management

import { PoolInteraction } from '@riskify/core';

const poolInteraction = new PoolInteraction(config);

// Stake in pool
const stakeTx = await poolInteraction.stake({
  poolId: poolId,
  amount: ethers.utils.parseEther('10000'),
  duration: 30 * 24 * 3600, // 30 days
});

// Unstake from pool
const unstakeTx = await poolInteraction.unstake({
  poolId: poolId,
  amount: ethers.utils.parseEther('5000'),
});

2. Reward Collection

import { RewardManager } from '@riskify/core';

const rewardManager = new RewardManager(config);

// Collect rewards
const tx = await rewardManager.claimRewards({
  poolId: poolId,
  recipient: wallet.address,
});

Event Monitoring

1. Pool Events

import { PoolEventMonitor } from '@riskify/core';

const monitor = new PoolEventMonitor(config);

// Monitor pool events
monitor.on('PoolCreated', (event) => {
  console.log('New pool created:', event.poolId);
});

monitor.on('RiskPropagated', (event) => {
  console.log('Risk propagated:', {
    from: event.sourcePoolId,
    to: event.targetPoolId,
    amount: event.amount,
  });
});

2. Risk Events

import { RiskEventMonitor } from '@riskify/core';

const monitor = new RiskEventMonitor(config);

// Monitor risk events
monitor.on('RiskLevelBreached', (event) => {
  console.log('Risk level breached:', {
    poolId: event.poolId,
    currentRisk: event.currentRisk,
    threshold: event.threshold,
  });
});

Error Handling

import { RiskifyError } from '@riskify/core';

try {
  // Attempt operation
  await poolInteraction.stake({
    poolId: poolId,
    amount: amount,
  });
} catch (error) {
  if (error instanceof RiskifyError) {
    switch (error.code) {
      case 'INSUFFICIENT_CAPACITY':
        console.log('Pool has insufficient capacity');
        break;
      case 'EXCEEDED_RISK_LIMIT':
        console.log('Operation would exceed risk limits');
        break;
      case 'INVALID_PARAMETERS':
        console.log('Invalid parameters provided');
        break;
      default:
        console.log('Unknown error:', error.message);
    }
  }
}

Best Practices

  1. Transaction Management

    • Always wait for transaction receipts
    • Implement proper error handling
    • Monitor gas prices and adjust accordingly
  2. Risk Management

    • Monitor risk levels regularly
    • Implement circuit breakers
    • Set appropriate risk limits
  3. Performance Optimization

    • Batch transactions when possible
    • Use event listeners efficiently
    • Implement proper caching
  4. Security

    • Validate all inputs
    • Implement access controls
    • Regular security audits

Testing

import { RiskifyTestUtils } from '@riskify/testing';

describe('Pool Integration', () => {
  let testUtils: RiskifyTestUtils;
  
  beforeEach(async () => {
    testUtils = await RiskifyTestUtils.create();
  });
  
  it('should create and stake in pool', async () => {
    const poolId = await testUtils.createTestPool();
    const amount = ethers.utils.parseEther('1000');
    
    await testUtils.stakeInPool(poolId, amount);
    const stake = await testUtils.getStake(poolId);
    
    expect(stake).to.equal(amount);
  });
}); 

Search concepts, APIs, pools, and integration guides.