@admin-jigsaw/jigsaw-sdk
Version:
Returns predefined data for Jigsaw platform and exposes functionality to retrieve the necessary data
351 lines (232 loc) • 10.9 kB
Markdown
# 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:
```bash
npm install jigsaw-sdk
```
## Getting Started
To use the Jigsaw SDK, you need to import the `JigsawClient` class and initialize it. You can initialize client for each
chain supported by Jigsaw
```typescript
import { JigsawClient } from "@admin-jigsaw/jigsaw-sdk";
const client_sonic = new JigsawClient(
process.env.SONIC_RPC_URL || "https://rpc.soniclabs.com",
sonic.id
);
const client_mainnet = new JigsawClient(
process.env.ETHEREUM_RPC_URL || "mainnet.infura.io",
mainnet.id
);
```
## 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
- **Multi-chain Support**: Work with multiple chains supported by Jigsaw
## 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.
```typescript
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");
```
### 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.
```typescript
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.
```typescript
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

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
Example for Ethereum:

Example for Sonic:

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.
```typescript
import { JigsawClient } from "@admin-jigsaw/jigsaw-sdk";
const client = new JigsawClient(
process.env.ETHEREUM_RPC_URL || "mainnet.infura.io",
mainnet.id
);
const userStrategies = await client.getUserStrategies(holdingAddress);
```
> [!NOTE]
> You can filter strategies by token symbol to focus on specific assets
```typescript
// Get only WETH strategies
const wethStrategies = await client.getUserStrategies(holdingAddress, "WETH");
```
### 3. Prepare Liquidator's Wallet

Ensure your liquidator wallet has sufficient funds to perform the liquidation transaction. You'll need enough native
coin for gas fees and enough jUSD.
<<<<<<< feat/multichain-support
### 4. Find a registry associated with the collateral in Stables Manager
=======
### 4. Request Information for Specific collateral
> > > > > > > master

In order to identify the borrowed amount, the registry of the collateral is required first.
### 5. 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
Use SDK to generate liquidation calldata:

And prepare the transaction as follows:

This call data is crucial as it contains the instructions for the smart contract on how to handle the various strategies
during liquidation.
Mostly it will be empty, but certain contracts, as Pendle (in this example), require additional information to perform
the withdrawal internally to liquidate the position.
### 7. Execute 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 `minCollateralPerJusd` amount of collateral per liquidated jUSD the liquidator agrees to get (up to you)
- The liquidation call data struct from our SDK

> [!IMPORTANT]
> If the transaction fails, just try to adjust slippage, in most of the cases it resolves the issue, otherwise - contact
> support team.
### 8. Verify 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:
```bash
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:
```solidity
function liquidate(
address _user,
address _collateral,
uint256 _jUsdAmount,
uint256 _minCollateralPerJusd,
LiquidateCalldata calldata _data
)
```
The `LiquidateCalldata` struct has the following shape:
```solidity
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](LICENSE) file for details.
## Changelog
See [CHANGELOG.md](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**
```bash
git checkout -b feature/your-feature-name
```
2. **Make your changes**
Implement your features or fixes.
3. **Build the package**
```bash
yarn run build
```
This step is required before proceeding with changesets to ensure that your changes compile correctly.
4. **Document your changes with Changeset**
```bash
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
5. **Test locally**
```bash
yarn test
```
6. **Commit your changes**
```bash
git add .
git commit -m "feat: your descriptive commit message"
```
7. **Push to the remote repository**
```bash
git push origin feature/your-feature-name
```
8. **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