12.1.0 • Published 6 months ago

@admin-jigsaw/jigsaw-sdk v12.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

Jigsaw SDK

Jigsaw SDK provides a streamlined interface for blockchain liquidators to manage insolvent loan positions. The SDK simplifies the complex process of liquidating positions where users have contributed collateral into various DeFi strategies.

Installation

Install the SDK using npm:

npm install jigsaw-sdk

Getting Started

To use the Jigsaw SDK, you need to import the JigsawClient class and initialize it. You can either use a default configuration, provide a custom RPC URL, or use your own viem public client.

import JigsawClient from "jigsaw-sdk";

// Initialize with default mainnet RPC
const client = new JigsawClient();

// Or initialize with custom RPC URL
const client = new JigsawClient("https://your-rpc-url.com");

// Or initialize with your own viem public client
import { createPublicClient, http } from "viem";

const customClient = createPublicClient({
  chain: mainnet,
  transport: http("https://your-rpc-url.com"),
});
const client = new JigsawClient(customClient);

Key Features

  • Strategy Management: Identify and manage user strategies across multiple protocols (AAVE, DINERO, RESERVOIR, PENDLE)
  • Token Filtering: Easily filter strategies by token symbol (e.g., WETH, USDC) to find all relevant positions
  • Liquidation Tools: Generate proper liquidation call data for insolvent positions
  • Gas Estimation: Get current gas prices for transaction cost estimation
  • Multi-protocol Support: Work with various DeFi protocols through a unified interface

API Reference

getUserStrategies(holdingAddress, assetSymbol?)

Retrieves the strategies associated with a user's holding contract. Optionally filters by asset symbol.

  • Parameters:

    • holdingAddress (Address): The address of the user's holding contract.
    • assetSymbol (string, optional): The symbol of the asset to filter strategies.
  • Returns: Promise<Address[]> - A list of strategy addresses or an empty array.

const holdingAddress = "0x..."; // User's holding contract address
const strategies = await client.getUserStrategies(holdingAddress);

// Filter by asset symbol
const usdtStrategies = await client.getUserStrategies(holdingAddress, "USDT");

getAllStrategies()

Retrieves all available strategies.

  • Returns: Strategy[] - A list of all strategies.
const strategies = client.getAllStrategies();

getUserLiquidationInfo(holdingAddress, assetSymbol?)

Retrieves liquidation information for a user's position in a strategy.

  • Parameters:

    • holdingAddress (Address): The address of the user's holding contract.
    • assetSymbol (string, optional): The symbol of the asset to filter strategies.
    • pendleSlippage (number, optional): Slippage parameter for Pendle strategies (default: 0.05).
  • Returns: Promise<{ strategies: Address[]; strategiesData: string[] }> - A struct with two arrays needed for liquidation.

const holdingAddress = "0x..."; // User's holding contract address
const info = await client.getUserLiquidationInfo(holdingAddress, "USDT");

getCurrentGasFee()

Retrieves the current gas price in ETH.

  • Returns: Promise<string> - The current gas price in ETH.
const gasFee = await client.getCurrentGasFee();
console.log(`Current gas price: ${gasFee} ETH`);

Requirements

  • Node.js
  • TypeScript
  • Viem

Step-by-Step Liquidation Tutorial

We've created a sample server application in the examples/server directory to demonstrate how to use the SDK in a real-world liquidation scenario. This example can actually work as a standalone app for identifying and liquidating insolvent positions.

Here's a walkthrough of the liquidation process:

1. Identify Liquidatable Position and Associated Holding

Identify Liquidatable Position

First, identify an insolvent position that can be liquidated. You'll need to find the holding address associated with the user's position. This is typically done by querying blockchain data or using a dashboard to monitor positions that have fallen below their required collateralization ratio.

2. Initialize the SDK and Query User Strategies

SDK Usage

Initialize the Jigsaw SDK and use it to query the user's strategies. This will help you identify which DeFi protocols the user has invested in and what tokens are involved.

import { JigsawClient } from "jigsaw-sdk";

const client = new JigsawClient(process.env.RPC_URL);
const userStrategies = await client.getUserStrategies(holdingAddress);

Note that you can filter strategies by token symbol to focus on specific assets:

// Get only WETH strategies
const wethStrategies = await client.getUserStrategies(holdingAddress, "WETH");

3. Prepare Liquidator Wallet

Prepare Liquidator Wallet

Ensure your liquidator wallet has sufficient funds to perform the liquidation transaction. You'll need ETH for gas fees and enough jUSD.

4. Request Information for Specific collateral

Request Strategy Info

For a more detailed look at a specific token, you should request its information. In this example, we're looking at a USD0++ (used in Pendle strategy only in this example).

5. Identify Borrowed Amount

Identify Borrowed Amount

Determine the amount borrowed by the user that needs to be repaid during liquidation. This information is typically available from the Shares Registry of the selected token or any other method of your choice.

6. Prepare Transaction

Prepare Transaction

Use the SDK to generate the liquidation call data needed for the transaction:

const liquidationInfo = await client.getUserLiquidationInfo(
  holdingAddress,
  tokenSymbol, // Filter by token, if no token provided will return mixed info (for all tokens), be careful
  0.05 // Optional - slippage parameter for certain protocols, e.g. Pendle (max 5%)
);

// The returned object contains:
// - strategies: Array of strategy addresses
// - strategiesData: Array of call data strings

This call data is crucial as it contains the instructions for the smart contract on how to handle the various strategies during liquidation.

7. Execute Liquidation

Successful Liquidation

Submit the liquidation transaction to the blockchain using the data prepared in the previous step. The transaction will need to include:

  • The user's address
  • The collateral address
  • The jUSD amount to liquidate
  • The min collateral receive (up to you)
  • The liquidation call data struct from our SDK

8. Verify Liquidation

Wallet State After Liquidation

After the liquidation is complete, verify your liquidator wallet state to ensure you've received the expected assets from the liquidation. The liquidation bonus should now be reflected in your wallet.

Example Server Application

The examples/server directory contains a simple Express server that demonstrates how to integrate the Jigsaw SDK into a backend application. This example server provides two main endpoints:

  1. /info - Fetches information about a user's strategies
  2. /liquidation-info - Generates liquidation call data for a user's position

To run the example server:

cd examples/server
npm install
npm run dev

The server app can be used as a starting point for your own liquidation service or as a reference implementation.

Notes for Liquidators

  • Liquidators can only liquidate insolvent and "liquidatable" loans
  • It's the liquidator's responsibility to identify _user, _collateral, and _jUsdAmount values
  • When users have contributed collateral into strategies, the contract must withdraw these contributions during liquidation
  • If a user has no active strategies, the strategies array will be empty and the strategiesData will be an empty string

Liquidation Process Technical Details

When a user's collateralization ratio drops and they become insolvent, liquidators can participate in the liquidation process. The primary purpose of this SDK is to simplify the generation of the LiquidateCalldata needed for liquidation.

The liquidation function signature is:

function liquidate(
    address _user,
        address _collateral,
        uint256 _jUsdAmount,
        uint256 _minCollateralReceive,
        LiquidateCalldata calldata _data
)

The LiquidateCalldata struct has the following shape:

struct LiquidateCalldata {
    address[] strategies;
    bytes[] strategiesData;
}

When users have contributed collateral into strategies before becoming insolvent, the contract must withdraw these investments as part of liquidation. The SDK automatically generates the correct withdrawal calldata to ensure proper liquidation of loans associated with certain strategy positions.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

See CHANGELOG.md for a list of changes and updates.

Development and Contribution

Making Updates

When making updates to the SDK, follow these steps:

  1. Create a new branch

    git checkout -b feature/your-feature-name
  2. Make your changes Implement your features or fixes.

  3. Build the package

    yarn run build

    This step is required before proceeding with changesets to ensure that your changes compile correctly.

  4. Document your changes with Changeset

    npx changeset
  • Follow the prompts to select which packages are affected
  • Choose the appropriate semver bump (major, minor, patch)
  • Provide a detailed description of your changes
  • This will create a new file in the .changeset directory
  1. Test locally

    yarn test
  2. Commit your changes

    git add .
    git commit -m "feat: your descriptive commit message"
  3. Push to the remote repository

    git push origin feature/your-feature-name
  4. Create a Pull Request

  • Open a PR to merge your branch into the main branch
  • Ensure all CI checks pass

Publishing a New Version

The publishing process is managed through changesets:

  1. Merge the approved feature PR to master

  2. Merge automatically created changesets PR to master

  3. New version is published automatically via a GitHub workflow

Versioning Guidelines

  • Patch (0.0.x): Bug fixes and minor changes that don't affect the API
  • Minor (0.x.0): New features added in a backward-compatible manner
  • Major (x.0.0): Breaking changes that require API consumers to update their code
12.1.0

6 months ago

12.0.0

6 months ago

11.0.0

6 months ago

10.1.1

6 months ago

10.1.0

6 months ago

10.0.1

7 months ago

10.0.0

7 months ago

9.2.0

7 months ago

9.1.0

7 months ago

9.0.0

7 months ago

8.0.1

7 months ago

8.0.0

7 months ago

7.2.0

7 months ago

7.1.0

7 months ago

7.0.0

7 months ago

6.1.1

7 months ago

6.1.0

7 months ago

6.0.1

7 months ago

5.0.2

7 months ago

4.1.0

7 months ago

4.0.0

7 months ago

3.0.0

9 months ago

2.1.0

9 months ago