UNPKG

@agentix/plugin-solana-ranger

Version:
1,423 lines (1,399 loc) 45.7 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { RANGER_DATA_API_BASE: () => RANGER_DATA_API_BASE, RANGER_SOR_API_BASE: () => RANGER_SOR_API_BASE, default: () => index_default }); module.exports = __toCommonJS(index_exports); var import_agentix2 = require("agentix"); // src/actions/getQuote.ts var import_zod = require("zod"); var getQuoteSchema = import_zod.z.object({ fee_payer: import_zod.z.string().describe("The public key of the fee payer account."), symbol: import_zod.z.string().describe("Trading symbol (e.g., 'SOL', 'BTC', 'ETH')."), side: import_zod.z.enum(["Long", "Short"]).describe("Trading side."), size: import_zod.z.number().positive().describe("The size of the position in base asset."), collateral: import_zod.z.number().positive().describe("The amount of collateral to use (in USDC)."), size_denomination: import_zod.z.string().describe("Denomination of the size (must match symbol)."), collateral_denomination: import_zod.z.literal("USDC").describe("Denomination of the collateral (must be 'USDC')."), adjustment_type: import_zod.z.enum([ "Increase", "DecreaseFlash", "DecreaseJupiter", "DecreaseDrift", "DecreaseAdrena", "CloseFlash", "CloseJupiter", "CloseDrift", "CloseAdrena", "CloseAll" ]).describe("Type of position adjustment or quote context."), target_venues: import_zod.z.array(import_zod.z.enum(["Jupiter", "Flash", "Drift"]).describe("Venue")).optional(), slippage_bps: import_zod.z.number().int().optional(), priority_fee_micro_lamports: import_zod.z.number().int().optional() }); var getQuoteAction = { name: "GET_QUOTE", similes: ["get quote", "fetch quote", "quote perp"], description: "Get a trade quote for a perp position using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "SOL", side: "Long", size: 1, collateral: 10, size_denomination: "SOL", collateral_denomination: "USDC", adjustment_type: "Increase" }, output: { venues: [], total_collateral: 10, total_size: 1, average_price: 20.625 }, explanation: "Get a quote for opening a long SOL position." } ] ], schema: getQuoteSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch(`${RANGER_SOR_API_BASE}/v1/order_metadata`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) }); if (!response.ok) { const error = await response.json(); throw new Error(`Quote request failed: ${error.message}`); } return response.json(); } }; // src/actions/getPositions.ts var import_zod2 = require("zod"); var getPositionsSchema = import_zod2.z.object({ public_key: import_zod2.z.string().describe("User's Solana wallet address."), platforms: import_zod2.z.array(import_zod2.z.enum(["DRIFT", "FLASH", "JUPITER", "ADRENA"])).optional().describe("Optional list of platforms to filter by."), symbols: import_zod2.z.array(import_zod2.z.string()).optional().describe( "Optional list of symbols to filter by (e.g., ['SOL-PERP', 'BTC-PERP'])." ), from: import_zod2.z.string().datetime().optional().describe( "Optional earliest position date (ISO 8601 format) to fetch (defaults to 2 days ago in API)." ) }); var getPositionsAction = { name: "GET_POSITIONS", similes: ["get positions", "fetch positions", "positions list"], description: "Fetch open positions for a user from the Ranger API.", examples: [ [ { input: { public_key: "YOUR_PUBLIC_KEY" }, output: { positions: [] }, explanation: "Get all open positions for a user." } ] ], schema: getPositionsSchema, handler: async (agent, input, { apiKey, baseUrl = "https://data-api-staging-437363704888.asia-northeast1.run.app" }) => { const params = new URLSearchParams(); params.set("public_key", input.public_key); if (input.platforms) input.platforms.forEach( (p) => params.append("platforms", p) ); if (input.symbols) input.symbols.forEach((s) => params.append("symbols", s)); if (input.from) params.set("from", input.from); const response = await fetch( `${baseUrl}/v1/positions?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error(`Get positions request failed: ${error.message}`); } return response.json(); } }; // src/actions/increasePosition.ts var import_zod3 = require("zod"); var import_web3 = require("@solana/web3.js"); var import_base64_js = __toESM(require("base64-js"), 1); var increasePositionSchema = import_zod3.z.object({ fee_payer: import_zod3.z.string(), symbol: import_zod3.z.string(), side: import_zod3.z.enum(["Long", "Short"]), size: import_zod3.z.number().positive(), collateral: import_zod3.z.number().positive(), size_denomination: import_zod3.z.string(), collateral_denomination: import_zod3.z.literal("USDC"), adjustment_type: import_zod3.z.literal("Increase"), target_venues: import_zod3.z.array(import_zod3.z.enum(["Jupiter", "Flash", "Drift"])).optional(), slippage_bps: import_zod3.z.number().int().optional(), priority_fee_micro_lamports: import_zod3.z.number().int().optional(), expected_price: import_zod3.z.number().optional() }); var increasePositionAction = { name: "INCREASE_POSITION", similes: ["open position", "increase position", "long perp", "short perp"], description: "Open or increase a perp position using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "SOL", side: "Long", size: 1, collateral: 10, size_denomination: "SOL", collateral_denomination: "USDC", adjustment_type: "Increase" }, output: { message: "...", meta: { venues: [] } }, explanation: "Open a long SOL position." } ] ], schema: increasePositionSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch( `${RANGER_SOR_API_BASE}/v1/increase_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) } ); if (!response.ok) { const error = await response.json(); throw new Error(`Increase position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js.default.toByteArray(messageBase64); const transaction = import_web3.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; const signature = await agent.wallet.signAndSendTransaction( transaction ); return { signature, meta: data.meta }; } }; // src/actions/decreasePosition.ts var import_zod4 = require("zod"); var import_web32 = require("@solana/web3.js"); var import_base64_js2 = __toESM(require("base64-js"), 1); var decreasePositionSchema = import_zod4.z.object({ fee_payer: import_zod4.z.string(), symbol: import_zod4.z.string(), side: import_zod4.z.enum(["Long", "Short"]), size: import_zod4.z.number().positive(), collateral: import_zod4.z.number().positive(), size_denomination: import_zod4.z.string(), collateral_denomination: import_zod4.z.literal("USDC"), adjustment_type: import_zod4.z.enum([ "DecreaseFlash", "DecreaseJupiter", "DecreaseDrift", "DecreaseAdrena" ]), target_venues: import_zod4.z.array(import_zod4.z.enum(["Jupiter", "Flash", "Drift"])).optional(), slippage_bps: import_zod4.z.number().int().optional(), priority_fee_micro_lamports: import_zod4.z.number().int().optional(), expected_price: import_zod4.z.number().optional() }); var decreasePositionAction = { name: "DECREASE_POSITION", similes: ["reduce position", "decrease position", "partial close perp"], description: "Decrease a perp position using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "SOL", side: "Long", size: 0.5, collateral: 5, size_denomination: "SOL", collateral_denomination: "USDC", adjustment_type: "DecreaseFlash" }, output: { signature: "...", meta: { venues: [] } }, explanation: "Decrease a long SOL position via Flash venue." } ] ], schema: decreasePositionSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch( `${RANGER_SOR_API_BASE}/v1/decrease_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) } ); if (!response.ok) { const error = await response.json(); throw new Error(`Decrease position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js2.default.toByteArray(messageBase64); const transaction = import_web32.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; const signature = await agent.wallet.signAndSendTransaction( transaction ); return { signature, meta: data.meta }; } }; // src/actions/closePosition.ts var import_zod5 = require("zod"); var import_web33 = require("@solana/web3.js"); var import_base64_js3 = __toESM(require("base64-js"), 1); var closePositionSchema = import_zod5.z.object({ fee_payer: import_zod5.z.string(), symbol: import_zod5.z.string(), side: import_zod5.z.enum(["Long", "Short"]), adjustment_type: import_zod5.z.enum([ "CloseFlash", "CloseJupiter", "CloseDrift", "CloseAdrena", "CloseAll" ]), slippage_bps: import_zod5.z.number().int().optional(), priority_fee_micro_lamports: import_zod5.z.number().int().optional(), expected_price: import_zod5.z.number().optional() }); var closePositionAction = { name: "CLOSE_POSITION", similes: ["close position", "exit trade", "close perp"], description: "Close an existing perp position using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "SOL", side: "Long", adjustment_type: "CloseFlash" }, output: { signature: "...", meta: { venues: [] } }, explanation: "Close a long SOL position via Flash venue." } ] ], schema: closePositionSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch(`${RANGER_SOR_API_BASE}/v1/close_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) }); if (!response.ok) { const error = await response.json(); throw new Error(`Close position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js3.default.toByteArray(messageBase64); const transaction = import_web33.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; const signature = await agent.wallet.signAndSendTransaction( transaction ); return { signature, meta: data.meta }; } }; // src/actions/withdrawBalance.ts var import_zod6 = require("zod"); var import_web34 = require("@solana/web3.js"); var import_base64_js4 = __toESM(require("base64-js"), 1); var withdrawBalanceSchema = import_zod6.z.object({ fee_payer: import_zod6.z.string(), symbol: import_zod6.z.string(), amount: import_zod6.z.number().positive(), sub_account_id: import_zod6.z.number().int().optional(), adjustment_type: import_zod6.z.literal("WithdrawBalanceDrift") }); var withdrawBalanceAction = { name: "WITHDRAW_BALANCE", similes: ["withdraw balance", "withdraw funds", "withdraw drift"], description: "Withdraw available balance from a Drift account using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "USDC", amount: 100, sub_account_id: 0, adjustment_type: "WithdrawBalanceDrift" }, output: { signature: "...", meta: { venue: "Drift", amount: 100, symbol: "USDC" } }, explanation: "Withdraw 100 USDC from Drift." } ] ], schema: withdrawBalanceSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch(`${RANGER_SOR_API_BASE}/v1/withdraw_balance`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) }); if (!response.ok) { const error = await response.json(); throw new Error(`Withdraw balance request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js4.default.toByteArray(messageBase64); const transaction = import_web34.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; const signature = await agent.wallet.signAndSendTransaction( transaction ); return { signature, meta: data.meta }; } }; // src/actions/depositCollateral.ts var import_zod7 = require("zod"); var import_web35 = require("@solana/web3.js"); var import_base64_js5 = __toESM(require("base64-js"), 1); var depositCollateralSchema = import_zod7.z.object({ fee_payer: import_zod7.z.string(), symbol: import_zod7.z.string(), side: import_zod7.z.enum(["Long", "Short"]), collateral: import_zod7.z.number().positive(), collateral_denomination: import_zod7.z.literal("USDC"), adjustment_type: import_zod7.z.enum([ "DepositCollateralFlash", "DepositCollateralJupiter", "DepositCollateralDrift" ]) }); var depositCollateralAction = { name: "DEPOSIT_COLLATERAL", similes: ["deposit collateral", "add margin", "add funds"], description: "Deposit collateral to a perp position using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "SOL", side: "Long", collateral: 100, collateral_denomination: "USDC", adjustment_type: "DepositCollateralFlash" }, output: { signature: "...", meta: { venues: [] } }, explanation: "Deposit 100 USDC collateral to a long SOL position via Flash." } ] ], schema: depositCollateralSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch( `${RANGER_SOR_API_BASE}/v1/deposit_collateral`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) } ); if (!response.ok) { const error = await response.json(); throw new Error(`Deposit collateral request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js5.default.toByteArray(messageBase64); const transaction = import_web35.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; const signature = await agent.wallet.signAndSendTransaction( transaction ); return { signature, meta: data.meta }; } }; // src/actions/withdrawCollateral.ts var import_zod8 = require("zod"); var import_web36 = require("@solana/web3.js"); var import_base64_js6 = __toESM(require("base64-js"), 1); var withdrawCollateralSchema = import_zod8.z.object({ fee_payer: import_zod8.z.string(), symbol: import_zod8.z.string(), side: import_zod8.z.enum(["Long", "Short"]), collateral: import_zod8.z.number().positive(), collateral_denomination: import_zod8.z.literal("USDC"), adjustment_type: import_zod8.z.enum([ "WithdrawCollateralFlash", "WithdrawCollateralJupiter", "WithdrawCollateralDrift" ]) }); var withdrawCollateralAction = { name: "WITHDRAW_COLLATERAL", similes: ["withdraw collateral", "remove margin", "remove funds"], description: "Withdraw collateral from a perp position using the Ranger SOR API.", examples: [ [ { input: { fee_payer: "YOUR_PUBLIC_KEY", symbol: "SOL", side: "Long", collateral: 50, collateral_denomination: "USDC", adjustment_type: "WithdrawCollateralFlash" }, output: { signature: "...", meta: { venues: [] } }, explanation: "Withdraw 50 USDC collateral from a long SOL position via Flash." } ] ], schema: withdrawCollateralSchema, handler: async (agent, input, { apiKey }) => { const response = await fetch( `${RANGER_SOR_API_BASE}/v1/withdraw_collateral`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(input) } ); if (!response.ok) { const error = await response.json(); throw new Error(`Withdraw collateral request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js6.default.toByteArray(messageBase64); const transaction = import_web36.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; const signature = await agent.wallet.signAndSendTransaction( transaction ); return { signature, meta: data.meta }; } }; // src/actions/getTradeHistory.ts var import_zod9 = require("zod"); var getTradeHistorySchema = import_zod9.z.object({ public_key: import_zod9.z.string(), platforms: import_zod9.z.array(import_zod9.z.string()).optional(), symbols: import_zod9.z.array(import_zod9.z.string()).optional(), start_time: import_zod9.z.string().optional(), end_time: import_zod9.z.string().optional() }); var getTradeHistoryAction = { name: "GET_TRADE_HISTORY", similes: ["get trade history", "fetch trades", "trade history"], description: "Fetch trade history for a user from the Ranger API.", examples: [ [ { input: { public_key: "YOUR_PUBLIC_KEY" }, output: { trades: [] }, explanation: "Get all trade history for a user." } ] ], schema: getTradeHistorySchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); params.set("public_key", input.public_key); if (input.platforms) input.platforms.forEach((p) => params.append("platforms", p)); if (input.symbols) input.symbols.forEach((s) => params.append("symbols", s)); if (input.start_time) params.set("start_time", input.start_time); if (input.end_time) params.set("end_time", input.end_time); const response = await fetch(`${RANGER_DATA_API_BASE}/v1/trade_history?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } }); if (!response.ok) { const error = await response.json(); throw new Error(`Get trade history request failed: ${error.message}`); } return response.json(); } }; // src/actions/getLiquidationsLatest.ts var import_zod10 = require("zod"); var getLiquidationsLatestSchema = import_zod10.z.object({}); var getLiquidationsLatestAction = { name: "GET_LIQUIDATIONS_LATEST", similes: [ "get latest liquidations", "fetch liquidations", "liquidations latest" ], description: "Fetch the latest liquidations from the Ranger API.", examples: [ [ { input: {}, output: { liquidations: [] }, explanation: "Get the latest liquidations." } ] ], schema: getLiquidationsLatestSchema, handler: async (agent, _input, { apiKey }) => { const response = await fetch( `${RANGER_DATA_API_BASE}/v1/liquidations/latest`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get liquidations latest request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getLiquidationsTotals.ts var import_zod11 = require("zod"); var getLiquidationsTotalsSchema = import_zod11.z.object({}); var getLiquidationsTotalsAction = { name: "GET_LIQUIDATIONS_TOTALS", similes: [ "get liquidations totals", "fetch liquidation totals", "liquidations summary" ], description: "Fetch the total liquidations from the Ranger API.", examples: [ [ { input: {}, output: { totals: [] }, explanation: "Get the total liquidations." } ] ], schema: getLiquidationsTotalsSchema, handler: async (agent, _input, { apiKey }) => { const response = await fetch( `${RANGER_DATA_API_BASE}/v1/liquidations/totals`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get liquidations totals request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getLiquidationsCapitulation.ts var import_zod12 = require("zod"); var getLiquidationsCapitulationSchema = import_zod12.z.object({ granularity: import_zod12.z.string().optional(), threshold: import_zod12.z.number().optional() }); var getLiquidationsCapitulationAction = { name: "GET_LIQUIDATIONS_CAPITULATION", similes: [ "get liquidations capitulation", "fetch liquidation capitulation", "liquidations threshold" ], description: "Fetch liquidations capitulation data from the Ranger API.", examples: [ [ { input: { granularity: "1h", threshold: 1e4 }, output: { data: [] }, explanation: "Get liquidations capitulation with 1h granularity and threshold 10000." } ] ], schema: getLiquidationsCapitulationSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.granularity) params.set("granularity", input.granularity); if (input.threshold !== void 0) params.set("threshold", input.threshold.toString()); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/liquidations/capitulation?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get liquidations capitulation request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getLiquidationsHeatmap.ts var import_zod13 = require("zod"); var getLiquidationsHeatmapSchema = import_zod13.z.object({ granularity: import_zod13.z.string().optional() }); var getLiquidationsHeatmapAction = { name: "GET_LIQUIDATIONS_HEATMAP", similes: [ "get liquidations heatmap", "fetch liquidation heatmap", "liquidations by time" ], description: "Fetch liquidations heatmap data from the Ranger API.", examples: [ [ { input: { granularity: "1h" }, output: { heatmap: [] }, explanation: "Get liquidations heatmap with 1h granularity." } ] ], schema: getLiquidationsHeatmapSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.granularity) params.set("granularity", input.granularity); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/liquidations/heatmap?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get liquidations heatmap request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getLiquidationsLargest.ts var import_zod14 = require("zod"); var getLiquidationsLargestSchema = import_zod14.z.object({ granularity: import_zod14.z.string().optional(), limit: import_zod14.z.number().int().optional() }); var getLiquidationsLargestAction = { name: "GET_LIQUIDATIONS_LARGEST", similes: [ "get largest liquidations", "fetch largest liquidations", "liquidations biggest" ], description: "Fetch the largest liquidations from the Ranger API.", examples: [ [ { input: { granularity: "1h", limit: 10 }, output: { liquidations: [] }, explanation: "Get the 10 largest liquidations with 1h granularity." } ] ], schema: getLiquidationsLargestSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.granularity) params.set("granularity", input.granularity); if (input.limit !== void 0) params.set("limit", input.limit.toString()); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/liquidations/largest?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get liquidations largest request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getFundingRateArbs.ts var import_zod15 = require("zod"); var getFundingRateArbsSchema = import_zod15.z.object({ min_diff: import_zod15.z.number().optional() }); var getFundingRateArbsAction = { name: "GET_FUNDING_RATE_ARBS", similes: [ "get funding rate arbs", "fetch funding arbitrage", "funding rate opportunities" ], description: "Fetch funding rate arbitrage opportunities from the Ranger API.", examples: [ [ { input: { min_diff: 0.01 }, output: { arbs: [] }, explanation: "Get funding rate arbitrage opportunities with minimum difference 0.01." } ] ], schema: getFundingRateArbsSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.min_diff !== void 0) params.set("min_diff", input.min_diff.toString()); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/funding_rates/arbs?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error(`Get funding rate arbs request failed: ${error.message}`); } return response.json(); } }; // src/actions/getFundingRatesAccumulated.ts var import_zod16 = require("zod"); var getFundingRatesAccumulatedSchema = import_zod16.z.object({ symbol: import_zod16.z.string().optional(), granularity: import_zod16.z.string().optional(), platform: import_zod16.z.string().optional() }); var getFundingRatesAccumulatedAction = { name: "GET_FUNDING_RATES_ACCUMULATED", similes: [ "get funding rates accumulated", "fetch accumulated funding", "funding rates sum" ], description: "Fetch accumulated funding rates from the Ranger API.", examples: [ [ { input: { symbol: "BTC-PERP", granularity: "1h", platform: "Drift" }, output: { rates: [] }, explanation: "Get accumulated funding rates for BTC-PERP on Drift with 1h granularity." } ] ], schema: getFundingRatesAccumulatedSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.symbol) params.set("symbol", input.symbol); if (input.granularity) params.set("granularity", input.granularity); if (input.platform) params.set("platform", input.platform); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/funding_rates/accumulated?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get funding rates accumulated request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getBorrowRatesAccumulated.ts var import_zod17 = require("zod"); var getBorrowRatesAccumulatedSchema = import_zod17.z.object({ symbol: import_zod17.z.string().optional(), granularity: import_zod17.z.string().optional(), platform: import_zod17.z.string().optional() }); var getBorrowRatesAccumulatedAction = { name: "GET_BORROW_RATES_ACCUMULATED", similes: [ "get borrow rates accumulated", "fetch accumulated borrow rates", "borrow rates sum" ], description: "Fetch accumulated borrow rates from the Ranger API.", examples: [ [ { input: { symbol: "BTC-PERP", granularity: "1h", platform: "Drift" }, output: { rates: [] }, explanation: "Get accumulated borrow rates for BTC-PERP on Drift with 1h granularity." } ] ], schema: getBorrowRatesAccumulatedSchema, handler: async (_agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.symbol) params.set("symbol", input.symbol); if (input.granularity) params.set("granularity", input.granularity); if (input.platform) params.set("platform", input.platform); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/borrow_rates/accumulated?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get borrow rates accumulated request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getFundingRatesExtreme.ts var import_zod18 = require("zod"); var getFundingRatesExtremeSchema = import_zod18.z.object({ granularity: import_zod18.z.string().optional(), limit: import_zod18.z.number().int().optional() }); var getFundingRatesExtremeAction = { name: "GET_FUNDING_RATES_EXTREME", similes: [ "get funding rates extreme", "fetch extreme funding", "funding rates outliers" ], description: "Fetch extreme funding rates from the Ranger API.", examples: [ [ { input: { granularity: "1h", limit: 5 }, output: { rates: [] }, explanation: "Get 5 most extreme funding rates with 1h granularity." } ] ], schema: getFundingRatesExtremeSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); if (input.granularity) params.set("granularity", input.granularity); if (input.limit !== void 0) params.set("limit", input.limit.toString()); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/funding_rates/extreme?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get funding rates extreme request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getFundingRatesOiWeighted.ts var import_zod19 = require("zod"); var getFundingRatesOiWeightedSchema = import_zod19.z.object({}); var getFundingRatesOiWeightedAction = { name: "GET_FUNDING_RATES_OI_WEIGHTED", similes: [ "get oi weighted funding rates", "fetch open interest weighted funding", "oi weighted funding rates" ], description: "Fetch open interest weighted funding rates from the Ranger API.", examples: [ [ { input: {}, output: { rates: [] }, explanation: "Get open interest weighted funding rates." } ] ], schema: getFundingRatesOiWeightedSchema, handler: async (agent, _input, { apiKey }) => { const response = await fetch( `${RANGER_DATA_API_BASE}/v1/funding_rates/oi_weighted`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get funding rates oi weighted request failed: ${error.message}` ); } return response.json(); } }; // src/actions/getFundingRatesTrend.ts var import_zod20 = require("zod"); var getFundingRatesTrendSchema = import_zod20.z.object({ symbol: import_zod20.z.string(), platform: import_zod20.z.string().optional() }); var getFundingRatesTrendAction = { name: "GET_FUNDING_RATES_TREND", similes: [ "get funding rates trend", "fetch funding trend", "funding rates history" ], description: "Fetch funding rates trend from the Ranger API.", examples: [ [ { input: { symbol: "BTC-PERP", platform: "Drift" }, output: { trend: [] }, explanation: "Get funding rates trend for BTC-PERP on Drift." } ] ], schema: getFundingRatesTrendSchema, handler: async (agent, input, { apiKey }) => { const params = new URLSearchParams(); params.set("symbol", input.symbol); if (input.platform) params.set("platform", input.platform); const response = await fetch( `${RANGER_DATA_API_BASE}/v1/funding_rates/trend?${params.toString()}`, { method: "GET", headers: { "Content-Type": "application/json", "x-api-key": apiKey } } ); if (!response.ok) { const error = await response.json(); throw new Error( `Get funding rates trend request failed: ${error.message}` ); } return response.json(); } }; // src/tools/ranger_perp_trading.ts var import_agentix = require("agentix"); var import_web37 = require("@solana/web3.js"); var import_base64_js7 = __toESM(require("base64-js"), 1); async function openPerpTradeRanger({ agent, symbol, side, size, collateral, apiKey, ...rest }) { const body = { fee_payer: agent.wallet.getAddress(), symbol, side, size, collateral, size_denomination: symbol, collateral_denomination: "USDC", adjustment_type: "Increase", // TODO: Confirm if this should be "Increase" or another type for open ...rest }; const response = await fetch(`${RANGER_SOR_API_BASE}/v1/increase_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(body) }); if (!response.ok) { const error = await response.json(); throw new Error(`Open position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js7.default.toByteArray(messageBase64); const transaction = import_web37.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; return (0, import_agentix.signOrSendTX)(agent, transaction); } async function closePerpTradeRanger({ agent, symbol, side, apiKey, ...rest }) { const body = { fee_payer: agent.wallet.getAddress(), symbol, side, adjustment_type: "CloseFlash", // TODO: Confirm adjustment_type for close ...rest }; const response = await fetch(`${RANGER_SOR_API_BASE}/v1/close_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(body) }); if (!response.ok) { const error = await response.json(); throw new Error(`Close position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js7.default.toByteArray(messageBase64); const transaction = import_web37.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; return (0, import_agentix.signOrSendTX)(agent, transaction); } async function increasePerpPositionRanger({ agent, symbol, side, size, collateral, apiKey, ...rest }) { const body = { fee_payer: agent.wallet.getAddress(), symbol, side, size, collateral, size_denomination: symbol, collateral_denomination: "USDC", adjustment_type: "Increase", ...rest }; const response = await fetch(`${RANGER_SOR_API_BASE}/v1/increase_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(body) }); if (!response.ok) { const error = await response.json(); throw new Error(`Increase position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js7.default.toByteArray(messageBase64); const transaction = import_web37.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; return (0, import_agentix.signOrSendTX)(agent, transaction); } async function decreasePerpPositionRanger({ agent, symbol, side, size, apiKey, ...rest }) { const body = { fee_payer: agent.wallet.getAddress(), symbol, side, size, adjustment_type: "DecreaseFlash", // TODO: Confirm adjustment_type for decrease ...rest }; const response = await fetch(`${RANGER_SOR_API_BASE}/v1/decrease_position`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(body) }); if (!response.ok) { const error = await response.json(); throw new Error(`Decrease position request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js7.default.toByteArray(messageBase64); const transaction = import_web37.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; return (0, import_agentix.signOrSendTX)(agent, transaction); } async function withdrawBalanceRanger({ agent, symbol, amount, apiKey, ...rest }) { const body = { fee_payer: agent.wallet.getAddress(), symbol, amount, adjustment_type: "WithdrawBalanceDrift", // TODO: Confirm adjustment_type for withdraw ...rest }; const response = await fetch(`${RANGER_SOR_API_BASE}/v1/withdraw_balance`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(body) }); if (!response.ok) { const error = await response.json(); throw new Error(`Withdraw balance request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js7.default.toByteArray(messageBase64); const transaction = import_web37.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; return (0, import_agentix.signOrSendTX)(agent, transaction); } async function withdrawCollateralRanger({ agent, symbol, side, collateral, apiKey, ...rest }) { const body = { fee_payer: agent.wallet.getAddress(), symbol, side, collateral, collateral_denomination: "USDC", adjustment_type: "WithdrawCollateralFlash", // TODO: Confirm adjustment_type for withdraw collateral ...rest }; const response = await fetch( `${RANGER_SOR_API_BASE}/v1/withdraw_collateral`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": apiKey }, body: JSON.stringify(body) } ); if (!response.ok) { const error = await response.json(); throw new Error(`Withdraw collateral request failed: ${error.message}`); } const data = await response.json(); const messageBase64 = data.message; const messageBytes = import_base64_js7.default.toByteArray(messageBase64); const transaction = import_web37.VersionedTransaction.deserialize(messageBytes); const { blockhash } = await agent.wallet.getConnection().getLatestBlockhash(); transaction.message.recentBlockhash = blockhash; return (0, import_agentix.signOrSendTX)(agent, transaction); } // src/index.ts var RangerPlugin = class extends import_agentix2.PluginBase { constructor() { const methods = { openPerpTradeRanger, closePerpTradeRanger, increasePerpPositionRanger, decreasePerpPositionRanger, withdrawBalanceRanger, withdrawCollateralRanger }; const actions = [ closePositionAction, decreasePositionAction, depositCollateralAction, getBorrowRatesAccumulatedAction, getFundingRateArbsAction, getFundingRatesAccumulatedAction, getFundingRatesExtremeAction, getFundingRatesOiWeightedAction, getFundingRatesTrendAction, getLiquidationsCapitulationAction, getLiquidationsHeatmapAction, getLiquidationsLargestAction, getLiquidationsLatestAction, getLiquidationsTotalsAction, getPositionsAction, increasePositionAction, getQuoteAction, withdrawBalanceAction, withdrawCollateralAction, getTradeHistoryAction ]; const supportedChains = [ { type: "solana" } ]; super("ranger", methods, actions, supportedChains); } supportsWallet(wallet) { return wallet instanceof import_agentix2.SolanaWalletBase; } }; var index_default = RangerPlugin; function getEnvOrDefault(envKey, fallback) { const proc = typeof globalThis !== "undefined" && globalThis.process ? globalThis.process : void 0; if (proc && proc.env && proc.env[envKey]) { return proc.env[envKey]; } return fallback; } var RANGER_SOR_API_BASE = getEnvOrDefault( "RANGER_SOR_API_BASE", "https://staging-sor-api-437363704888.asia-northeast1.run.app" ); var RANGER_DATA_API_BASE = getEnvOrDefault( "RANGER_DATA_API_BASE", "https://data-api-staging-437363704888.asia-northeast1.run.app" ); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { RANGER_DATA_API_BASE, RANGER_SOR_API_BASE });