Skip to content

Commit

Permalink
Added license & code comments on utils
Browse files Browse the repository at this point in the history
  • Loading branch information
sjuanati committed Mar 16, 2023
1 parent 8f127a3 commit b4c64a8
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 49 deletions.
15 changes: 14 additions & 1 deletion src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
// SPDX-License-Identifier: AGPLv3

// ________ ________ ________
// |\ ____\|\ __ \|\ __ \
// \ \ \___|\ \ \|\ \ \ \|\ \
// \ \ \ __\ \ _ _\ \ \\\ \
// \ \ \|\ \ \ \\ \\ \ \\\ \
// \ \_______\ \__\\ _\\ \_______\
// \|_______|\|__|\|__|\|_______|

// gro protocol - ethereum subgraph: https://github.com/groLabs/gro-subgraph-mainnet

/// @notice Contains all constant values used across the different subgraph functions

import { contracts } from '../../addresses';
import {
Num,
Expand Down Expand Up @@ -82,7 +96,6 @@ export const DEPOSIT_HANDLER_ADDRESSES = [
Address.fromString(contracts.DepositHandlerV2Address),
Address.fromString(contracts.DepositHandlerV3Address),
];

export const WITHDRAWAL_HANDLER_ADDRESSES = [
Address.fromString(contracts.WithdrawHandlerV1Address),
Address.fromString(contracts.WithdrawHandlerV2Address),
Expand Down
27 changes: 24 additions & 3 deletions src/utils/contracts.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
// SPDX-License-Identifier: AGPLv3

// ________ ________ ________
// |\ ____\|\ __ \|\ __ \
// \ \ \___|\ \ \|\ \ \ \|\ \
// \ \ \ __\ \ _ _\ \ \\\ \
// \ \ \|\ \ \ \\ \\ \ \\\ \
// \ \_______\ \__\\ _\\ \_______\
// \|_______|\|__|\|__|\|_______|

// gro protocol - ethereum subgraph: https://github.com/groLabs/gro-subgraph-mainnet

/// @notice Contains contract-related util functions and address conversions

import { contracts } from '../../addresses';
import { Address } from '@graphprotocol/graph-ts';
import { STAKER_ADDRESSES } from '../utils/constants';


// check if Transfer is a deposit or withdrawal
/// @notice Checks if Transfer is a deposit or withdrawal based on from/to addresses
/// @return - True if deposit (from = 0x) or withdrawal (to = 0x)
/// - False otherwise
export const isDepositOrWithdrawal = (
from: Address,
to: Address,
Expand All @@ -13,7 +29,9 @@ export const isDepositOrWithdrawal = (
: false;
}

// check if Transfer comes in or out of a staker contract
/// @notice Checks if Transfer comes from Staker contract
/// @return - True if from or to is a Staker address
/// - False otherwise
export const isStakerTransfer = (
from: Address,
to: Address,
Expand All @@ -23,11 +41,14 @@ export const isStakerTransfer = (
: false;
}

/// @notice Checks if Transfer goes to the GRouter contract
/// @return - True if from to is the GRouter address
/// - False otherwise
export const isTransferToGRouter = (to: Address): bool => {
return gRouterAddress.equals(to);
}

// contract addresses
// Contract addresses conversion (from string to Address)
// Gro Protocol
export const gvtAddress = Address.fromString(contracts.GvtAddress);
export const pwrdAddress = Address.fromString(contracts.PwrdAddress);
Expand Down
4 changes: 2 additions & 2 deletions src/utils/staker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
} from '@graphprotocol/graph-ts';


/// @notice Gets the current reward debt for a given user & pool from the Staker
/// @notice Gets the current reward debt from the Staker for a given user & pool
/// @param stakerContract the staker contract
/// @param userAddress the user address
/// @param poolId the pool identifier
Expand All @@ -43,7 +43,7 @@ export function getRewardDebt<T>(
Address.fromBytes(userAddress),
);
if (userInfo.reverted) {
const data = `on userAddress: {}, poolId: {}`;
const data = `on userAddress: {} poolId: {}`;
log.error(
`getRewardDebt(): try_userInfo reverted for Staker ${data} in /utils/staker.ts`,
[userAddress.toHexString(), poolId.toString()]
Expand Down
34 changes: 19 additions & 15 deletions src/utils/strats.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
// SPDX-License-Identifier: AGPLv3

// ________ ________ ________
// |\ ____\|\ __ \|\ __ \
// \ \ \___|\ \ \|\ \ \ \|\ \
// \ \ \ __\ \ _ _\ \ \\\ \
// \ \ \|\ \ \ \\ \\ \ \\\ \
// \ \_______\ \__\\ _\\ \_______\
// \|_______|\|__|\|__|\|_______|

// gro protocol - ethereum subgraph: https://github.com/groLabs/gro-subgraph-mainnet

/// @notice Contains all static data referring to Convex strategies plus
/// strategy-related util functions
/// @dev Most of the names/descriptions are to be used in the front-end

import { TOKEN as Token} from '../utils/constants';
import { gVaultAddress } from '../utils/contracts';
import { Strategy as Strat } from '../types/strats';
import {
GVault,
GVault__strategiesResult,
} from '../../generated/GVault/GVault';
import {
log,
Bytes,
Address,
ethereum,
} from '@graphprotocol/graph-ts';


/// @notice Contains the static data from all Convex strategies
export const getGVaultStrategies = (): Strat[] => {
const strats = [
new Strat(
Expand Down Expand Up @@ -84,22 +95,15 @@ export const getGVaultStrategies = (): Strat[] => {
return strats;
}

export const getTotalAssetsStrat3crv = (
strategyAddress: Address,
): ethereum.CallResult<GVault__strategiesResult> => {
const contract = GVault.bind(gVaultAddress);
const assets = contract.try_strategies(strategyAddress);
return assets;
}

/// @return strategy address given a queue identifier
export const getStrategyAddressByQueueId = (queueId: number): Bytes => {
const strats = getGVaultStrategies();
for (let i = 0; i < strats.length; i++) {
if (strats[i].queueId == queueId) {
return strats[i].id;
}
}
log.error('getStrategyAddressByQueueId(): strategy by id not found in /utils/strats.ts', []);
log.error('getStrategyAddressByQueueId(): strategy by queue id not found in /utils/strats.ts', []);
return Address.zero();
}

Expand Down
87 changes: 59 additions & 28 deletions src/utils/tokens.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
// SPDX-License-Identifier: AGPLv3

// ________ ________ ________
// |\ ____\|\ __ \|\ __ \
// \ \ \___|\ \ \|\ \ \ \|\ \
// \ \ \ __\ \ _ _\ \ \\\ \
// \ \ \|\ \ \ \\ \\ \ \\\ \
// \ \_______\ \__\\ _\\ \_______\
// \|_______|\|__|\|__|\|_______|

// gro protocol - ethereum subgraph: https://github.com/groLabs/gro-subgraph-mainnet

/// @notice Contains token-related utility functions

import { Gvt } from '../../generated/Gvt/Gvt';
import { UniswapV2Pair } from '../../generated/UniswapV2PairGvtGro/UniswapV2Pair';
import {
AccessControlledOffchainAggregator as ChainlinkAggregator
} from '../../generated/ChainlinkAggregator/AccessControlledOffchainAggregator';
import {
gvtAddress,
uni2UsdcWethAddress,
chainlinkDaiUsdAddress,
chainlinkUsdcUsdAddress,
chainlinkUsdtUsdAddress,
} from '../utils/contracts';
import {
NUM,
ADDR,
Expand All @@ -22,6 +29,13 @@ import {
Address,
BigDecimal,
} from '@graphprotocol/graph-ts';
import {
gvtAddress,
uni2UsdcWethAddress,
chainlinkDaiUsdAddress,
chainlinkUsdcUsdAddress,
chainlinkUsdtUsdAddress,
} from '../utils/contracts';


// TEMPORARILY COPIED HERE (generates exception otherwise)
Expand All @@ -41,28 +55,28 @@ export const initPrice = (): Price => {
return price;
}

/// @return gvt or pwrd depending on the <isPwrd> parameter
/// @dev <isPwrd>: the deposit or withdrawal field that indicates the token type:
/// - For DepositHandler & WithdrawHandler: field `pwrd` (true: pwrd, false: gvt)
/// - For GRouter: field `tranche` (true: pwrd, false: gvt)
export const getGroToken = (isPwrd: bool): string => {
return (isPwrd)
? Token.PWRD
: Token.GVT;
}

export const getGvtPrice = (): BigDecimal => {
const contract = Gvt.bind(gvtAddress);
const pricePerShare = contract.try_getPricePerShare();
if (pricePerShare.reverted) {
log.error('getGvtPrice(): try_getPricePerShare() reverted in /utils/tokens.ts', []);
return NUM.ZERO;
} else {
return tokenToDecimal(pricePerShare.value, 18, DECIMALS);
}
}

// Retrieves price per share for a given token
/// @return price per share given a token type
export const getPricePerShare = (token: string): BigDecimal => {
let price: BigDecimal = NUM.ZERO;
if (token === Token.GVT) {
price = getGvtPrice();
const contract = Gvt.bind(gvtAddress);
const pricePerShare = contract.try_getPricePerShare();
if (pricePerShare.reverted) {
log.error('getPricePerShare(): try_getPricePerShare() reverted in /utils/tokens.ts', []);
return price;
} else {
return tokenToDecimal(pricePerShare.value, 18, DECIMALS);
}
} else if (token === Token.GRO) {
const _price = initPrice();
price = _price.gro;
Expand All @@ -79,6 +93,7 @@ export const getPricePerShare = (token: string): BigDecimal => {
return price;
}

/// @return token type given a pool identifier
export const getTokenByPoolId = (
poolId: i32,
): string => {
Expand All @@ -102,21 +117,28 @@ export const getTokenByPoolId = (
}
}

// Converts a BigInt into a N-decimal BigDecimal
/// @notice Converts a BigInt to BigDecimal
/// @param amount the amount to be converted
/// @param factor the base conversion factor (1eN)
/// @param decimals the decimal precision (normally 7)
/// @return the converted BigDecimal
export function tokenToDecimal(
amount: BigInt,
precision: i32,
factor: i32,
decimals: i32,
): BigDecimal {
const scale = BigInt.fromI32(10)
.pow(precision as u8)
.pow(factor as u8)
.toBigDecimal();
return amount.toBigDecimal()
.div(scale)
.truncate(decimals);
}

// converts a Bigdecimal coin amount to USD value
/// @notice Converts an stablecoin amount to its USD value
/// @param coin the coin type (dai, usdc, usdt)
/// @param amount the coin amount
/// @return the USD value
export const amountToUsd = (
coin: string,
amount: BigDecimal
Expand All @@ -131,7 +153,12 @@ export const amountToUsd = (
return amount.times(price).truncate(DECIMALS);
}

// returns the USD value in BigInt of a given stablecoin amount (used for G2 withdrawals)
/// @notice Gives the USD value in BigInt for a given stablecoin amount
/// (dai, usdc, usdt or 3crv)
/// @dev Only used for G2 withdrawals
/// @param tokenIndex the <tokenIndex> field from GRouter withdrawals
/// @param amount the coin amount
/// @return the USD value in BigInt
export const getUSDAmountOfShare = (
tokenIndex: number,
coinAmount: BigDecimal
Expand All @@ -152,7 +179,10 @@ export const getUSDAmountOfShare = (
return BigInt.fromString(usdAmount.truncate(0).toString());
}

// returns the USD value of a given stablecoin (DAI, USDC or USDT)
/// @notice Gives the USD value in BigDecimal for a given stablecoin type
/// (dai, usdc, usdt) based on Chainlink prices
/// @param token the token type
/// @return the USD value in BigDecimal
export function getStablecoinUsdPrice(token: string): BigDecimal {
const chainlinkAddress: Address = (token === Token.DAI)
? chainlinkDaiUsdAddress
Expand All @@ -172,6 +202,8 @@ export function getStablecoinUsdPrice(token: string): BigDecimal {
}
}

/// @return the USDC value of a WETH
/// @dev Using USDC instead of USD to avoid one more call to Chainlink
export function getWethPrice(): BigDecimal {
const contract = UniswapV2Pair.bind(uni2UsdcWethAddress);
const reserves = contract.try_getReserves();
Expand All @@ -181,8 +213,7 @@ export function getWethPrice(): BigDecimal {
} else {
const usdcReserve = tokenToDecimal(reserves.value.get_reserve0(), 6, DECIMALS);
const wethReserve = tokenToDecimal(reserves.value.get_reserve1(), 18, DECIMALS);
// TODO: update WETH price
// TODO: chainlink to calc the USD price of USDC.
// OPTIONAL: chainlink to calc the USD price of USDC.
const price = usdcReserve.div(wethReserve).truncate(DECIMALS);
return price;
}
Expand Down
2 changes: 2 additions & 0 deletions src/utils/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import { Tx } from '../types/tx';


/// @return transaction data in a structured way
/// @dev only used for Balancer pool to show descriptive logs
export function getTxData<T>(ev: T): Tx {
const tx = new Tx(
'on hash {}, block {}, timestamp {} contract {}',
Expand Down

0 comments on commit b4c64a8

Please sign in to comment.