Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
65 changes: 51 additions & 14 deletions src/cached.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,66 @@
import memoize from "memoizee";
import {IDict, IExtendedPoolDataFromApi, INetworkName, IPoolType} from "./interfaces.js";
import {uncached_getAllPoolsFromApi, uncached_getCrvApyFromApi, uncached_getUsdPricesFromApi} from './external-api.js'
import {curve} from "./curve";

const _getCachedData = memoize(
async (network: INetworkName, isLiteChain: boolean) => {
const poolsDict = await uncached_getAllPoolsFromApi(network, isLiteChain);
const poolLists = Object.values(poolsDict)
const usdPrices = uncached_getUsdPricesFromApi(poolLists);
const crvApy = uncached_getCrvApyFromApi(poolLists)
return { poolsDict, poolLists, usdPrices, crvApy };
},
{
promise: true,
maxAge: 5 * 60 * 1000, // 5m
primitive: true,
/**
* Memoizes a function that returns a promise.
* Custom function instead of `memoizee` because we want to be able to set the cache manually based on server data.
* @param fn The function that returns a promise and will be memoized
* @param maxAge The maximum age of the cache in milliseconds
* @returns A memoized `fn` function that includes a `set` method to set the cache manually
*/
const memoize = <TResult, TParams extends any[], TFunc extends (...args: TParams) => Promise<TResult>>(fn: TFunc, {maxAge}: {
maxAge: number
}) => {
const cache: Record<string, Promise<TResult>> = {};
const cachedFn = async (...args: TParams): Promise<TResult> => {
const key = JSON.stringify(args);
if (key in cache) {
return cache[key];
}
const promise = fn(...args);
cache[key] = promise;
try {
const result = await promise;
setTimeout(() => delete cache[key], maxAge);
return result;
} catch (e) {
delete cache[key];
throw e;
}
};
cachedFn.set = (result: TResult, ...args: TParams) => {
const key = JSON.stringify(args);
setTimeout(() => delete cache[key], maxAge);
cache[key] = Promise.resolve(result);
}
)
return cachedFn as TFunc & { set: (result: TResult, ...args: TParams) => void };
}

function createCache(poolsDict: Record<"main" | "crypto" | "factory" | "factory-crvusd" | "factory-eywa" | "factory-crypto" | "factory-twocrypto" | "factory-tricrypto" | "factory-stable-ng", IExtendedPoolDataFromApi>) {
const poolLists = Object.values(poolsDict)
const usdPrices = uncached_getUsdPricesFromApi(poolLists);
const crvApy = uncached_getCrvApyFromApi(poolLists)
return {poolsDict, poolLists, usdPrices, crvApy};
}

const _getCachedData = memoize(async (network: INetworkName, isLiteChain: boolean) =>
createCache(await uncached_getAllPoolsFromApi(network, isLiteChain)), { maxAge: 1000 * 60 * 5 /* 5 minutes */ })

export const _getPoolsFromApi =
async (network: INetworkName, poolType: IPoolType, isLiteChain = false): Promise<IExtendedPoolDataFromApi> => {
const {poolsDict} = await _getCachedData(network, isLiteChain);
return poolsDict[poolType]
}

export const _setPoolsFromApi =
(network: INetworkName, isLiteChain: boolean, data: Record<IPoolType, IExtendedPoolDataFromApi>): void =>
_getCachedData.set(
createCache(data),
network,
isLiteChain
)

export const _getAllPoolsFromApi = async (network: INetworkName, isLiteChain = false): Promise<IExtendedPoolDataFromApi[]> => {
const {poolLists} = await _getCachedData(network, isLiteChain);
return poolLists
Expand Down
19 changes: 17 additions & 2 deletions src/curve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@
import { getFactoryPoolsDataFromApi } from "./factory/factory-api.js";
import { getCryptoFactoryPoolData } from "./factory/factory-crypto.js";
import { getTricryptoFactoryPoolData } from "./factory/factory-tricrypto.js";
import {IPoolData, IDict, ICurve, IChainId, IFactoryPoolType, Abi, INetworkConstants} from "./interfaces";
import {
IPoolData,
IDict,
ICurve,
IChainId,
IFactoryPoolType,
Abi,
INetworkConstants,
IPoolType,
IExtendedPoolDataFromApi,
} from "./interfaces";
import ERC20Abi from './constants/abis/ERC20.json' with { type: 'json' };
import cERC20Abi from './constants/abis/cERC20.json' with { type: 'json' };
import yERC20Abi from './constants/abis/yERC20.json' with { type: 'json' };
Expand Down Expand Up @@ -56,6 +66,7 @@
import { L2Networks } from "./constants/L2Networks.js";
import { getTwocryptoFactoryPoolData } from "./factory/factory-twocrypto.js";
import {getNetworkConstants} from "./utils.js";
import {_setPoolsFromApi} from "./cached";


export const OLD_CHAINS = [1, 10, 56, 100, 137, 250, 1284, 2222, 8453, 42161, 42220, 43114, 1313161554]; // these chains have non-ng pools
Expand Down Expand Up @@ -147,7 +158,7 @@
async init(
providerType: 'JsonRpc' | 'Web3' | 'Infura' | 'Alchemy' | 'NoRPC',
providerSettings: { url?: string, privateKey?: string, batchMaxCount? : number } | { externalProvider: ethers.Eip1193Provider } | { network?: Networkish, apiKey?: string } | 'NoRPC',
options: { gasPrice?: number, maxFeePerGas?: number, maxPriorityFeePerGas?: number, chainId?: number } = {} // gasPrice in Gwei
options: { gasPrice?: number, maxFeePerGas?: number, maxPriorityFeePerGas?: number, chainId?: number, poolsData?: Record<IPoolType, IExtendedPoolDataFromApi> } = {} // gasPrice in Gwei
): Promise<void> {
// @ts-ignore
this.provider = null;
Expand Down Expand Up @@ -209,7 +220,7 @@
} else if (!providerSettings.url?.startsWith("https://rpc.gnosischain.com")) {
try {
this.signer = await this.provider.getSigner();
} catch (e) {

Check warning on line 223 in src/curve.ts

View workflow job for this annotation

GitHub Actions / test

'e' is defined but never used
this.signer = null;
}
}
Expand Down Expand Up @@ -286,7 +297,7 @@
if (this.signer) {
try {
this.signerAddress = await this.signer.getAddress();
} catch (err) {

Check warning on line 300 in src/curve.ts

View workflow job for this annotation

GitHub Actions / test

'err' is defined but never used
this.signer = null;
}
} else {
Expand All @@ -294,6 +305,10 @@
}

this.feeData = { gasPrice: options.gasPrice, maxFeePerGas: options.maxFeePerGas, maxPriorityFeePerGas: options.maxPriorityFeePerGas };
if (options.poolsData) {
_setPoolsFromApi(this.constants.NETWORK_NAME, this.isLiteChain, options.poolsData);
}

await this.updateFeeData();

for (const pool of Object.values({...this.constants.POOLS_DATA, ...this.constants.LLAMMAS_DATA})) {
Expand Down
Loading