Skip to content

Commit

Permalink
fix broken adapters
Browse files Browse the repository at this point in the history
  • Loading branch information
g1nt0ki committed Mar 11, 2024
1 parent 10a03ce commit 67f2e9d
Show file tree
Hide file tree
Showing 13 changed files with 147 additions and 91 deletions.
44 changes: 20 additions & 24 deletions projects/augmented-finance/index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
const sdk = require('@defillama/sdk');
const { nullAddress } = require('../helper/unwrapLPs')
const abi = { "inputs": [{ "internalType": "address", "name": "user", "type": "address" }], "name": "getReservesData", "outputs": [{ "components": [{ "internalType": "address", "name": "underlyingAsset", "type": "address" }, { "internalType": "address", "name": "pricingAsset", "type": "address" }, { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "symbol", "type": "string" }, { "internalType": "uint256", "name": "decimals", "type": "uint256" }, { "internalType": "uint256", "name": "baseLTVasCollateral", "type": "uint256" }, { "internalType": "uint256", "name": "reserveLiquidationThreshold", "type": "uint256" }, { "internalType": "uint256", "name": "reserveLiquidationBonus", "type": "uint256" }, { "internalType": "uint256", "name": "reserveFactor", "type": "uint256" }, { "internalType": "bool", "name": "usageAsCollateralEnabled", "type": "bool" }, { "internalType": "bool", "name": "borrowingEnabled", "type": "bool" }, { "internalType": "bool", "name": "stableBorrowRateEnabled", "type": "bool" }, { "internalType": "bool", "name": "isActive", "type": "bool" }, { "internalType": "bool", "name": "isFrozen", "type": "bool" }, { "internalType": "uint128", "name": "liquidityIndex", "type": "uint128" }, { "internalType": "uint128", "name": "variableBorrowIndex", "type": "uint128" }, { "internalType": "uint128", "name": "liquidityRate", "type": "uint128" }, { "internalType": "uint128", "name": "variableBorrowRate", "type": "uint128" }, { "internalType": "uint128", "name": "stableBorrowRate", "type": "uint128" }, { "internalType": "uint40", "name": "lastUpdateTimestamp", "type": "uint40" }, { "internalType": "address", "name": "depositTokenAddress", "type": "address" }, { "internalType": "address", "name": "stableDebtTokenAddress", "type": "address" }, { "internalType": "address", "name": "variableDebtTokenAddress", "type": "address" }, { "internalType": "address", "name": "strategy", "type": "address" }, { "internalType": "bool", "name": "isExternalStrategy", "type": "bool" }, { "internalType": "uint256", "name": "availableLiquidity", "type": "uint256" }, { "internalType": "uint256", "name": "totalPrincipalStableDebt", "type": "uint256" }, { "internalType": "uint256", "name": "averageStableRate", "type": "uint256" }, { "internalType": "uint256", "name": "totalStableDebt", "type": "uint256" }, { "internalType": "uint256", "name": "stableDebtLastUpdateTimestamp", "type": "uint256" }, { "internalType": "uint256", "name": "totalScaledVariableDebt", "type": "uint256" }, { "internalType": "uint256", "name": "priceInEth", "type": "uint256" }], "internalType": "struct IUiPoolDataProvider.AggregatedReserveData[]", "name": "", "type": "tuple[]" }, { "components": [{ "internalType": "address", "name": "underlyingAsset", "type": "address" }, { "internalType": "uint256", "name": "scaledDepositTokenBalance", "type": "uint256" }, { "internalType": "bool", "name": "usageAsCollateralEnabledOnUser", "type": "bool" }, { "internalType": "uint256", "name": "stableBorrowRate", "type": "uint256" }, { "internalType": "uint256", "name": "scaledVariableDebt", "type": "uint256" }, { "internalType": "uint256", "name": "principalStableDebt", "type": "uint256" }, { "internalType": "uint256", "name": "stableBorrowLastUpdateTimestamp", "type": "uint256" }], "internalType": "struct IUiPoolDataProvider.UserReserveData[]", "name": "", "type": "tuple[]" }, { "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }

const config = {
ethereum: '0x8F5273c5aa638e946BC5dD2171Ae9E9184C75228',
bsc: '0xa450547F27F0947760C9C818d9fd2CD51DFA7441',
avax: '0x483B76b13B14DB4fF49359aF9DF3A51F25FaB6a0',
ethereum: '0x9276635Ec39C72866f3cF70298eFe501EB5dcDf1',
bsc: '0xEdBDF91ac20287e332c761179FaCe71eba9FBc93',
avax: '0xb2e7216F2f70ac9d9Eec70e1Ca6f2f1CADf218D5',
xdai: '0x75e5cF901f3A576F72AB6bCbcf7d81F1619C6a12',
}

module.exports = {
methodology: "Counts the tokens locked in the contracts to be used as collateral to borrow or to earn yield. Borrowed coins are not counted towards the TVL, so only the coins actually locked in the contracts are counted. There's multiple reasons behind this but one of the main ones is to avoid inflating the TVL through cycled lending.",
// deadFrom: 2024-02-22
};

Object.keys(config).forEach(chain => {
const provider = config[chain]
module.exports[chain] = {
tvl: async (_, _b, _cb, { api, }) => {
const balances = {}
const data = await api.call({ abi, target: provider, params: nullAddress })
data[0].forEach(i => {
sdk.util.sumSingleBalance(balances, i.underlyingAsset, i.availableLiquidity, chain)
})
return balances
},
borrowed: async (_, _b, _cb, { api, }) => {
const balances = {}
const data = await api.call({ abi, target: provider, params: nullAddress })
data[0].forEach(i => {
sdk.util.sumSingleBalance(balances, i.underlyingAsset, +i.totalPrincipalStableDebt + +i.totalScaledVariableDebt, chain)
})
return balances
},
}
})
borrowed: () => ({}), // project abandoned?
tvl: async (_, _1, _2, { api }) => {
if (chain === 'xdai') return {}
const tokens = await api.call({ abi: abi.getReservesList, target: config[chain] })
const data = await api.multiCall({ abi: abi.getReserveData, calls: tokens, target: config[chain]})
const owners = data.map(c=>c.depositTokenAddress)
return api.sumTokens({ tokensAndOwners2: [tokens, owners] })
}
}})

const abi = {
"getReserveData": "function getReserveData(address asset) view returns (((uint256 data) configuration, uint128 liquidityIndex, uint128 variableBorrowIndex, uint128 currentLiquidityRate, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, address depositTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address strategy, uint8 id))",
"getReserveNormalizedIncome": "function getReserveNormalizedIncome(address asset) view returns (uint256)",
"getReserveNormalizedVariableDebt": "function getReserveNormalizedVariableDebt(address asset) view returns (uint256)",
"getReservesList": "address[]:getReservesList",
}
2 changes: 1 addition & 1 deletion projects/elektrik/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const query = `{
}`

async function tvl(_, _b, _cb, { api, }) {
const { pools } = await cachedGraphQuery('elektrik-1', 'https://subgraph.elektrik.network/subgraphs/name/ELEKTRIK-GRAPH', query)
const { pools } = await cachedGraphQuery('elektrik/test-2', 'https://subgraph.elektrik.network/subgraphs/name/ELEKTRIK-GRAPH', query)
const ownerTokens = pools.map(i => [[i.token0.id, i.token1.id], i.id])
return sumTokens2({ api, ownerTokens, })
}
Expand Down
2 changes: 1 addition & 1 deletion projects/extra/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Object.keys(config).forEach(chain => {
const calls = []
for (let i = 1; i <= vaultLogs.length; i++) calls.push(i)

const data = await api.multiCall({ target: positionViewer, abi: getVaultAbi, calls })
const data = (await api.multiCall({ target: positionViewer, abi: getVaultAbi, calls, permitFailure: true })).filter(i => i)
data.forEach(({ pair, totalLp }) => api.add(pair, totalLp))

const tokensAndOwners = logs.map(i => [i.reserve, i.eTokenAddress])
Expand Down
48 changes: 24 additions & 24 deletions projects/helper/chain/cosmos.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const axios = require("axios");
const sdk = require("@defillama/sdk");
const { transformBalances } = require("../portedTokens");
const { get, post } = require("../http");
const { PromisePool } = require("@supercharge/promise-pool");
const { log } = require("../utils");
const ADDRESSES = require('../coreAssets.json')
Expand All @@ -27,15 +27,15 @@ const endPoints = {
persistence: "https://rest.cosmos.directory/persistence",
secret: "https://rpc.ankr.com/http/scrt_cosmos",
// chihuahua: "https://api.chihuahua.wtf",
injective: "https://sentry.lcd.injective.network:443",
injective: "https://injective-rest.publicnode.com",
migaloo: "https://migaloo-api.polkachu.com",
fxcore: "https://fx-rest.functionx.io",
xpla: "https://dimension-lcd.xpla.dev",
kava: "https://api2.kava.io",
neutron: "https://rest-kralum.neutron-1.neutron.org",
quasar: "https://quasar-api.polkachu.com",
gravitybridge: "https://gravitychain.io:1317",
sei: "https://sei-api.polkachu.com",
sei: "https://sei-rest.publicnode.com",
aura: "https://lcd.aura.network",
archway: "https://api.mainnet.archway.io",
sifchain: "https://sifchain-api.polkachu.com",
Expand All @@ -53,7 +53,7 @@ const chainSubpaths = {

// some contract calls need endpoint with higher gas limit
const highGasLimitEndpoints = {
'sei1xr3rq8yvd7qplsw5yx90ftsr2zdhg4e9z60h5duusgxpv72hud3shh3qfl': "https://rest.sei-apis.com",
// 'sei1xr3rq8yvd7qplsw5yx90ftsr2zdhg4e9z60h5duusgxpv72hud3shh3qfl': "https://rest.sei-apis.com",
}

function getEndpoint(chain, { contract } = {}) {
Expand All @@ -69,7 +69,7 @@ async function query(url, block, chain) {
if (block !== undefined) {
endpoint += `&height=${block - (block % 100)}`;
}
return (await axios.get(endpoint)).data.result;
return (await get(endpoint)).result;
}

async function queryV1Beta1({ chain, paginationKey, block, url } = {}) {
Expand All @@ -87,7 +87,7 @@ async function queryV1Beta1({ chain, paginationKey, block, url } = {}) {
}
endpoint += paginationQueryParam;
}
return (await axios.get(endpoint)).data;
return get(endpoint)
}

async function getTokenBalance({ token, owner, block, chain }) {
Expand Down Expand Up @@ -130,7 +130,7 @@ async function getDenomBalance({ denom, owner, block, chain } = {}) {
if (block !== undefined) {
endpoint += `?height=${block - (block % 100)}`;
}
let { data } = await axios.get(endpoint)
let data = await get(endpoint)
data = chain === 'terra' ? data.balances : data.result
const balance = data.find((balance) => balance.denom === denom);
return balance ? Number(balance.amount) : 0;
Expand All @@ -145,8 +145,8 @@ async function getBalance2({ balances = {}, owner, block, chain, tokens, blackli
endpoint += `?height=${block - (block % 100)}`;
}
const {
data: { balances: data },
} = await axios.get(endpoint);
balances: data,
} = await get(endpoint);
for (const { denom, amount } of data) {
if (blacklistedTokens?.includes(denom)) continue;
if (tokens && !tokens.includes(denom)) continue;
Expand Down Expand Up @@ -178,13 +178,13 @@ async function queryContract({ contract, chain, data }) {
if (typeof data !== "string") data = JSON.stringify(data);
data = Buffer.from(data).toString("base64");
return (
await axios.get(
await get(
`${getEndpoint(chain, { contract })}/cosmwasm/wasm/v1/contract/${contract}/smart/${data}`
)
).data.data;
).data;
}

const multipleEndpoints={
const multipleEndpoints = {
sei: [
"https://sei-api.polkachu.com",
"https://sei-rest.brocha.in",
Expand All @@ -197,20 +197,20 @@ const multipleEndpoints={

async function queryContractWithRetries({ contract, chain, data }) {
const rpcs = multipleEndpoints[chain]
if(rpcs === undefined){
return queryContract({contract, chain, data})
if (rpcs === undefined) {
return queryContract({ contract, chain, data })
}
if (typeof data !== "string") data = JSON.stringify(data);
data = Buffer.from(data).toString("base64");
for(let i=0; i<rpcs.length; i++){
try{
for (let i = 0; i < rpcs.length; i++) {
try {
return (
await axios.get(
await get(
`${rpcs[i]}/cosmwasm/wasm/v1/contract/${contract}/smart/${data}`
)
).data.data;
} catch(e){
if(i >= rpcs.length - 1){
).data;
} catch (e) {
if (i >= rpcs.length - 1) {
throw e
}
}
Expand All @@ -222,7 +222,7 @@ async function queryManyContracts({ contracts = [], chain, data }) {
const { results, errors } = await PromisePool
.withConcurrency(parallelLimit)
.for(contracts)
.process(async (contract) => queryContract({ contract, chain, data }))
.process(async (contract) => queryContract({ contract, chain, data }))

if (errors && errors.length) throw errors[0]

Expand All @@ -237,9 +237,9 @@ async function queryContracts({ chain, codeId, }) {

do {
let endpoint = `${getEndpoint(chain)}/cosmwasm/wasm/v1/code/${codeId}/contracts?pagination.limit=${limit}${paginationKey ? `&pagination.key=${encodeURIComponent(paginationKey)}` : ''}`
const { data: { contracts, pagination } } = await axios.get(endpoint)
paginationKey = pagination.next_key
res.push(...contracts)
const { contracts, pagination } = await get(endpoint)
paginationKey = pagination.next_key
res.push(...contracts)
} while (paginationKey)

return res
Expand Down
38 changes: 38 additions & 0 deletions projects/helper/chain/waves.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const axios = require('axios')
const { get } = require('../http')
const API_HOST = "https://nodes.wavesnodes.com/"; // https://docs.waves.tech/en/waves-node/node-api/#api-of-pool-of-public-nodes

const axiosObj = axios.create({
Expand Down Expand Up @@ -65,8 +66,45 @@ async function data(address, key) {
return response.data;
}

const tokenMapping = {
'3VuV5WTmDz47Dmdn3QpcYjzbSdipjQE4JMdNe1xZpX13': { cgId: 'ethereum', decimals: 8 },
'2Fge5HEBRD3XTeg7Xg3FW5yiB9HVJFQtMXiWMQo72Up6': { cgId: 'wrapped-bitcoin', decimals: 8 },
'9wc3LXNA4TEBsXyKtoLE9mrbDD7WMHXvXrCjZvabLAsi': { cgId: 'tether', decimals: 6 },
'HGgabTqUS8WtVFUJzfmrTDMgEccJuZLBPhFgQFxvnsoW': { cgId: 'usd-coin', decimals: 6 },
}

async function sumTokens({ owners, api, includeWaves = true, }) {
await Promise.all(
owners.map(async (owner) => {
const { balances } = await get(API_HOST + `assets/balance/${owner}`);
balances.forEach(({ assetId, balance }) => {
if (tokenMapping[assetId]) {
const { cgId, decimals } = tokenMapping[assetId]
api.addCGToken(cgId, balance / (10 ** decimals))
} else {
api.add(assetId, balance)
}
})
})
)
if (includeWaves)
await Promise.all(
owners.map(async (owner) => {
const { balance } = await get(API_HOST + `addresses/balance/${owner}`);
api.addCGToken('waves', balance / 1e8)
})
)
}

async function call({ target, key}) {
const { value } = await await get(API_HOST + `addresses/data/${target}/${key}`)
return value;
}

module.exports = {
call,
assetDetails,
scriptEvaluate,
data,
sumTokens,
};
17 changes: 6 additions & 11 deletions projects/socean/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
const { getConnection, decodeAccount, sumTokens2 } = require('../helper/solana')
const { PublicKey } = require("@solana/web3.js")
const ADDRESSES = require('../helper/coreAssets.json')
const { sumTokens2, } = require('../helper/solana')

async function tvl(_, _1, _2, { api }) {
const connection = getConnection()
// const programPublicKey = new PublicKey('5ocnV1qiCgaQR8Jb8xWnVbApfaygJ8tNoZfgPwsgx9kx')
const stakeAccount = new PublicKey('5oc4nmbNTda9fx8Tw57ShLD132aqDK65vuHH4RU1K4LZ')
const data = await connection.getAccountInfo(stakeAccount)
const i = decodeAccount('scnStakePool', data)
api.add(ADDRESSES.solana.SOL, i.totalStakeLamports.toString())
return api.getBalances()
// https://www.npmjs.com/package/@unstake-it/sol
// https://learn.sanctum.so/docs/contracts

async function tvl() {
return sumTokens2({ solOwners: ['3rBnnH9TTgd3xwu48rnzGsaQkSr1hR64nY71DrDt6VrQ'],})
}

module.exports = {
Expand Down
4 changes: 2 additions & 2 deletions projects/solfarm.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { get } = require('./helper/http')

async function fetch() {
var response = await get('https://api.solfarm.io/tvl')
var response = await get('https://api.tulip.garden/tvl')

return response.TOTAL;
return response.total;
}

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion projects/sora.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { post } = require('./helper/http')

async function tvl(timestamp) {
const { data: { entities: { nodes } } } = await post('https://api.subquery.network/sq/sora-xor/sora-prod-sub4', {
const { data: { entities: { nodes } } } = await post('https://api.subquery.network/sq/sora-xor/sora-prod', {
"query": "query NetworkTvlQuery($after: Cursor, $type: SnapshotType, $from: Int, $to: Int) {\n entities: networkSnapshots(\n after: $after\n orderBy: TIMESTAMP_DESC\n filter: {and: [{type: {equalTo: $type}}, {timestamp: {lessThanOrEqualTo: $from}}, {timestamp: {greaterThanOrEqualTo: $to}}]}\n ) {\n pageInfo {\n hasNextPage\n endCursor\n \n }\n nodes {\n timestamp\n liquidityUSD\n }\n }\n}",
"operationName": "NetworkTvlQuery",
"variables": {
Expand Down
6 changes: 3 additions & 3 deletions projects/sushiswap-trident/trident.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const tridentQueryWithBlock = `
query get_tokens($block: Int) {
tokens(
block: { number: $block }
first: 1000
first: 100
orderBy: liquidityUSD
orderDirection: desc
where: { liquidityUSD_gt: 0 }
Expand All @@ -34,7 +34,7 @@ const tridentQueryWithBlock = `
const tridentQuery = `
query get_tokens {
tokens(
first: 1000
first: 100
orderBy: liquidityUSD
orderDirection: desc
where: { liquidityUSD_gt: 0 }
Expand Down Expand Up @@ -63,7 +63,7 @@ function trident(chain) {
result.tokens.forEach((token) => {
api.add(token.id, token.liquidity);
});

return api.getBalances()
};
}

Expand Down
4 changes: 2 additions & 2 deletions projects/teahouse-v3/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const teahouseVaultAPI = "https://vault-content-api.teahouse.finance/vaults";
// get vault contract addresses from teahouse api
async function getVaultContractsAddress(chain) {
let plAddress = [];
const { vaults } = await getConfig("teahouse", teahouseVaultAPI);
const { vaults } = await getConfig("teahouse/v3", teahouseVaultAPI);
vaults.forEach((element) => {
// v3 vaults
if (element.isDeFi == true && element.isActive == true) {
Expand All @@ -34,7 +34,7 @@ chains.forEach((chain) => {
api.addTokens(tokens, bals);
if (['boba', 'mantle'].includes(chain)) {
const tvl = await api.getUSDValue()
if (+tvl === 0) throw new Error('tvl is 0')
if (+tvl === 0) throw new Error('tvl is 0 Balances:' + JSON.stringify(api.getBalances()))
}
return api.getBalances();
},
Expand Down
4 changes: 2 additions & 2 deletions projects/teahouse/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const teahouseVaultAPI = "https://vault-content-api.teahouse.finance/vaults";
// get vault contract addresses from teahouse api
async function getVaultContractsAddress(chain) {
let htAddress = [];
const { vaults } = await getConfig("teahouse", teahouseVaultAPI);
const { vaults } = await getConfig("teahouse/v1", teahouseVaultAPI);
vaults.forEach((element) => {
// v2 vaults
if (element.isDeFi == false && element.isActive == true) {
Expand Down Expand Up @@ -44,7 +44,7 @@ chains.forEach((chain) => {
api.addTokens(tokens, bals);
if (chain === 'bsc') {
const tvl = await api.getUSDValue()
if (+tvl === 0) throw new Error('tvl is 0')
if (+tvl === 0) throw new Error('tvl is 0 Balances:' + JSON.stringify(api.getBalances()))
}
return api.getBalances();
},
Expand Down
4 changes: 2 additions & 2 deletions projects/tulip/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const garden = "0xceF2f95f185D49bcd1c10DE7f23BEaCBaae6eD0f";

module.exports = {
oasis: {
staking: staking(garden, petal, "oasis"),
tvl: getUniTVL({ factory: '0x90a5e676EFBdeFeeeb015cd87484B712fd54C96A', chain: 'oasis', useDefaultCoreAssets: true }),
staking: staking(garden, petal),
tvl: getUniTVL({ factory: '0x90a5e676EFBdeFeeeb015cd87484B712fd54C96A', useDefaultCoreAssets: true }),
}
};
Loading

0 comments on commit 67f2e9d

Please sign in to comment.