Skip to content

Commit

Permalink
refactor code to use ethers v6 (DefiLlama#8592)
Browse files Browse the repository at this point in the history
* refactor code tu use ethers v6

* minor fix

* minor fix

* update typescript version
  • Loading branch information
g1nt0ki authored Jan 10, 2024
1 parent 8f0a6aa commit f972b2c
Show file tree
Hide file tree
Showing 45 changed files with 2,476 additions and 7,552 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/commentResult.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async function main() {
body = `The adapter at ${path} exports TVL:
\n \n ${file.substring(summaryIndex + 17).replaceAll('\n', '\n ')}`;
} else if (errorIndex != -1) {
body = `Error while running adapter at ${path}:
body = `Error while running adapter at ${path ?? ''}:
\n \n ${file.split(errorString)[1].replaceAll('\n', '\n ')}`;
} else
return;
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
# fail if package.json or package-lock.json is changed
FILES_MODIFIED=${{ steps.file_changes.outputs.files_modified }}
if [[ $FILES_MODIFIED == *"package.json"* || $FILES_MODIFIED == *"package-lock.json"* ]]; then
echo "------ ERROR ------ \n Please revert changes to package.json / package-lock.json" > /home/runner/work/DefiLlama-Adapters/DefiLlama-Adapters/output.txt
echo "------ ERROR ------ > Please revert changes to package.json / package-lock.json" > /home/runner/work/DefiLlama-Adapters/DefiLlama-Adapters/output.txt
node ${{ github.workspace }}/.github/workflows/commentResult.js /home/runner/work/DefiLlama-Adapters/DefiLlama-Adapters/output.txt "${{ github.repository_owner }}" "${{ github.event.repository.name }}" "${{ github.event.number }}"
exit 1
fi
Expand Down
9,391 changes: 2,245 additions & 7,146 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@
"@defillama/sdk": "latest",
"@project-serum/anchor": "^0.26.0",
"@solana/web3.js": "^1.87.6",
"@solendprotocol/solend-sdk": "^0.6.2",
"@solendprotocol/solend-sdk": "^0.4.3",
"@supercharge/promise-pool": "^2.1.0",
"axios": "^0.27.2",
"axios": "^1.6.5",
"bignumber.js": "^9.0.1",
"blakejs": "^1.2.1",
"bn.js": "^5.2.1",
"borsh": "^0.7.0",
"curve25519-js": "^0.0.4",
"dotenv": "^8.6.0",
"ethers": "^5.6.5",
"ethers": "^6.0.0",
"graphql": "^16.6.0",
"graphql-request": "^4.0.0",
"hi-base32": "^0.5.1",
Expand All @@ -40,7 +40,7 @@
"p-limit": "^3.1.0",
"starknet": "^5.24.3",
"tron-format-address": "^0.1.8",
"typescript": "^4.7.4"
"typescript": "^5.0.0"
},
"overrides": {
"ansi-regex": "5.0.1",
Expand Down
2 changes: 1 addition & 1 deletion projects/1inch.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Object.keys(config).forEach(chain => {
})
logs.forEach(i => ownerTokens.push([[i.token1, i.token2], i.mooniswap]))
}
return sumTokens2({ api, ownerTokens, blacklistedTokens, })
return sumTokens2({ api, ownerTokens, blacklistedTokens, sumChunkSize: 50, })
}
}
})
12 changes: 5 additions & 7 deletions projects/CollectifDAO/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const {BigNumber} = require("@ethersproject/bignumber");
const {nullAddress} = require("../helper/tokenMapping");
const {get} = require("../helper/http");

Expand Down Expand Up @@ -32,19 +31,18 @@ module.exports = {
const minersOwners = await getMinersOwners();
const totalStaked = await api.call({abi: totalAssetsABI, target: COLLECTIF_LIQUID_STAKING_POOL_CONTRACT});

let totalCollateral = BigNumber.from(0);
let totalCollateral = 0

if (minersOwners && minersOwners.length > 0) {
const collaterals = await Promise.all(minersOwners.map(fetchCollateral));
totalCollateral = collaterals.reduce((acc, cur) => {
const [available, locked] = cur;
return acc.add(available).add(locked);
}, BigNumber.from(0));
return acc + +available + +locked
}, 0);
}

const tvl = BigNumber.from(totalStaked).add(totalCollateral).toString();

api.add(nullAddress, tvl)
api.add(nullAddress, totalStaked)
api.add(nullAddress, totalCollateral)
},
},
};
13 changes: 4 additions & 9 deletions projects/ankr/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
const { get } = require("../helper/http")
const sdk = require('@defillama/sdk');
const abi = require("./abi.json");
const { ethers } = require("ethers");
const { toUSDTBalances } = require("../helper/balances")

let _response

Expand Down Expand Up @@ -50,7 +47,7 @@ async function getFantomTvl() {
}
}

async function getGnosisTvl(timestamp, block, chainBlocks) {
async function getGnosisTvl(timestamp, block, chainBlocks, { api}) {

//Current Ankr Provider Address, there is a hard cap on how much mGNO each address can stake, other addresses might appear*/
const ankrProviderAddress = "0x4069D8A3dE3A72EcA86CA5e0a4B94619085E7362"
Expand All @@ -63,16 +60,14 @@ async function getGnosisTvl(timestamp, block, chainBlocks) {
//Provider Registry Logic Contract = "0x6c6f910a79639dcc94b4feef59ff507c2e843929"


var providerBalance = (await sdk.api.abi.call({
var providerBalance = (await api.call({
abi: abi.getProviderBalance,
chain: 'xdai',
target: proxyStakingPool,
params: [ankrProviderAddress],
block: chainBlocks['xdai'],
})).output
}))

//providerBalance = [balance, totalCap]
var staked = ethers.utils.formatEther(providerBalance[0])
var staked = providerBalance[0] / 1e18

//Staked amount is in mGNO, 32 mGNO = 1 GNO
var trueStaked = staked / 32
Expand Down
23 changes: 4 additions & 19 deletions projects/arcade-xyz/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const sdk = require("@defillama/sdk");
const { BigNumber } = require('ethers');

const { fetchVaults, fetchLoans } = require('./queries');
const { sumTokens2 } = require('../helper/unwrapLPs');
Expand Down Expand Up @@ -48,30 +47,16 @@ async function tvl(_, block, _cb, { api }) {
// Fetches all active loans, their payable curency and amount borrowed then sums it up.
async function borrowed(_, block, _cb, { api }) {
const loans = await fetchLoans(block);
const balances = {}

// Iterate over each loan to sum up principal by currency
for (const loan of loans) {
const { payableCurrency, principal, interestRate } = loan;
const fullRepayment = getRepayment(principal, interestRate)

sdk.util.sumSingleBalance(balances, payableCurrency, fullRepayment, api.chain);
api.add(payableCurrency, principal)
const interest = principal * interestRate / 1e21
api.add(payableCurrency, interest)
}

return balances;
}

const decimals18 = BigNumber.from(10).pow(18);
function getRepayment(principalStr, interestRateStr) {
const principal = BigNumber.from(principalStr);
const interestRate = BigNumber.from(interestRateStr);

const interest = principal
.mul(interestRate)
.div(decimals18)
.div(1000);

return principal.add(interest);
return api.getBalances();
}

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion projects/clober/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const contractV1DeployedChainIds = [1, 137, 42161]
const contractV1_1DeployedChainIds = [137, 1101, 42161]

function calculateSalt(chainId, nonce) {
return ethers.utils.solidityKeccak256(['uint256', 'uint256'], [chainId, nonce])
return ethers.solidityPackedKeccak256(['uint256', 'uint256'], [chainId, nonce])
}

async function fetchTokenAddressesV1_0(api, chainId){
Expand Down
7 changes: 2 additions & 5 deletions projects/counterstake/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ const {
fetchOswapExchangeRates,
summingBaseAABalancesToTvl,
} = require('../helper/chain/obyte');
const utils = require('../helper/utils');
const sdk = require('@defillama/sdk')
const { sumTokens2 } = require('../helper/unwrapLPs')
const { getConfig } = require('../helper/cache')
const { formatUnits } = require('ethers/lib/utils')

async function bridgeTvl(timestamp, assetMetadata, exchangeRates) {
const baseAABalances = await Promise.all([
Expand Down Expand Up @@ -143,14 +140,14 @@ const tryToGetUSDPriceOfUnknownTokens = async (sum, api) => {
target: LINE_CONTRACT,
});

const totalLocked = BigInt(transformedSumObject[LINE_TOKEN_KEY]);
const totalLocked = transformedSumObject[LINE_TOKEN_KEY]

const linePriceInCollateral = await api.call({
abi: "uint256:getPrice",
target: ORACLE_CONTRACT_ADDRESS,
});

const priceInCollateral = formatUnits(totalLocked * BigInt(linePriceInCollateral), 36);
const priceInCollateral = totalLocked * linePriceInCollateral / 1e36
const exchangeRates = await fetchOswapExchangeRates();

transformedSumObject['usd'] = exchangeRates['GBYTE_USD'] * priceInCollateral;
Expand Down
4 changes: 2 additions & 2 deletions projects/deltaprime/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async function tvlAvalanche(timestamp, block, chainBlocks, { api }) {
const ownedAssets = await api.multiCall({ abi: getAllOwnedAssetsAbi, calls: accounts })
accounts.forEach((o, i) => {
ownedAssets[i].forEach(tokenStr => {
tokenStr = ethers.utils.parseBytes32String(tokenStr)
tokenStr = ethers.decodeBytes32String(tokenStr)
const token = assetToAddressMappingAvalanche[tokenStr]
if (!token) {
sdk.log('Missing asset mapping for: ' + tokenStr)
Expand Down Expand Up @@ -111,7 +111,7 @@ async function tvlArbitrum(timestamp, block, chainBlocks, { api }) {

accounts.forEach((o, i) => {
ownedAssets[i].forEach(tokenStr => {
tokenStr = ethers.utils.parseBytes32String(tokenStr)
tokenStr = ethers.decodeBytes32String(tokenStr)
const token = assetToAddressMappingArbitrum[tokenStr]
if (!token) return;
if (!token) {
Expand Down
4 changes: 1 addition & 3 deletions projects/filet/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ const { fetchURL } = require('../helper/utils')


const BigNumber = require("bignumber.js")
const { getExports } = require('../helper/heroku-api')
const { nullAddress } = require("../helper/tokenMapping");
const { get } = require("../helper/http");
const {utils} = require("ethers");

//bsc staking con
const filetStakingCon_BSC = "0x9c821defD3BBb07C5c786C3bB039051364Fa6F39";
Expand Down Expand Up @@ -36,7 +34,7 @@ const getMinersList = async () => {
let bytes = Buffer.alloc(20);
bytes.writeUint8(0xff, 0);
bytes.writeBigUint64BE(BigInt(minerId), 12);
return utils.getAddress('0x' + bytes.toString('hex'));
return '0x' + bytes.toString('hex')
});
}

Expand Down
32 changes: 6 additions & 26 deletions projects/gearbox/events.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { api, api2 } = require("@defillama/sdk");
const { Contract, BigNumber } = require("ethers");
const { api2 } = require("@defillama/sdk");
const { Contract, ethers } = require("ethers");
const sdk = require('@defillama/sdk')
const { getLogs } = require('../helper/cache/getLogs')

Expand Down Expand Up @@ -60,23 +60,12 @@ const getV2CAs = async (creditManager, block, api) => {
for (let cfAddr of cfAddrs) {
const cf = new Contract(cfAddr, abi["filtersV2"], getProvider("ethereum"))

const topics = {
OpenCreditAccount: cf.interface.getEventTopic("OpenCreditAccount"),
CloseCreditAccount: cf.interface.getEventTopic("CloseCreditAccount"),
LiquidateCreditAccount: cf.interface.getEventTopic(
"LiquidateCreditAccount"
),
LiquidateExpiredCreditAccount: cf.interface.getEventTopic(
"LiquidateExpiredCreditAccount"
),
TransferAccount: cf.interface.getEventTopic("TransferAccount"),
};
const l = (
await getLogs({
target: cfAddr,
fromBlock,
api,
topics: [Object.values(topics)],
topics: abi["filtersV2"].map(i => ethers.id(i)),
})
).map((log) => ({
...cf.interface.parseLog(log),
Expand Down Expand Up @@ -132,7 +121,7 @@ const getV2CAs = async (creditManager, block, api) => {

return totalValue[0]
? totalValue
.reduce((a, c) => a.add(BigNumber.from(c)), BigNumber.from("0"))
.reduce((a, c) => a + BigInt(c), BigInt(0))
.toString()
: "0";
};
Expand All @@ -159,22 +148,13 @@ const getV1CAs = async (creditManager, block, api) => {
);
const cf = await cm.creditFilter();

const topics = {
OpenCreditAccount: cm.interface.getEventTopic("OpenCreditAccount"),
CloseCreditAccount: cm.interface.getEventTopic("CloseCreditAccount"),
RepayCreditAccount: cm.interface.getEventTopic("RepayCreditAccount"),
LiquidateCreditAccount: cm.interface.getEventTopic(
"LiquidateCreditAccount"
),
TransferAccount: cm.interface.getEventTopic("TransferAccount"),
};

const logs = (
await getLogs({
target: creditManager,
fromBlock,
api,
topics: [Object.values(topics)],
topics: abi["filtersV1"].map(i => ethers.id(i)),
})
).map((log) => ({
...cm.interface.parseLog(log),
Expand Down Expand Up @@ -227,7 +207,7 @@ const getV1CAs = async (creditManager, block, api) => {
});

return totalValue
.reduce((a, c) => a.add(BigNumber.from(c)), BigNumber.from("0"))
.reduce((a, c) => a + BigInt(c), BigInt(0))
.toString();
};

Expand Down
8 changes: 3 additions & 5 deletions projects/gearbox/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
const sdk = require("@defillama/sdk");
const { sumTokens2 } = require("../helper/unwrapLPs.js");
const abi = require("./abi.json");

const { getV2CAs, getV1CAs } = require("./events");
const { BigNumber } = require("ethers");

const addressProviderV3 = "0x9ea7b04da02a5373317d745c1571c84aad03321d";
//// Gearbox TVL
Expand Down Expand Up @@ -171,7 +169,7 @@ const getV3CAs = async (creditManager, block, api) => {
target: creditManager,
});

if (!caAddrs) return BigNumber.from("0").toString();
if (!caAddrs) return "0"

const totalValue = await api.multiCall({
// ICreditManagerV3__factory.createInterface().getFunction("calcDebtAndCollateral").format(ethers.utils.FormatTypes.full)
Expand All @@ -186,8 +184,8 @@ const getV3CAs = async (creditManager, block, api) => {

return totalValue
.reduce(
(a, c) => a.add(BigNumber.from(c?.totalValue ?? "0")),
BigNumber.from("0")
(a, c) => a + BigInt(c?.totalValue ?? '0'),
BigInt(0)
)
.toString();
};
Expand Down
11 changes: 3 additions & 8 deletions projects/glif/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const { BigNumber } = require("@ethersproject/bignumber");
const { nullAddress } = require("../helper/tokenMapping");
const { get } = require("../helper/http");

Expand All @@ -20,15 +19,11 @@ module.exports = {
get("https://events.glif.link/metrics"),
]);

const totalAssetsBN = BigNumber.from(totalAssets);
const totalLockedByMinersBN = BigNumber.from(
totalLockedByMiners.totalMinerCollaterals
);
const totalAssetsBN = +totalAssets
const totalLockedByMinersBN = +totalLockedByMiners.totalMinerCollaterals
// then we add the totalLockedByMiners to the totalAssets, to account for the FIL locked by miners as borrow collateral
// this gets our tvl in attoFIL (wei denominated) without double counting
const tvl = totalAssetsBN.add(totalLockedByMinersBN).toString();

api.add(nullAddress, tvl);
api.add(nullAddress, totalAssetsBN+totalLockedByMinersBN);
},
},
};
Loading

0 comments on commit f972b2c

Please sign in to comment.