Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Neutral.trade adapter #12674

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"dependencies": {
"@coral-xyz/anchor": "^0.30.1",
"@defillama/sdk": "latest",
"@drift-labs/vaults-sdk": "^0.2.13",
"@project-serum/anchor": "^0.26.0",
"@solana/web3.js": "^1.87.6",
"@solendprotocol/solend-sdk": "^0.4.3",
Expand Down
122 changes: 122 additions & 0 deletions projects/neutral-trade/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const DATA_URL = 'https://raw.githubusercontent.com/neutral-trade/vaults-data/main';

const START_TIMESTAMP = 1730419200; // 2024-11-01


const TOKENS = {
USDC: {
name: 'USDC',
mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
decimals: 6
},
SOL: {
name: 'SOL',
mint: 'So11111111111111111111111111111111111111112',
decimals: 9
},
WBTC: {
name: 'Wrapped BTC (Wormhole) (WBTC)',
mint: '3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh',
decimals: 8
},
WETH: {
name: 'Wrapped ETH (Wormhole) (WETH)',
mint: '7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs',
decimals: 8
}
};

const VAULTS = [
{
name: "USDC Basis (Perps Basket)",
address: "4cvgasNfbJ36yeMVJSkscgL2Yco9dFGdj52Wrg91fmHv",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/btcethfunding.json`
},
{
name: "BTC Super Staking",
address: "BVddkVtFJLCihbVrtLo8e3iEd9NftuLunaznAxFFW8vf",
token: TOKENS.WBTC,
dataUrl: `${DATA_URL}/btcjlpnl.json`
},
{
name: "ETH Super Staking",
address: "ENr5e1BMN5vFUHf4iCCPzR4GjWCKgtHnQcdniRQqMdEL",
token: TOKENS.WETH,
dataUrl: `${DATA_URL}/ethjlpnl.json`
},
{
name: "USDC Staking (JLP Delta Neutral)",
address: "9Fcn3Fd4d5ocrb12xCUtEvezxcjFEAyHBPfrZDiPt9Qj",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/jlpdn.json`
},
{
name: "USDC Staking (JLP Delta Neutral) v2",
address: "41Y8C4oxk4zgJT1KXyQr35UhZcfsp5mP86Z2G7UUzojU",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/jlpdnv2.json`
},
{
name: "USDC Basis (Sanctum-INF)",
address: "CxL8eQmGhN9LKSoHj7bU95JekFPtyZoUc57mbehb5A56",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/solbasis.json`
},
{
name: "SOL Super Staking",
address: "EuSLjg23BrtwYAk1t4TFe5ArYSXCVXLBqrHRBfWQiTeJ",
token: TOKENS.SOL,
dataUrl: `${DATA_URL}/soljlpnl.json`
},
{
name: "JLP Traders Print",
address: "85XuR4kE5yxp1hk91WHAawinXZsuJowxy59STYYpM9pK",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/tradersprint.json`
},
{
name: "JLP Traders Rekt",
address: "2r81MPMDjGSrbmGRwzDg6aqhe3t3vbKcrYfpes5bXckS",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/tradersrekt.json`
},
{
name: "vip01",
address: "CZU38L2NyL6tqFxzYAGYkmkf2JG98tZfZ2CnUapVgXQe",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/vip01.json`
},
{
name: "vip02",
address: "DUW6uWcrsjYmsYDjp9iGDN4JdRa2MqznjuxjKVok5Fsj",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/vip02.json`
},
{
name: "vip03",
address: "Fd3k4c6Dv7m9673ae87P6duQrftY9UVfwiCxngNbJrUQ",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/vip03.json`
},
// 'vip04', // currently inactive
{
name: "vip05",
address: "9BMEyctGvajEubk5iCRBnM9fkeTXUhrxaweYq34jZdC8",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/vip05.json`
},
{
name: "vip06",
address: "6DFDj66PbPoTC16Sh51MJijoTTMYCbMCVC85tnc5UfQ3",
token: TOKENS.USDC,
dataUrl: `${DATA_URL}/vip06.json`
},
];

module.exports = {
DATA_URL,
START_TIMESTAMP,
TOKENS,
VAULTS,
};
58 changes: 58 additions & 0 deletions projects/neutral-trade/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const { Connection, Keypair } = require("@solana/web3.js");
const { AnchorProvider, Program } = require('@project-serum/anchor');
const { DriftClient } = require('@drift-labs/sdk');
const { IDL, VAULT_PROGRAM_ID, VaultClient } = require("@drift-labs/vaults-sdk");
const { JLPDN_PROGAM_ID_V1 } = require("./constants");


/// INIT DRIFT SDK
const initialize = async () => {
const connection = new Connection('https://cold-hanni-fast-mainnet.helius-rpc.com/');
const wallet = Keypair.generate();
const initializeDriftClient = async () => {
const driftClient = new DriftClient({
connection,
wallet,
env: "mainnet-beta",
});
await driftClient.subscribe();
return driftClient;
};
const initializeProgram = (version) => {
const provider = new AnchorProvider(connection, wallet, AnchorProvider.defaultOptions());
return new Program(
IDL,
version == 1 ? JLPDN_PROGAM_ID_V1 : VAULT_PROGRAM_ID,
provider
);
};
const initializeVaultClient = async (version) => {
return new VaultClient({
driftClient: await initializeDriftClient(),
program: initializeProgram(version),
cliMode: true,
});
};
const client = await initializeVaultClient();
const client_jlpdnv1 = await initializeVaultClient(1);
return { client, client_jlpdnv1 };
};


/**
* Utility function to format a timestamp into YYYY-MM-DD format.
* @param {number} ts - The timestamp in milliseconds.
* @returns {string} - The formatted date string.
*/
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}


module.exports = {
initialize,
formatDate,
};
97 changes: 97 additions & 0 deletions projects/neutral-trade/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const { PublicKey } = require("@solana/web3.js");
const { VAULTS, START_TIMESTAMP } = require("./constants");
const { initialize, formatDate } = require("./helpers");


/**
* Fetch historical TVL data from the vault's data repository.
* @param {object} vault - Vault object containing data URL and token details.
* @param {string} date - Date string in YYYY-MM-DD format.
* @returns {Promise<{usd_tvl: number, token_tvl: number}>} - Historical TVL data.
*/
async function fetchHistoricalTvl(vault, date) {
let usd_tvl = 0;
let token_tvl = 0;

try {
const response = await fetch(vault.dataUrl);
const allEntries = Object.entries(await response.json());
const entry = allEntries.find(([entryTime]) => entryTime?.startsWith(date));
if (entry) {
const [, entryData] = entry;
usd_tvl = entryData?.TVL_USD || 0;
token_tvl = (entryData?.TVL_TOKEN || 0) * Math.pow(10, vault.token.decimals);
}
} catch (error) {
console.error(`Error fetching historical TVL for vault ${vault.name} on ${date}:`, error);
}

return { usd_tvl, token_tvl };
}


/**
* Fetch the current TVL of a vault from the blockchain.
* @param {object} vault - Vault object containing address and token details.
* @param {object} client - Drift client for interacting with the blockchain.
* @returns {Promise<number>} - Current token TVL.
*/
async function fetchCurrentTvl(vault, client) {
try {
const vaultInstance = await client.getVault(new PublicKey(vault.address));
const token_tvl = await client.calculateVaultEquityInDepositAsset({
address: vault.address,
vault: vaultInstance,
factorUnrealizedPNL: true,
});
return Number(token_tvl);
} catch (error) {
console.error(`Error fetching current TVL for vault ${vault.name}:`, error);
return 0;
}
}


/**
* Main TVL calculation function, handling both historical and current data.
* @param {object} api - API object to aggregate TVL data.
*/
async function tvl(api) {
const queryDate = new Date(api.timestamp * 1000);
queryDate.setHours(0, 0, 0, 0);
const currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);

const isHistorical = queryDate.valueOf() < currentDate.valueOf();

// Fetch historical TVL from Neutral.trade data repository.
if (isHistorical) {
console.log("fetching tvl from historical data repository");
for (const vault of VAULTS) {
const { token_tvl } = await fetchHistoricalTvl(vault, formatDate(queryDate));
api.add(vault.token.mint, token_tvl);
}
}

// Fetch current TVL from the blockchain.
else {
console.log("fetching tvl from current onchain data");
const { client, client_jlpdnv1 } = await initialize();
await Promise.all(
VAULTS.map(async (vault) => {
const _client =
vault.name === "USDC Staking (JLP Delta Neutral)" ? client_jlpdnv1 : client;
const token_tvl = await fetchCurrentTvl(vault, _client);
api.add(vault.token.mint, token_tvl);
})
);
}
}


module.exports = {
start: START_TIMESTAMP,
timetravel: true,
methodology: "The combined TVL and PnL of all public and private vaults.",
solana: { tvl },
};
Loading