Open alex-pakalniskis opened 3 months ago
Thanks @alex-pakalniskis for opening this issue!
For COLLABORATOR only :
To add labels, comment on the issue
/label add label1,label2,label3
To remove labels, comment on the issue
/label remove label1,label2,label3
First issue by @alex-pakalniskis
Issues Details of @alex-pakalniskis in shipyard-software-DeFi-Pulse-Adapters : | OPEN | CLOSED | TOTAL |
---|---|---|---|
1 | 0 | 1 |
The task involves updating the subgraph endpoints in various files to ensure compatibility with The Graph's decentralized network. The hosted service subgraph endpoints will be deprecated after June 12th, so we need to update the endpoints to the new network endpoints.
To implement the solution, follow these steps for each file:
This file does not explicitly reference a subgraph endpoint. Verify if the APIs (SY_POOLS_API_URL
and SA_POOLS_API_URL
) are affected by the deprecation and update them accordingly if needed.
Update the subgraph endpoint to the new network endpoint.
const sdk = require("../../sdk");
const BigNumber = require("bignumber.js");
const { request, gql } = require("graphql-request");
const SUBGRAPH_URL = "https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>";
const XTokenWrapperContractAddress = "0x2b9dc65253c035eb21778cb3898eab5a0ada0cce";
async function getTokens() {
let tokens = [];
try {
const tokensQuery = gql`
query Tokens {
tokens(where: { symbol_not: "SPT" }) {
id
}
}
`;
const tokensResponse = await request(SUBGRAPH_URL, tokensQuery);
tokens = tokensResponse.tokens.map((token) => token.id);
} catch (e) {
console.log(e);
throw e;
}
return tokens;
}
async function getBalances(tokens, block) {
const balanceCalls = tokens.map((token) => ({
target: token,
params: XTokenWrapperContractAddress,
}));
let balanceResponses;
try {
balanceResponses = (
await sdk.api.abi.multiCall({
block,
calls: balanceCalls,
abi: "erc20:balanceOf",
})
).output;
} catch (e) {
console.log(e);
throw e;
}
let balances = {};
balanceResponses.forEach((response) => {
if (response.success) {
const token = response.input.target;
const balance = BigNumber(response.output);
if (balance > 0) {
balances[token] = balance.toFixed();
}
}
});
return balances;
}
let tokenHolderMap = [];
async function tvl(timestamp, block) {
const tokens = await getTokens();
const balances = await getBalances(tokens, block);
tokenHolderMap = [
{
tokens,
holders: [XTokenWrapperContractAddress],
},
];
return balances;
}
module.exports = {
name: "Swarm Markets",
token: "SMT",
category: "DEXes",
start: 1627776000,
tvl,
tokenHolderMap,
};
Update the subgraph endpoint to the new network endpoint.
const { request, gql } = require("graphql-request");
const BigNumber = require('bignumber.js');
const sdk = require('../../sdk');
const GRAPH_URL = 'https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>';
async function tvl(timestamp, block) {
const { amms } = await request(GRAPH_URL, GET_POOLS, { block });
const result = { '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48': '0' };
for (let i = 0; i < amms.length; i++) {
const amm = amms[i];
const collateralToken = amm['collateralToken']['id'];
const response = await sdk.api.erc20.balanceOf({
block,
target: collateralToken,
owner: amm['id'],
});
if (!result[collateralToken]) {
result[collateralToken] = '0';
}
result[collateralToken] = BigNumber(result[collateralToken]).plus(response.output).toFixed();
for (let im = 0; im < amm.markets.length; im++) {
const market = amm.markets[im];
const response = await sdk.api.erc20.balanceOf({
block,
target: collateralToken,
owner: market['id'],
});
result[collateralToken] = BigNumber(result[collateralToken]).plus(response.output).toFixed();
}
}
return result;
}
const GET_POOLS = gql`
query Pools($block: Int) {
amms(block: { number: $block }) {
id
collateralToken {
id
}
markets {
id
}
}
}
`
module.exports = {
name: 'Siren',
token: 'SI',
category: 'derivatives',
start: 1605574800,
tvl
}
Update the subgraph endpoint to the new network endpoint if applicable.
const axios = require("axios");
const SUBGRAPH_URL = "https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>";
async function tvl(timestamp, block) {
if (block < 18692990) {
return {
"0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270": 0
};
}
const { data } = await axios.get("https://files.insurace.io/public/defipulse/polygonpools.json");
const pools = data.pools;
for (pool in pools) {
if (pool.PoolToken == "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE") {
pool.PoolToken = "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270";
}
}
const { output: _tvlList } = await sdk.api.abi.multiCall({
calls: pools.map((pool) => ({
target: pool.StakersPool,
params: pool.PoolToken,
})),
abi: abi["getStakedAmountPT"],
block,
chain: 'polygon'
});
const balances = {};
_.each(_tvlList, (element) => {
if (element.success) {
let address = element.input.params[0];
if (address == "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE") {
address = "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270";
}
let balance = element.output;
if (BigNumber(balance).toNumber() <= 0) {
return;
}
balances[address] = BigNumber(balances[address] || 0).plus(balance).toFixed();
} else {
console.log(element);
}
});
return balances;
}
module.exports = {
name: 'InsurAce Protocol_Polygon',
token: 'INSUR',
chain: 'Polygon',
category: 'Derivatives',
start: 18692990,
tvl
};
Update the subgraph endpoint to the new network endpoint.
const sdk = require('../../sdk');
const _ = require('underscore');
const BigNumber = require('bignumber.js');
const { request, gql } = require("graphql-request");
const abi = require('./abi');
const V2_ADDRESS = '0xBA12222222228d8Ba445958a75a0704d566BF2C8';
const tokensApi = 'https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>';
async function tvl(timestamp, block) {
let balances = {
'0x0000000000000000000000000000000000000000': '0',
};
let poolLogs = await sdk.api.util.getLogs({
target: '0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd',
topic: 'LOG_NEW_POOL(address,address)',
keys: ['topics'],
fromBlock: 9562480,
toBlock: block
});
let poolCalls = [];
let pools = _.map(poolLogs.output, (poolLog) => {
if (poolLog.topics) {
return `0x${poolLog.topics[2].slice(26)}`
} else {
return `0x${poolLog[2].slice(26)}`
}
});
const poolTokenData = (await sdk.api.abi.multiCall({
calls: _.map(pools, (poolAddress) => ({ target: poolAddress })),
abi: abi.getCurrentTokens,
})).output;
_.forEach(poolTokenData, (poolToken) => {
let poolTokens = poolToken.output;
let poolAddress = poolToken.input.target;
_.forEach(poolTokens, (token) => {
poolCalls.push({
target: token,
params: poolAddress,
});
})
});
let poolBalances = (await sdk.api.abi.multiCall({
block,
calls: poolCalls,
abi: 'erc20:balanceOf'
})).output;
_.each(poolBalances, (balanceOf) => {
if(balanceOf.success) {
let balance = balanceOf.output;
let address = balanceOf.input.target;
if (BigNumber(balance).toNumber() <= 0) {
return;
}
balances[address] = BigNumber(balances[address] || 0).plus(balance).toFixed();
}
});
try {
const POOL_TOKENS = gql`
{
balancers {
pools {
tokens {
address
}
}
}`;
const v2Tokens = await request(tokensApi, POOL_TOKENS, {
block,
});
let tokenAddresses = [];
for (let i = 0; i < v2Tokens.balancers[0].pools.length; i++) {
for (let address of v2Tokens.balancers[0].pools[i].tokens) {
tokenAddresses.push(address.address)
}
}
tokenAddresses = _.uniq(tokenAddresses);
let v2Calls = tokenAddresses.map((address) => {
return {
target: address,
params: V2_ADDRESS
}
});
let v2Balances = (await sdk.api.abi.multiCall({
block,
calls: v2Calls,
abi: 'erc20:balanceOf'
})).output;
_.each(v2Balances, (balanceOf) => {
if (balanceOf.success) {
let balance = balanceOf.output;
let address = balanceOf.input.target;
if (BigNumber(balance).toNumber() <= 0) {
return;
}
balances[address] = BigNumber(balances[address] || 0)
.plus(balance)
.toFixed();
}
});
} catch (e) {
console.log(e);
throw(e);
}
return balances;
}
module.exports = {
name: 'Balancer',
token: 'BAL',
category: 'dexes',
start : 1582761600,
tvl
}
Update the subgraph endpoint to the new network endpoint.
const sdk = require("../../sdk");
const BigNumber = require("bignumber.js");
const synthetixContractAbi = require("./synthetix.abi.json");
const synthetixStateContractAbi = require("./synthetix-state.abi.json");
const exchangeRatesContractAbi = require("./exchange-rates.abi.json");
const systemSettingsContractAbi = require("./system-settings.abi.json");
const pageResults = require("graph-results-pager");
const synthetixState = "0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82";
const synthetix = "0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F";
const exchangeRates = "0xd69b189020EF614796578AfE4d10378c5e7e1138";
const systemSettings = "0xD3C8d372bFCd36c2B452639a7ED6ef7dbFDC56F8";
const snxGraphEndpoint = "https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>";
async function tvl(timestamp, block) {
const holders = await SNXHolders(block);
const [
{ output: unformattedSnxPrice },
{ output: unformattedSnxTotalSupply },
{ output: unformattedLastDebtLedgerEntry },
{ output: unformattedTotalIssuedSynths },
{ output: unformattedIssuanceRatio },
] = await Promise.all([
sdk.api.abi.call({
block,
target: exchangeRates,
abi: exchangeRatesContractAbi["rateForCurrency"],
params: [
"0x534e580000000000000000000000000000000000000000000000000000000000",
],
}),
sdk.api.abi.call({
block,
target: synthetix,
abi: synthetixContractAbi["totalSupply"],
}),
sdk.api.abi.call({
block,
target: synthetixState,
abi: synthetixStateContractAbi["lastDebtLedgerEntry"],
}),
sdk.api.abi.call({
block,
target: synthetix,
abi: synthetixContractAbi["totalIssuedSynthsExcludeEtherCollateral"],
params: [
"0x7355534400000000000000000000000000000000000000000000000000000000",
],
}),
sdk.api.abi.call({
block,
target: systemSettings,
abi: systemSettingsContractAbi["issuanceRatio"],
}),
]);
const [snxPrice, snxTotalSupply, totalIssuedSynths, issuanceRatio] = [
unformattedSnxPrice,
unformattedSnxTotalSupply,
unformattedTotalIssuedSynths,
unformattedIssuanceRatio,
].map((n) => toBig(n, 18));
const lastDebtLedgerEntry = toBig(unformattedLastDebtLedgerEntry, 27);
debug({ snxPrice, snxTotalSupply, totalIssuedSynths, issuanceRatio });
let snxTotal = toBig(0);
let snxLocked = toBig(0);
for (const {
collateral: unformattedCollateral,
debtEntryAtIndex: unformattedDebtEntryAtIndex,
initialDebtOwnership: unformattedInitialDebtOwnership,
} of holders) {
const collateral = toBig(unformattedCollateral, 18);
const debtEntryAtIndex = toBig(unformattedDebtEntryAtIndex, 0);
const initialDebtOwnership = toBig(unformattedInitialDebtOwnership, 0);
let debtBalance = totalIssuedSynths
.times(lastDebtLedgerEntry)
.div(debtEntryAtIndex)
.times(initialDebtOwnership);
let collateralRatio = debtBalance.div(collateral).div(snxPrice);
if (debtBalance.isNaN()) {
debtBalance = toBig(0);
collateralRatio = toBig(0);
}
const lockedSnx = collateral.times(
BigNumber.min(toBig(1), collateralRatio.div(issuanceRatio))
);
snxTotal = snxTotal.plus(collateral);
snxLocked = snxLocked.plus(lockedSnx);
}
debug({ snxLocked, snxTotal, snxTotalSupply, snxPrice });
const percentLocked = snxLocked.div(snxTotal);
debug({ percentLocked });
const tvl = snxTotalSupply.times(percentLocked).times(snxPrice).toFixed();
debug({ tvl });
return {
[synthetix]: tvl,
};
}
async function SNXHolders(blockNumber) {
return await pageResults({
api: snxGraphEndpoint,
query: {
entity: "snxholders",
selection: {
orderBy: "collateral",
orderDirection: "desc",
block: {
number: blockNumber,
},
where: {
collateral_gt: 0,
block_gt: 5873222,
},
},
properties: ["collateral", "debtEntryAtIndex", "initialDebtOwnership"],
},
max: 1000,
});
}
function toBig(n, decimals = 0) {
if (!n) return new BigNumber(0);
return new BigNumber(n.toString()).div(Math.pow(10, decimals));
}
function debug(o) {
Object.entries(o).forEach(([k, v]) => {
console.log("%s=%s", k, v);
});
console.log();
}
module.exports = {
name: "Synthetix",
token: "SNX",
category: "derivatives",
start: 1565287200,
tvl,
};
Replace <ID>
, <SUBGRAPH_NAME>
, and <VERSION>
with the actual values obtained from Subgraph Studio. This will ensure that the Synthetix project continues to function correctly with the new subgraph endpoint.
Click here to create a Pull Request with the proposed solution
Files used for this task:
Not Found
Hey team,
We've noticed that you're referencing a subgraph deployed on The Graph's hosted service in this repository. Just a heads-up: after June 12th, hosted service subgraph endpoints will no longer be available as the offering is being deprecated.
If you are the subgraph owner or maintainer, it's time to upgrade your subgraph to the network. This ensures everything keeps running smoothly and you get access to all the latest features and improvements. Here is a quick guide with all the upgrade steps.
If you're not the subgraph owner or maintainer, check Graph Explorer to see if the subgraph development team has already upgraded to the network. If you don’t find an upgraded subgraph, a friendly nudge to the subgraph development team would be greatly appreciated—it's a quick process that benefits everyone. Here's the upgrade guide with all the necessary steps for the subgraph development team.
Once the subgraph is upgraded to the network, you can create an API key and updated query URL in Subgraph Studio then update this repository to query from the new endpoint,
https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>
Need more support or have more questions? Feel free to reach out to felix@edgeandnode.com. We're here to help!
Cheers,
Paka