assembly/composables/useBalances.ts

311 lines
8.5 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";
2021-08-31 19:23:47 +00:00
import { Network, useNetwork } from "./useNetwork";
2021-09-03 13:59:09 +00:00
import { useWeb3 } from "@instadapp/vue-web3";
2021-07-26 22:19:20 +00:00
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({
2021-08-22 17:35:46 +00:00
user: {
mainnet: {},
2021-10-08 15:49:24 +00:00
polygon: {},
arbitrum: {}
2021-08-22 17:35:46 +00:00
},
dsa: {
mainnet: {},
2021-10-08 15:49:24 +00:00
polygon: {},
arbitrum: {}
2021-08-22 17:35:46 +00:00
}
2021-07-26 22:19:20 +00:00
});
2021-08-01 18:29:41 +00:00
const prices = reactive({
mainnet: {},
2021-10-08 15:49:24 +00:00
polygon: {},
arbitrum: {}
2021-08-01 18:29:41 +00:00
});
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-31 19:23:47 +00:00
const { account, library } = useWeb3();
2021-10-08 15:49:24 +00:00
const { activeNetworkId } = useNetwork();
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.instadapp.io/defi/prices");
prices.polygon = await $axios.$get(
"https://api.instadapp.io/defi/polygon/prices"
);
2021-10-08 15:49:24 +00:00
prices.arbitrum = await $axios.$get(
"https://api.instadapp.io/defi/arbitrum/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:
2021-08-31 19:23:47 +00:00
activeNetworkId.value === Network.Mainnet
? await getBalances(account.value, Network.Mainnet, library.value)
2021-08-18 20:20:45 +00:00
: {},
polygon:
2021-08-31 19:23:47 +00:00
activeNetworkId.value === Network.Polygon
? await getBalances(account.value, Network.Polygon, library.value)
2021-10-08 15:49:24 +00:00
: {},
arbitrum:
activeNetworkId.value === Network.Arbitrum
? await getBalances(account.value, Network.Arbitrum, library.value)
2021-08-18 20:20:45 +00:00
: {}
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:
2021-08-31 19:23:47 +00:00
activeNetworkId.value === Network.Mainnet
2021-08-18 20:20:45 +00:00
? await getBalances(
activeAccount.value.address,
Network.Mainnet,
2021-08-31 19:23:47 +00:00
library.value
2021-08-18 20:20:45 +00:00
)
: {},
polygon:
2021-08-31 19:23:47 +00:00
activeNetworkId.value === Network.Polygon
2021-08-18 20:20:45 +00:00
? await getBalances(
activeAccount.value.address,
Network.Polygon,
2021-08-31 19:23:47 +00:00
library.value
2021-08-18 20:20:45 +00:00
)
2021-10-08 15:49:24 +00:00
: {},
arbitrum:
activeNetworkId.value === Network.Arbitrum
? await getBalances(
activeAccount.value.address,
Network.Arbitrum,
library.value
)
2021-08-18 20:20:45 +00:00
: {}
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-10-08 15:49:24 +00:00
balances[type]?.[network || activeNetworkId.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-31 19:23:47 +00:00
balances[type]?.[network || activeNetworkId.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") => {
2021-08-31 19:23:47 +00:00
const balance = getBalanceByAddress(address, activeNetworkId.value, type);
const price = ensureValue(prices[activeNetworkId.value][address]).toFixed();
2021-08-01 18:29:41 +00:00
return times(balance, price).toFixed();
};
const balanceTotal = computed(() =>
2021-08-31 19:23:47 +00:00
tokens[activeNetworkId.value].allTokens.reduce(
2021-08-01 18:29:41 +00:00
(totalNetWorth, token) =>
plus(totalNetWorth, netWorth(token.address)).toFixed(),
"0"
)
);
const getAssets = (type = "dsa") => {
2021-08-31 19:23:47 +00:00
return tokens[activeNetworkId.value].allTokens
2021-08-01 18:29:41 +00:00
.map(token => ({
...token,
2021-10-08 15:49:24 +00:00
balance: getBalanceByAddress(
token.address,
activeNetworkId.value,
type
),
2021-08-01 18:29:41 +00:00
netWorth: netWorth(token.address, type)
}))
.sort(by("-netWorth"));
};
2021-08-31 19:23:47 +00:00
watch(library, () => {
2021-08-18 20:20:45 +00:00
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] = {
2021-08-23 23:07:53 +00:00
address: tokenAddress,
2021-07-26 22:19:20 +00:00
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) {}
}