UNPKG

@admin-jigsaw/jigsaw-sdk

Version:

Returns predefined data for Jigsaw platform and exposes functionality to retrieve the necessary data

317 lines (316 loc) 17.6 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; import { createPublicClient, formatEther, http } from "viem"; import { mainnet } from "viem/chains"; import { strategyManagerAbi } from "../contracts/strategyManagerAbi"; import { STRATEGY_MANAGER } from "../constants"; import { strategyAbi } from "../contracts/strategyAbi"; import { generatePendleRemoveLiquidityDataString, getPendleMarketByStrategy, } from "../utils/pendle.utils"; import { removeLiquiditySingleToken } from "../lib/pendle"; import { getProtocolByStrategy } from "../utils/protocols.utils"; import { COLLATERALS } from "../constants/coinsConstants"; import { PENDLE_STRATEGIES, AAVE_STRATEGIES, DINERO_STRATEGIES, PROTOCOLS_DATA, RESERVOIR_STRATEGIES, NUCLEUS_STRATEGIES, PROTOCOLS_ASSETS, } from "../constants/strategiesConstants"; var JigsawClient = /** @class */ (function () { function JigsawClient(clientOrRpcUrl) { if (typeof clientOrRpcUrl === "object") { this.client = clientOrRpcUrl; // Use provided client } else { var transport = clientOrRpcUrl ? http(clientOrRpcUrl) : http(); this.client = createPublicClient({ chain: mainnet, transport: transport }); } } /** * Fetches user strategies based on holding address and optional asset symbol. * @param holdingAddress The address of the user's holding contract. * @param assetSymbol Optional filter for asset symbol. * @returns A list of strategies. */ JigsawClient.prototype.getUserStrategies = function (holdingAddress, assetSymbol) { return __awaiter(this, void 0, void 0, function () { var data, error_1; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.client.readContract({ address: STRATEGY_MANAGER, abi: strategyManagerAbi, functionName: "getHoldingToStrategy", args: [holdingAddress], })]; case 1: data = _a.sent(); // TODO: Add a check to see if the user is insolvent on the collateral associated with the strategy, filter to keep only insolvent strategies if (!Array.isArray(data)) return [2 /*return*/, []]; // If no asset symbol specified, return all strategy addresses if (!assetSymbol) { return [2 /*return*/, data]; } // Filter strategies based on asset symbol return [2 /*return*/, data.filter(function (strategyAddress) { var collateralInfo = _this.getCollateralByStrategy(strategyAddress); return (collateralInfo === null || collateralInfo === void 0 ? void 0 : collateralInfo.symbol) === assetSymbol; })]; case 2: error_1 = _a.sent(); console.error("Failed to fetch user strategies:", error_1); return [2 /*return*/, []]; case 3: return [2 /*return*/]; } }); }); }; /** * Fetches liquidation call data for user strategies filtered by asset symbol. * @param holdingAddress User's holding contract address. * @param assetSymbol Optional filter for asset symbol. * @returns Object with arrays of strategy addresses and corresponding call data strings. */ JigsawClient.prototype.getUserLiquidationInfo = function (holdingAddress, assetSymbol) { return __awaiter(this, void 0, void 0, function () { var strategies, callDataPromises, callData, error_2; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 4]); return [4 /*yield*/, this.getUserStrategies(holdingAddress, assetSymbol)]; case 1: strategies = _a.sent(); if (!strategies.length) { return [2 /*return*/, { strategies: [], callData: [] }]; } callDataPromises = strategies.map(function (strategyAddress) { return __awaiter(_this, void 0, void 0, function () { var protocolName, multicallResults, totalSharesRaw, tokenAddress, pendleMarket, resp, error_3; var _a, _b, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: _e.trys.push([0, 5, , 6]); protocolName = getProtocolByStrategy(strategyAddress); if (!(protocolName === PROTOCOLS_DATA.PENDLE.name)) return [3 /*break*/, 4]; return [4 /*yield*/, this.client.multicall({ contracts: [ { address: strategyAddress, abi: strategyAbi, functionName: "recipients", args: [holdingAddress], }, { address: strategyAddress, abi: strategyAbi, functionName: "tokenIn", args: [], }, ], })]; case 1: multicallResults = _e.sent(); totalSharesRaw = ((_a = multicallResults[0]) === null || _a === void 0 ? void 0 : _a.result) ? ((_b = multicallResults[0].result[1]) !== null && _b !== void 0 ? _b : BigInt(0)) : BigInt(0); tokenAddress = (_d = (_c = multicallResults[1]) === null || _c === void 0 ? void 0 : _c.result) !== null && _d !== void 0 ? _d : null; pendleMarket = getPendleMarketByStrategy(strategyAddress); if (!pendleMarket || !tokenAddress) return [2 /*return*/, ""]; return [4 /*yield*/, removeLiquiditySingleToken(tokenAddress, totalSharesRaw.toString(), pendleMarket, holdingAddress)]; case 2: resp = _e.sent(); return [4 /*yield*/, generatePendleRemoveLiquidityDataString(resp)]; case 3: return [2 /*return*/, _e.sent()]; case 4: // Return empty string for non-Pendle strategies return [2 /*return*/, ""]; case 5: error_3 = _e.sent(); console.error("Error processing strategy ".concat(strategyAddress, ":"), error_3); return [2 /*return*/, ""]; case 6: return [2 /*return*/]; } }); }); }); return [4 /*yield*/, Promise.all(callDataPromises)]; case 2: callData = _a.sent(); return [2 /*return*/, { strategies: strategies, callData: callData, }]; case 3: error_2 = _a.sent(); console.error("Failed to fetch liquidation info:", error_2); return [2 /*return*/, { strategies: [], callData: [] }]; case 4: return [2 /*return*/]; } }); }); }; /** * Helper method to get collateral information for a strategy * @param strategyAddress The strategy address * @returns Collateral information including symbol and address */ JigsawClient.prototype.getCollateralByStrategy = function (strategyAddress) { var _loop_1 = function (collateral) { // Check all strategy maps for this strategy address var isAaveStrategy = Object.entries(AAVE_STRATEGIES).some(function (_a) { var symbol = _a[0], strat = _a[1]; return strat.stratAddress === strategyAddress && symbol === collateral.symbol; }); var isDineroStrategy = Object.entries(DINERO_STRATEGIES).some(function (_a) { var symbol = _a[0], strat = _a[1]; return strat.stratAddress === strategyAddress && symbol === collateral.symbol; }); var isReservoirStrategy = Object.entries(RESERVOIR_STRATEGIES).some(function (_a) { var symbol = _a[0], strat = _a[1]; return strat.stratAddress === strategyAddress && symbol === collateral.symbol; }); // Pendle has different structure with general and matured pools var isPendleStrategy = Object.entries(PENDLE_STRATEGIES).some(function (_a) { var symbol = _a[0], pools = _a[1]; if (symbol !== collateral.symbol) return false; return ((pools.general && pools.general.stratAddress === strategyAddress) || (pools.matured && pools.matured.stratAddress === strategyAddress)); }); // Nucleus has nested structure var isNucleusStrategy = Object.entries(NUCLEUS_STRATEGIES).some(function (_a) { var mainSymbol = _a[0], pairs = _a[1]; return Object.values(pairs).some(function (pair) { return pair.stratAddress === strategyAddress && (mainSymbol === collateral.symbol || pair.pairSymbol === collateral.symbol); }); }); if (isAaveStrategy || isDineroStrategy || isReservoirStrategy || isPendleStrategy || isNucleusStrategy) { return { value: { symbol: collateral.symbol, address: collateral.address, } }; } }; for (var _i = 0, _a = Object.values(COLLATERALS); _i < _a.length; _i++) { var collateral = _a[_i]; var state_1 = _loop_1(collateral); if (typeof state_1 === "object") return state_1.value; } return null; }; /** * Fetches the current gas fee in Ether. * @returns The gas price as a formatted string. */ JigsawClient.prototype.getCurrentGasFee = function () { return __awaiter(this, void 0, void 0, function () { var gasPrice, priceInEth, error_4; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.client.getGasPrice()]; case 1: gasPrice = _a.sent(); priceInEth = formatEther(gasPrice); console.log("Current gas price is ".concat(priceInEth)); return [2 /*return*/, priceInEth]; case 2: error_4 = _a.sent(); console.error("Failed to fetch gas price:", error_4); return [2 /*return*/, "0"]; case 3: return [2 /*return*/]; } }); }); }; /** * Retrieves information about a specific strategy. * @param strategyAddress Strategy contract address. * @returns StrategyInfo object or null. */ JigsawClient.prototype.getStrategyInfo = function (strategyAddress) { return __awaiter(this, void 0, void 0, function () { var strategyInfo, error_5; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.client.readContract({ address: STRATEGY_MANAGER, abi: strategyManagerAbi, functionName: "strategyInfo", args: [strategyAddress], })]; case 1: strategyInfo = (_a.sent()); return [2 /*return*/, strategyInfo !== null && strategyInfo !== void 0 ? strategyInfo : null]; case 2: error_5 = _a.sent(); console.error("Failed to fetch strategy info:", error_5); return [2 /*return*/, null]; case 3: return [2 /*return*/]; } }); }); }; /** * Retrieves all available strategies. * @returns A list of available strategies with their protocol names. */ JigsawClient.prototype.getAllStrategies = function () { return Object.values(COLLATERALS).map(function (collateral) { var protocol = PROTOCOLS_ASSETS.find(function (protocol) { return protocol.assets.includes(collateral.symbol); }); return { symbol: collateral.symbol, address: collateral.address, protocolName: protocol ? protocol.name : "UNKNOWN", }; }); }; return JigsawClient; }()); export { JigsawClient };