assembly/composables/useBalances.ts

280 lines
7.7 KiB
TypeScript
Raw Normal View History

2021-08-01 18:29:41 +00:00
import {
computed,
reactive,
onMounted,
2021-08-18 20:20:45 +00:00
useContext,
watch
2021-08-01 18:29:41 +00:00
} from "@nuxtjs/composition-api";
2021-07-26 22:19:20 +00:00
import BigNumber from "bignumber.js";
import abis from "~/constant/abis";
import addresses from "~/constant/addresses";
import tokens from "~/constant/tokens";
import uniPoolTokens from "~/constant/uniPoolTokens";
import { useDSA } from "./useDSA";
import { Network } from "./useNetwork";
import { useWeb3 } from "./useWeb3";
import Web3 from "web3";
import { AbiItem } from "web3-utils";
import { useToken } from "./useToken";
2021-08-01 18:29:41 +00:00
import { useBigNumber } from "./useBigNumber";
import { useSorting } from "./useSorting";
2021-07-26 22:19:20 +00:00
const balances = reactive({
user: null,
dsa: null
});
2021-08-01 18:29:41 +00:00
const prices = reactive({
mainnet: {},
polygon: {}
});
2021-07-26 22:19:20 +00:00
export function useBalances() {
2021-08-01 18:29:41 +00:00
const { $axios } = useContext();
const { times, plus, ensureValue } = useBigNumber();
2021-08-18 20:20:45 +00:00
const { account, networkName, web3 } = useWeb3();
2021-07-26 22:19:20 +00:00
const { activeAccount } = useDSA();
const { getTokenByKey } = useToken();
2021-08-01 18:29:41 +00:00
const { by } = useSorting();
2021-07-26 22:19:20 +00:00
2021-08-01 18:29:41 +00:00
onMounted(async () => {
prices.mainnet = await $axios.$get("https://api.internal.instadapp.io/defi/prices");
2021-08-01 18:29:41 +00:00
prices.polygon = await $axios.$get(
"https://api.internal.instadapp.io/defi/polygon/prices"
2021-08-01 18:29:41 +00:00
);
});
2021-07-26 22:19:20 +00:00
const fetchBalances = async (refresh = false) => {
if (!balances.user || refresh) {
2021-08-19 22:12:39 +00:00
if (!account.value) return;
2021-07-26 22:19:20 +00:00
balances.user = {
2021-08-18 20:20:45 +00:00
mainnet:
networkName.value === Network.Mainnet
? await getBalances(account.value, Network.Mainnet, web3.value)
: {},
polygon:
networkName.value === Network.Polygon
? await getBalances(account.value, Network.Polygon, web3.value)
: {}
2021-07-26 22:19:20 +00:00
};
}
if (!balances.dsa || refresh) {
2021-08-19 22:12:39 +00:00
if (!activeAccount.value) return;
2021-07-26 22:19:20 +00:00
balances.dsa = {
2021-08-18 20:20:45 +00:00
mainnet:
networkName.value === Network.Mainnet
? await getBalances(
activeAccount.value.address,
Network.Mainnet,
web3.value
)
: {},
polygon:
networkName.value === Network.Polygon
? await getBalances(
activeAccount.value.address,
Network.Polygon,
web3.value
)
: {}
2021-07-26 22:19:20 +00:00
};
}
};
2021-08-01 18:29:41 +00:00
const getBalanceByKey = (tokenKey, network = null, type = "dsa") => {
return getBalanceByAddress(getTokenByKey(tokenKey)?.address, network, type);
};
const getBalanceByAddress = (address, network = null, type = "dsa") => {
2021-07-26 22:19:20 +00:00
return (
2021-08-01 18:29:41 +00:00
balances[type]?.[network || networkName.value][address]?.balance || "0"
2021-07-26 22:19:20 +00:00
);
};
2021-08-01 18:29:41 +00:00
const getBalanceRawByKey = (tokenKey, network = null, type = "dsa") => {
2021-07-28 21:38:15 +00:00
return (
2021-08-01 18:29:41 +00:00
balances[type]?.[network || networkName.value][
2021-07-28 21:38:15 +00:00
getTokenByKey(tokenKey)?.address
]?.raw || "0"
);
};
2021-08-01 18:29:41 +00:00
const netWorth = (address, type = "dsa") => {
const balance = getBalanceByAddress(address, networkName.value, type);
const price = ensureValue(prices[networkName.value][address]).toFixed();
return times(balance, price).toFixed();
};
const balanceTotal = computed(() =>
tokens[networkName.value].allTokens.reduce(
(totalNetWorth, token) =>
plus(totalNetWorth, netWorth(token.address)).toFixed(),
"0"
)
);
const getAssets = (type = "dsa") => {
return tokens[networkName.value].allTokens
.map(token => ({
...token,
balance: getBalanceByAddress(token.address, networkName.value, type),
netWorth: netWorth(token.address, type)
}))
.sort(by("-netWorth"));
};
2021-08-18 20:20:45 +00:00
watch(web3, () => {
fetchBalances(true);
});
2021-07-26 22:19:20 +00:00
return {
balances,
fetchBalances,
2021-07-28 21:38:15 +00:00
getBalanceByKey,
2021-08-01 18:29:41 +00:00
getBalanceRawByKey,
balanceTotal,
prices,
getAssets
2021-07-26 22:19:20 +00:00
};
}
async function getBalances(
owner,
network: Network,
web3: Web3,
additionalTokens = []
) {
try {
const tokenResolverABI = abis.resolver.balance;
const tokenResolverAddr = addresses[network].resolver.balance;
const tokensArr = tokens[network].allTokens;
const tokensList =
network === Network.Mainnet
? [...tokensArr, ...uniPoolTokens[network].allTokens]
: tokensArr;
let tokensAddrArr = tokensList.map(a => a.address);
const tokenResolverInstance = new web3.eth.Contract(
tokenResolverABI as AbiItem[],
tokenResolverAddr
);
const tokensAddrArrLength = tokensAddrArr.length;
let additionalTokensInfo;
let isNotTokens;
if (additionalTokens && additionalTokens.length) {
additionalTokens = additionalTokens.filter(
token =>
!tokensArr.find(a => a.address.toLowerCase() === token.toLowerCase())
);
}
if (additionalTokens && additionalTokens.length) {
additionalTokensInfo = await getTokensDetails(
additionalTokens,
network,
web3
);
isNotTokens = Object.fromEntries(
additionalTokens
.filter((val, index) => !additionalTokensInfo[index].isToken)
.map(val => [val, { isToken: false }])
);
additionalTokens = additionalTokens.filter(
(val, index) => additionalTokensInfo[index].isToken
);
additionalTokensInfo = additionalTokensInfo.filter(val => val.isToken);
tokensAddrArr = tokensAddrArr.concat(additionalTokens);
}
const tokenBalances = await tokenResolverInstance.methods
.getBalances(owner, tokensAddrArr)
.call();
let tokensBalObj = {};
tokenBalances.forEach((a, i) => {
const tokenAddress = web3.utils.toChecksumAddress(tokensAddrArr[i]);
let tokenData;
if (i < tokensAddrArrLength) {
tokenData = {
...tokensList[i],
decimals: tokensList[i].decimals.toString()
};
} else {
tokenData = additionalTokensInfo[i - tokensAddrArrLength];
}
const { name, symbol, decimals, type, isStableCoin, key } = tokenData;
tokensBalObj[tokenAddress] = {
name,
symbol,
decimals,
type,
isStableCoin,
key,
balance: new BigNumber(a).dividedBy(10 ** tokenData.decimals).toFixed(),
raw: String(a)
};
});
tokensBalObj = { ...tokensBalObj, ...isNotTokens };
return tokensBalObj;
} catch (error) {
return Promise.reject(error);
}
}
const storedTokens = {};
async function getTokensDetails(addressArr, network: Network, web3: Web3) {
try {
const balanceInstance = new web3.eth.Contract(
abis.resolver.balance as AbiItem[],
addresses[network].resolver.balance
);
const result = [];
for (let i = 0; i < addressArr.length; i++) {
let details = tokens[network].getTokenByAddress(addressArr[i]);
if (!details) {
details = uniPoolTokens[network].getTokenByAddress(addressArr[i]);
}
if (!details) {
details = storedTokens[addressArr[i]];
} else {
details.isToken = true;
}
try {
if (!details) {
details = await balanceInstance.methods
.getTokenDetails([addressArr[i]])
.call();
const { name, symbol, decimals, isToken } = details[0];
details = {
name,
symbol,
decimals,
isToken,
type: "token",
isStableCoin: false,
key: symbol.toLowerCase()
};
storedTokens[addressArr[i]] = details;
}
} catch (error) {
if (
error.message &&
error.message === "Returned error: execution reverted"
) {
details = { isToken: false };
} else {
throw error;
}
}
details.address = addressArr[i];
result[i] = details;
}
return result;
} catch (error) {}
}