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

[PFT-709] Add function to get referral data for partners #39

Merged
merged 3 commits into from
Apr 3, 2024
Merged
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@parifi/sdk",
"version": "0.1.10",
"version": "0.1.11",
"description": "Parifi SDK with common utility functions",
"files": [
"dist",
Expand Down
29 changes: 29 additions & 0 deletions src/common/subgraphMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Position,
PriceFeedSnapshot,
PythData,
Referral,
Token,
Vault,
VaultPosition,
Expand Down Expand Up @@ -294,3 +295,31 @@ export const mapVaultsArrayToInterface = (response: any): Vault[] | undefined =>
throw error;
}
};

export const mapReferralDataToInterface = (response: any): Referral | undefined => {
try {
return {
id: response.id,
partner: response.partner ? mapSubgraphResponseToAccountInterface(response.partner) : undefined,
referredUser: response.partner ? mapSubgraphResponseToAccountInterface(response.partner) : undefined,
sizeInUsd: response.sizeInUsd,
timestamp: response.timestamp,
txHash: response.txHash,
referralRewardsInUsd: response.referralRewardsInUsd,
};
} catch (error) {
console.log('Error while mapping data', error);
throw error;
}
};

export const mapReferralsArrayToInterface = (response: any): Referral[] | undefined => {
try {
return response.referrals.map((referral: Referral) => {
return mapReferralDataToInterface(referral);
});
} catch (error) {
console.log('Error while mapping data', error);
throw error;
}
};
33 changes: 31 additions & 2 deletions src/interfaces/subgraphTypes.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
//// NOTE: All fields from the subgraph interfaces have their type as string
//// and are marked as optional. This is because the logic to fetch these data might
//// differ based on the requirement or function, and only required fields are fetched
//// with queries to keep it concise and avoid fetching unnecessary data.

////////////////////////////////////////////////////////////////
//////////////////// ENUMS //////////////////////////////
////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -51,10 +56,10 @@ export interface Account {
referralFeesInUsd?: string;

// " Total Realized P&L from Positions in USD "
totalRealizedPnlPositions: string
totalRealizedPnlPositions?: string;

// " Total Realized P&L from Vaults in USD "
totalRealizedPnlVaults: string
totalRealizedPnlVaults?: string;
}

////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -525,3 +530,27 @@ export interface VaultPosition {
export interface VaultPositionsResponse {
vaultPositions: VaultPosition[];
}

// Subgraph interface for partner referrals
export interface Referral {
// " Partner (Referrer) address + Referred address + log Index "
id?: string;

// " Partner (Referrer) address that referred another user "
partner?: Account;

// " Referred user - User that was referred by the partner"
referredUser?: Account;

// " Position Size in USD "
sizeInUsd?: string;

// " Timestamp "
timestamp?: string;

// " Transaction hash of the create position tx for user referral "
txHash?: string;

// " Referral rewards in USD "
referralRewardsInUsd?: string;
}
25 changes: 23 additions & 2 deletions src/subgraph/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { getAllOrdersByUserAddress, getAllPendingOrders, getOrderById, getPythPriceIdsForOrderIds } from './orders';
import {
getAllOrdersByUserAddress,
getAllPendingOrders,
getOrderById,
getPythPriceIdsForOrderIds,
getReferralDataForPartner,
} from './orders';
import { PythConfig, RpcConfig, SubgraphConfig } from '../interfaces/classConfigs';
import {
getAllPositionsByUserAddress,
Expand All @@ -13,7 +19,7 @@ import {
getTotalUnrealizedPnlInUsd,
} from './positions';
import { getAllMarketsFromSubgraph, getMarketById } from './markets';
import { Market, Order, Position, Vault } from '../interfaces/subgraphTypes';
import { Market, Order, Position, Referral, Vault } from '../interfaces/subgraphTypes';
import { Chain } from '@parifi/references';
import request, { GraphQLClient } from 'graphql-request';
import { getPublicSubgraphEndpoint } from './common';
Expand All @@ -22,6 +28,7 @@ import {
getTotalPoolsValue,
getUserTotalPoolsValue,
getUserVaultDataByChain,
getVaultApr,
getVaultDataByChain,
} from './vaults';
import { Pyth } from '../pyth';
Expand Down Expand Up @@ -222,4 +229,18 @@ export class Subgraph {
const subgraphEndpoint = this.getSubgraphEndpoint(this.rpcConfig.chainId);
return await getUserTotalPoolsValue(userAddress, this.rpcConfig.chainId, subgraphEndpoint, this.pyth.pythClient);
}

public async getVaultApr(vaultId: string): Promise<{ apr7Days: Decimal; apr30Days: Decimal; aprAllTime: Decimal }> {
const subgraphEndpoint = this.getSubgraphEndpoint(this.rpcConfig.chainId);
return await getVaultApr(subgraphEndpoint, vaultId);
}

public async getReferralDataForPartner(
partnerAddress: string,
count: number = 20,
skip: number = 0,
): Promise<Referral[]> {
const subgraphEndpoint = this.getSubgraphEndpoint(this.rpcConfig.chainId);
return await getReferralDataForPartner(subgraphEndpoint, partnerAddress, count, skip);
}
}
26 changes: 24 additions & 2 deletions src/subgraph/orders/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { request } from 'graphql-request';
import { Order } from '../../interfaces/subgraphTypes';
import { Order, Referral } from '../../interfaces/subgraphTypes';
import {
fetchOrdersByIdQuery,
fetchOrdersByUserQuery,
fetchPartnerRewards,
fetchPendingOrdersQuery,
fetchPriceIdsFromOrderIdsQuery,
} from './subgraphQueries';
import { mapOrdersArrayToInterface, mapSingleOrderToInterface } from '../../common/subgraphMapper';
import {
mapOrdersArrayToInterface,
mapReferralsArrayToInterface,
mapSingleOrderToInterface,
} from '../../common/subgraphMapper';
import { EMPTY_BYTES32, getPriceIdsForCollaterals, getUniqueValuesFromArray } from '../../common';
import { NotFoundError } from '../../error/not-found.error';

Expand Down Expand Up @@ -86,3 +91,20 @@ export const getPythPriceIdsForOrderIds = async (subgraphEndpoint: string, order
throw error;
}
};

// Returns the referral data of a partner
export const getReferralDataForPartner = async (
subgraphEndpoint: string,
partnerAddress: string,
count: number = 20,
skip: number = 0,
): Promise<Referral[]> => {
try {
const query = fetchPartnerRewards(partnerAddress.toLowerCase(), count, skip);
const subgraphResponse = await request(subgraphEndpoint, query);
const referrals: Referral[] = mapReferralsArrayToInterface(subgraphResponse) ?? [];
return referrals;
} catch (error) {
throw error;
}
};
20 changes: 20 additions & 0 deletions src/subgraph/orders/subgraphQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,23 @@ export const fetchPriceIdsFromOrderIdsQuery = (orderIds: string[]) =>
}
}
`;

export const fetchPartnerRewards = (partnerAddress: string, count: number = 20, skip: number = 0) => gql`
{
referrals(
first: ${count}
skip: ${skip}
orderBy: timestamp
orderDirection: desc
where: { partner: "${partnerAddress}" }
) {
id
partner { id }
referredUser { id }
sizeInUsd
timestamp
txHash
referralRewardsInUsd
}
}
`;
60 changes: 54 additions & 6 deletions src/subgraph/vaults/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import { request } from 'graphql-request';
import { Vault, VaultPositionsResponse } from '../../interfaces';
import { fetchAllVaultsQuery, fetchUserAllVaultsQuery } from './subgraphQueries';
import { fetchAllVaultsQuery, fetchUserAllVaultsQuery, fetchVaultAprDetails } from './subgraphQueries';
import { mapVaultsArrayToInterface } from '../../common/subgraphMapper';
import { NotFoundError } from '../../error/not-found.error';
import { Chain as SupportedChain, availableVaultsPerChain } from '@parifi/references';

import { PRICE_FEED_DECIMALS, getNormalizedPriceByIdFromPriceIdArray } from '../../common';
import { DECIMAL_ZERO, PRICE_FEED_DECIMALS, getNormalizedPriceByIdFromPriceIdArray } from '../../common';
import Decimal from 'decimal.js';
import { getLatestPricesFromPyth, normalizePythPriceForParifi } from '../../pyth/pyth';
import { AxiosInstance } from 'axios';

// const matchChain: Record<SupportedChain, Chain> = {
// [SupportedChain.ARBITRUM_SEPOLIA]: arbitrumSepolia,
// };

// Get all vaults from subgraph
export const getAllVaults = async (subgraphEndpoint: string): Promise<Vault[]> => {
try {
Expand Down Expand Up @@ -135,3 +131,55 @@ export const getTotalPoolsValue = async (
const totalPoolValue = data.reduce((a, b) => a + b.totatVaultValue, 0);
return { data, totalPoolValue };
};

export const getVaultApr = async (
subgraphEndpoint: string,
vaultId: string,
): Promise<{ apr7Days: Decimal; apr30Days: Decimal; aprAllTime: Decimal }> => {
// Interface for subgraph response
interface VaultAprInterface {
vaultDailyDatas: {
apr: Decimal;
vault: {
allTimeApr: Decimal;
};
}[];
}

let apr7Days: Decimal = DECIMAL_ZERO;
let apr30Days: Decimal = DECIMAL_ZERO;
let aprAllTime: Decimal = DECIMAL_ZERO;

try {
const subgraphResponse: VaultAprInterface = await request(subgraphEndpoint, fetchVaultAprDetails(vaultId));
console.log(subgraphResponse);
const vaultDatas = subgraphResponse.vaultDailyDatas;

// If no APR data found, return 0;
if (vaultDatas.length == 0) {
return { apr7Days, apr30Days, aprAllTime };
} else {
// Set All Time APR for the vault from response
aprAllTime = vaultDatas[0].vault.allTimeApr;
}

/// Calculate the APR of vault based on timeframe data. If enough data points are not available,
/// the value is set to 0;
for (let index = 0; index < vaultDatas.length; index++) {
const vaultData = vaultDatas[index];

// Do not calculate 7 day APR if less than 7 days of data is available
if (index < 7 && vaultDatas.length >= 7) {
apr7Days = apr7Days.add(vaultData.apr);
}

// Do not calculate 30 day APR if less than 30 days of data is available
if (index < 30 && vaultDatas.length >= 30) {
apr30Days = apr30Days.add(vaultData.apr);
}
}
return { apr7Days: apr7Days.div(7), apr30Days: apr30Days.div(30), aprAllTime: aprAllTime };
} catch (error) {
throw error;
}
};
14 changes: 14 additions & 0 deletions src/subgraph/vaults/subgraphQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,17 @@ query vaultInfo {
}
}
`;

export const fetchVaultAprDetails = (vaultId: string) => gql`
{
vaultDailyDatas(
first: 30
orderBy: startTimestamp
orderDirection: desc
where: { vault: "${vaultId}" }
) {
vault { allTimeApr }
apr
}
}
`;
8 changes: 8 additions & 0 deletions test/subgraph-tests/orders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,12 @@ describe('Order fetching logic from subgraph', () => {
const { gelatoTaskId: taskId } = await parifiSdk.core.settleOrderUsingGelato(orderId);
console.log('taskId', taskId);
});

it('should return referral data for partner address', async () => {
await parifiSdk.init();
const partnerAddress = '0x30f06f86f107f9523f5b91a8e8aeb602b7b260bd';

const referralData = await parifiSdk.subgraph.getReferralDataForPartner(partnerAddress);
console.log('referralData', referralData);
});
});
Loading
Loading