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

Treasury on Indexers side #100

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion indexers/enterprise-stats/src/dao/getDaoAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { contractQuery } from "chain/lcd"
import { enterprise, enterprise_factory } from "types/contracts";
import { Dao } from "./Dao";
import { getAssetPrice } from "chain/getAssetPrice";
import { getDaoTotalStakedAmount } from "./getDaoTotalStakedAmount";
import { getDaoTotalStakedAmount } from "../../../enterprise/src/treasury/getDaoTotalStakedAmount";
import Big from "big.js";

const toAsset = (response: enterprise.AssetInfoBaseFor_Addr | enterprise_factory.AssetInfoBaseFor_Addr): Asset | undefined => {
Expand Down
2 changes: 1 addition & 1 deletion indexers/enterprise-stats/src/dao/getNFTDaoStakedValue.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Dao } from "./Dao"
import { getDaoTotalStakedAmount } from "./getDaoTotalStakedAmount"
import { getDaoTotalStakedAmount } from "../../../enterprise/src/treasury/getDaoTotalStakedAmount"
import { getNFTCollectionFloorPrice } from "chain/getNftCollectionFloorPrice"

export const getNFTDaoStakedValue = async (dao: Pick<Dao, 'address' | 'membershipContractAddress'>) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getAssetInfo } from "chain/getAssetInfo"
import { Dao } from "./Dao"
import { getDaoTotalStakedAmount } from "./getDaoTotalStakedAmount"
import { getDaoTotalStakedAmount } from "../../../enterprise/src/treasury/getDaoTotalStakedAmount"
import { getAssetPrice } from "chain/getAssetPrice"
import { Asset, AssetWithPrice } from "chain/Asset"

Expand Down
19 changes: 19 additions & 0 deletions indexers/enterprise/src/chain/Asset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
type AssetType = 'cw20' | 'native'

export interface Asset {
type: AssetType
id: string
}

export interface AssetInfo {
name: string
symbol?: string
decimals: number
icon?: string
}

export type AssetWithInfoAndBalance = Asset & AssetInfo & { balance: string }

export const areSameAsset = (a: Asset, b: Asset) => {
return a.type === b.type && a.id === b.id
}
8 changes: 8 additions & 0 deletions indexers/enterprise/src/chain/NFT.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export interface NFT {
address: string;
id: string;
}

export interface NFTWithPrice extends NFT {
usd: number;
}
1 change: 1 addition & 0 deletions indexers/enterprise/src/chain/NetworkName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type NetworkName = 'testnet' | 'mainnet'
5 changes: 5 additions & 0 deletions indexers/enterprise/src/chain/fromChainAmount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Big } from "big.js";

export const fromChainAmount = (amount: string | number, decimals: number) => {
return Big(amount).div(Math.pow(10, decimals)).toNumber()
}
36 changes: 36 additions & 0 deletions indexers/enterprise/src/chain/getAssetBalance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Asset } from "./Asset"
import { contractQuery, getBankBalance } from "./lcd"
import memoize from 'memoizee'

interface GetAssetBalance {
asset: Asset
address: string
}

interface CW20BalanceResponse {
balance?: string
}

export const getAssetBalance = memoize(async ({ asset, address }: GetAssetBalance) => {
const { id, type } = asset

if (type === 'native') {
const coins = await getBankBalance(address)
if (!coins) return '0'

const coin = coins.get(asset.id);

return coin?.amount?.toString() ?? '0'
}

const { balance } = await contractQuery<CW20BalanceResponse>(
id,
{
balance: {
address,
},
}
);

return balance ?? '0'
})
47 changes: 47 additions & 0 deletions indexers/enterprise/src/chain/getAssetInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Asset, AssetInfo } from 'chain/Asset';
import { getAssetsInfo } from './getAssetsInfo';
import { contractQuery } from './lcd';
import { NetworkName } from './NetworkName';

interface CW20TokenInfoResponse {
name: string;
symbol: string;
decimals: number;
total_supply: string;
}

interface GetAssetInfoParams {
asset: Asset;
networkName: NetworkName
}

export const getAssetInfo = async ({ asset: { id, type }, networkName }: GetAssetInfoParams): Promise<AssetInfo> => {
if (type === 'cw20') {
const { name, symbol, decimals } = await contractQuery<CW20TokenInfoResponse>(id, {
token_info: {},
});

return {
name,
symbol,
decimals,
};
}

if (id === 'uluna') {
return {
name: 'LUNA',
symbol: 'LUNA',
icon: 'https://assets.terra.money/icon/svg/Luna.svg',
decimals: 6,
};
}

const assets = await getAssetsInfo(networkName);
const asset = assets.find((asset) => asset.id === id);
if (asset) {
return asset
}

throw new Error(`Asset with id=${id} not found`);
};
8 changes: 8 additions & 0 deletions indexers/enterprise/src/chain/getAssetPrice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Asset } from './Asset'
import { getPricesOfLiquidAssets } from './getPricesOfLiquidAssets'

export const getAssetPrice = async (asset: Asset): Promise<number> => {
const prices = await getPricesOfLiquidAssets()

return prices[asset.id] || 0
}
50 changes: 50 additions & 0 deletions indexers/enterprise/src/chain/getAssetsInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { NetworkName } from '@terra-money/apps/hooks';
import { assertDefined } from '@terra-money/apps/utils';
import axios from 'axios';
import { AssetInfo } from 'chain/Asset';
import { memoize } from 'utils/memoize';

const TFM_ASSETS_INFO_URL = 'https://api-terra2.tfm.com/tokens';

const TFL_ASSETS_INFO_URL = 'https://assets.terra.money/ibc/tokens.json'

interface TFMAssetInfo {
contract_addr: string;
decimals: number;
name: string;
symbol: string;
}

interface TFLAssetInfo {
denom: string;
sybmol?: string;
name: string;
icon: string;
decimals?: number;
}

type TFLAssetsInfo = Record<NetworkName, Record<string, TFLAssetInfo>>

export const getAssetsInfo = memoize(async (network: NetworkName = 'mainnet') => {
const { data: tflData } = await axios.get<TFLAssetsInfo>(TFL_ASSETS_INFO_URL);
const assets: Array<AssetInfo & { id: string }> = Object.values(tflData[network]).filter(asset => asset.decimals).map(info => ({
name: info.name,
symbol: info.sybmol,
decimals: assertDefined(info.decimals),
icon: info.icon,
id: info.denom,
}))

if (network === 'mainnet') {
const { data: tfmData } = await axios.get<TFMAssetInfo[]>(TFM_ASSETS_INFO_URL);
const tfmAssets = tfmData.map(info => ({
name: info.name,
symbol: info.symbol,
decimals: info.decimals,
id: info.contract_addr,
}))
assets.push(...tfmAssets)
}

return assets;
});
19 changes: 19 additions & 0 deletions indexers/enterprise/src/chain/getAssetsPrices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import axios from 'axios'
import memoize from 'memoizee'

const TFM_ASSETS_PRICES_URL = 'https://price.api.tfm.com/tokens/?limit=1500'

type TFMChain = 'osmosis' | 'terra2' | 'juno' | 'terra_classic'

interface TFMTokenInfo {
chain: TFMChain
usd: number
}

type TFMResponse = Record<string, TFMTokenInfo>

export const getAssetsPrices = memoize(async () => {
const { data } = await axios.get<TFMResponse>(TFM_ASSETS_PRICES_URL)

return data
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import memoize from 'memoizee'
import axios from 'axios'
import { getAssetPrice } from './getAssetPrice'
import { getAssetInfo } from './getAssetInfo'
import { fromChainAmount } from './fromChainAmount'

const TFM_NFT_API = 'https://nft-terra2.tfm.dev/graphql'

interface TFMError {
message: string
}

interface TFMFloorPrice {
price?: number
denom?: string
}

interface TFMStatisticContent {
floorPrice: TFMFloorPrice
collectionAddr: string
}

interface TFMResponse {
data: {
collectionTable: {
content: TFMStatisticContent[]
}
},
errors?: TFMError[]
}

const query = `
query MyQuery {
collectionTable(limit: 100000) {
content {
floorPrice
collectionAddr
}
}
}
`

type NFTCollectionFloorPrice = Record<string, number>

const getDataFromTFMCollectionTable = memoize(async () => {
const { data: { data, errors } } = await axios.post<TFMResponse>(TFM_NFT_API, {
query,
operationName: "MyQuery",
variables: null
})

if (errors) {
throw new Error(`Failed to get NFT collections from ${TFM_NFT_API}: ${errors[0]?.message}`)
}

return data.collectionTable.content
})

export const convertCollectionPriceToUsd = async ({ denom, price }: TFMFloorPrice) => {
if (!denom || !price) {
return 0
}

try {
const { decimals } = await getAssetInfo({ id: denom, type: 'native' })

const denomPrice = await getAssetPrice({ id: denom, type: 'native' })

return fromChainAmount(denomPrice, decimals) * price
} catch (err) {
console.error(`Error getting price of a denom=${denom}`, err)
}

return 0
}

export const getFloorPricesOfSupportedNFTCollections = memoize(async () => {
const data = await getDataFromTFMCollectionTable()

const record: NFTCollectionFloorPrice = {}

await Promise.all(data.map(async ({ collectionAddr, floorPrice }) => {
record[collectionAddr] = await convertCollectionPriceToUsd(floorPrice)
}))

return record
})

export const getSupportedNFTCollections = memoize(async () => {
const data = await getDataFromTFMCollectionTable()

return new Set(data.map(({ collectionAddr }) => collectionAddr))
})
15 changes: 15 additions & 0 deletions indexers/enterprise/src/chain/getNFTPrice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { NFT } from "./NFT";
import { getNFTCollectionFloorPrice } from "./getNftCollectionFloorPrice";
import { getPricesOfNftsInCollection } from "./getPricesOfNftsInCollection";

export const getNFTPrice = async (nft: NFT): Promise<number | null> => {
try {
const prices = await getPricesOfNftsInCollection(nft.address)

return prices[nft.id] || 0
} catch (err) {
console.error(`Error getting price for NFT collection=${nft.address} id=${nft.id}`, err.toString())
}

return getNFTCollectionFloorPrice(nft.address)
}
8 changes: 8 additions & 0 deletions indexers/enterprise/src/chain/getNftCollectionFloorPrice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import memoize from 'memoizee'
import { getFloorPricesOfSupportedNFTCollections } from './getFloorPricesOfSupportedNFTCollections';

export const getNFTCollectionFloorPrice = memoize(async (address: string): Promise<number | null> => {
const record = await getFloorPricesOfSupportedNFTCollections()

return record[address]
})
33 changes: 33 additions & 0 deletions indexers/enterprise/src/chain/getNftIds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { contractQuery } from "./lcd";

interface GetNftIdsParams {
collection: string
owner: string
}

type NftIdsResponse = {
ids?: string[];
tokens?: string[];
};

export const getNftIds = async ({ collection, owner }: GetNftIdsParams) => {
const fetchNftIds = async (startAfter?: string): Promise<string[]> => {
const response = await contractQuery<NftIdsResponse>(collection, {
tokens: { owner, start_after: startAfter },
});

const ids = response.ids ?? response.tokens ?? []

if (!ids.length) {
return [];
}

const lastId = ids[ids.length - 1];
const nextIds = await fetchNftIds(lastId);
return [...(ids || []), ...nextIds];
};

const ids = await fetchNftIds();

return ids
}
Loading