2lambda123 / shipyard-software-DeFi-Pulse-Adapters

GNU Affero General Public License v3.0
0 stars 0 forks source link

Subgraph endpoint update required #19

Open alex-pakalniskis opened 3 months ago

alex-pakalniskis commented 3 months ago

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

git-greetings[bot] commented 3 months ago

Thanks @alex-pakalniskis for opening this issue!

For COLLABORATOR only :

git-greetings[bot] commented 3 months ago

First issue by @alex-pakalniskis

Issues Details of @alex-pakalniskis in shipyard-software-DeFi-Pulse-Adapters : OPEN CLOSED TOTAL
1 0 1
codeautopilot[bot] commented 3 months ago

Potential solution

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.

How to implement

To implement the solution, follow these steps for each file:

  1. Verify the subgraph has been upgraded: Check if the subgraph has been upgraded to the decentralized network.
  2. Create an API key and get the new endpoint: Obtain the new query URL from Subgraph Studio.
  3. Update the endpoint in the code: Replace the old subgraph endpoint with the new one in the respective files.
  4. Test the changes: Ensure that the new endpoint is correctly integrated and test the functionality to confirm that everything works as expected.

File: chains/polygon/projects/barnbridge/index.js

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.

File: projects/swarm-markets/index.js

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,
};

File: projects/siren/index.js

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
}

File: chains/polygon/projects/insurace/index.js

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
};

File: projects/balancer/index.js

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
}

File: projects/synthetix/index.js

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:

Changes on chains/polygon/projects/barnbridge/index.js To address the issue of updating the subgraph endpoint in the `chains/polygon/projects/barnbridge/index.js` file, follow these steps: 1. **Identify the Current Subgraph Endpoint**: Locate the current subgraph endpoint URL in the file. This file does not explicitly show a subgraph endpoint, so it might be using an API or another method to fetch data. 2. **Update to the New Network Endpoint**: If there was a subgraph endpoint, you would replace it with the new network endpoint as per the guide provided. Since this file uses API URLs (`SY_POOLS_API_URL` and `SA_POOLS_API_URL`), you need to check if these APIs are affected by the deprecation and update them accordingly. 3. **Verify and Test**: Ensure that the new endpoint is correctly integrated and test the functionality to confirm that everything works as expected. Since the file does not explicitly reference a subgraph endpoint, it seems there is no immediate change required here. However, you should verify if the APIs (`SY_POOLS_API_URL` and `SA_POOLS_API_URL`) are related to the subgraph and need updating. ### Steps to Verify and Update (if needed): 1. **Check API Documentation**: Verify if the APIs `https://prod-poly-v2.api.barnbridge.com/api/smartyield/pools` and `https://prod-poly-v2.api.barnbridge.com/api/smartalpha/pools` are affected by the subgraph deprecation. 2. **Contact API Provider**: If unsure, contact the BarnBridge team or check their documentation to confirm if these endpoints are impacted. 3. **Update Endpoints**: If the APIs are affected, update them to the new endpoints provided by BarnBridge. 4. **Test the Changes**: After updating, test the script to ensure it fetches data correctly and the TVL calculation works as expected. ### Example (if endpoints needed updating): ```javascript const SY_POOLS_API_URL = 'https://new-api.barnbridge.com/api/smartyield/pools'; const SA_POOLS_API_URL = 'https://new-api.barnbridge.com/api/smartalpha/pools'; ``` Since there is no direct subgraph endpoint in this file, no immediate changes are required unless the APIs are confirmed to be affected. If they are, follow the steps above to update and test the new endpoints.
Changes on projects/swarm-markets/index.js To address the issue of updating the subgraph endpoint in the `projects/swarm-markets/index.js` file, follow these steps: 1. **Identify the New Subgraph Endpoint**: First, ensure that the subgraph has been upgraded to the network. You can check this on the [Graph Explorer](https://thegraph.com/explorer) or by contacting the subgraph development team. 2. **Create an API Key and Updated Query URL**: Once the subgraph is upgraded, create an API key and get the new query URL from Subgraph Studio. The new endpoint will be in the format: ``` https://api.studio.thegraph.com/query/// ``` 3. **Update the Endpoint in the Code**: Replace the old subgraph endpoint with the new one in the `SUBGRAPH_URL` constant. Here is the updated code snippet with a placeholder for the new subgraph endpoint: ```javascript /*================================================== Modules ==================================================*/ const sdk = require("../../sdk"); const BigNumber = require("bignumber.js"); const { request, gql } = require("graphql-request"); // Update this URL with the new subgraph endpoint const SUBGRAPH_URL = "https://api.studio.thegraph.com/query///"; const XTokenWrapperContractAddress = "0x2b9dc65253c035eb21778cb3898eab5a0ada0cce"; /*================================================== TVL ==================================================*/ 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; } /*================================================== Exports ==================================================*/ module.exports = { name: "Swarm Markets", token: "SMT", category: "DEXes", start: 1627776000, // Sunday, Aug 01, 2021 12:00:00.000 AM +UTC tvl, // tvl function should be kept above tokenHolderMap tokenHolderMap, }; ``` ### Summary 1. Verify the subgraph has been upgraded. 2. Obtain the new subgraph endpoint URL. 3. Update the `SUBGRAPH_URL` constant in the code with the new endpoint. This will ensure that your application continues to function correctly after the hosted service is deprecated.
Changes on projects/siren/index.js To address the issue of updating the subgraph endpoint in the `projects/siren/index.js` file, follow these steps: 1. **Identify the New Endpoint**: First, ensure that the subgraph has been upgraded to The Graph's decentralized network. You can check this on the [Graph Explorer](https://thegraph.com/explorer) or by contacting the subgraph development team. 2. **Create an API Key and Get the New Query URL**: If the subgraph has been upgraded, create an API key and get the new query URL from Subgraph Studio. The new endpoint will be in the format: ``` https://api.studio.thegraph.com/query/// ``` 3. **Update the Endpoint in the Code**: Replace the old `GRAPH_URL` with the new endpoint URL. Here is the updated code snippet for `projects/siren/index.js`: ```javascript /*================================================== Modules ==================================================*/ const { request, gql } = require("graphql-request"); const BigNumber = require('bignumber.js'); const sdk = require('../../sdk'); // Replace the old GRAPH_URL with the new endpoint URL const GRAPH_URL = 'https://api.studio.thegraph.com/query///'; /*================================================== TVL ==================================================*/ 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']; // Get collateral in AMM 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(); // Get collateral in Markets 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 } } } ` /*================================================== Exports ==================================================*/ module.exports = { name: 'Siren', token: 'SI', category: 'derivatives', start: 1605574800, // Nov-17-2020 01:00:00 AM +UTC tvl } ``` ### Summary 1. Verify the subgraph has been upgraded. 2. Obtain the new endpoint URL from Subgraph Studio. 3. Update the `GRAPH_URL` in the `projects/siren/index.js` file with the new endpoint URL. This will ensure that the subgraph queries continue to function correctly after the hosted service is deprecated.
Changes on chains/polygon/projects/insurace/index.js To address the issue of updating the subgraph endpoint in the `chains/polygon/projects/insurace/index.js` file, follow these steps: 1. **Identify the Current Subgraph Endpoint**: Locate the current subgraph endpoint URL in the file. In this case, it seems there is no direct subgraph endpoint URL in the provided code snippet. However, if there is one, it would typically be an HTTP URL used in an `axios.get` request or similar. 2. **Upgrade the Subgraph**: Follow the [upgrade guide](https://thegraph.com/docs/en/sunrise/#how-do-i-upgrade-my-hosted-service-subgraph) to upgrade the subgraph to The Graph's decentralized network. This step might involve actions outside of this codebase, such as deploying the subgraph to the decentralized network. 3. **Create an API Key and Updated Query URL**: Once the subgraph is upgraded, create an API key and obtain the new query URL from Subgraph Studio. The new URL will be in the format: ``` https://api.studio.thegraph.com/query/// ``` 4. **Update the Endpoint in the Code**: Replace the old subgraph endpoint URL with the new one in the code. Since the provided code snippet does not show a direct subgraph endpoint, you might need to search the entire file or related files for any subgraph endpoint references. Here is an example of how you might update the endpoint if it were present in the code: ```javascript const axios = require("axios"); // Old endpoint (example) // const SUBGRAPH_URL = "https://api.thegraph.com/subgraphs/name/old-subgraph"; // New endpoint const SUBGRAPH_URL = "https://api.studio.thegraph.com/query///"; 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, // Stakers Pool creation time, Friday, 03 September 2021 07:21:14 AM tvl }; ``` In this example, replace ``, ``, and `` with the actual values obtained from Subgraph Studio. If there is no subgraph endpoint in this specific file, ensure to check other related files or configurations where the subgraph endpoint might be referenced.
Changes on projects/balancer/index.js To address the issue of updating the subgraph endpoint in the `projects/balancer/index.js` file, follow these steps: 1. **Identify the Current Endpoint**: The current subgraph endpoint is: ```javascript const tokensApi = 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-v2'; ``` 2. **Upgrade the Subgraph**: Follow the [upgrade guide](https://thegraph.com/docs/en/sunrise/#how-do-i-upgrade-my-hosted-service-subgraph) to upgrade the subgraph to The Graph's decentralized network. This step is crucial and should be done by the subgraph owner or maintainer. 3. **Create an API Key and Get the New Endpoint**: Once the subgraph is upgraded, create an API key and get the new query URL from Subgraph Studio. The new endpoint will look something like: ``` https://api.studio.thegraph.com/query/// ``` 4. **Update the Endpoint in the Code**: Replace the old endpoint with the new one in the `projects/balancer/index.js` file. Here is the updated code snippet with a placeholder for the new endpoint: ```javascript /*================================================== Modules ==================================================*/ 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'; // Update this line with the new endpoint const tokensApi = 'https://api.studio.thegraph.com/query///'; /*================================================== TVL ==================================================*/ async function tvl(timestamp, block) { let balances = { '0x0000000000000000000000000000000000000000': '0', // ETH }; 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; } /*================================================== Exports ==================================================*/ module.exports = { name: 'Balancer', token: 'BAL', category: 'dexes', start : 1582761600, // 02/27/2020 @ 12:00am (UTC) tvl } ``` Replace ``, ``, and `` with the actual values obtained from Subgraph Studio. This update ensures that the subgraph endpoint is pointing to the new network endpoint, complying with the deprecation of the hosted service.
Changes on projects/synthetix/index.js To address the issue of updating the subgraph endpoint for the Synthetix project, we need to follow the provided guide and update the endpoint URL in the `projects/synthetix/index.js` file. Here is a step-by-step plan: 1. **Check for the Updated Subgraph**: Verify if the Synthetix subgraph has been upgraded to the network by checking the [Graph Explorer](https://thegraph.com/explorer). 2. **Create an API Key and Get the New Endpoint**: If the subgraph has been upgraded, create an API key and get the new query URL from Subgraph Studio as per the [upgrade guide](https://thegraph.com/docs/en/sunrise/#how-do-i-upgrade-my-hosted-service-subgraph). 3. **Update the Endpoint in the Code**: Replace the old subgraph endpoint with the new one in the `projects/synthetix/index.js` file. Here is the updated code snippet with the new endpoint: ```javascript /*================================================== Modules ==================================================*/ 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"); /*================================================== Settings ==================================================*/ const synthetixState = "0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82"; const synthetix = "0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F"; const exchangeRates = "0xd69b189020EF614796578AfE4d10378c5e7e1138"; const systemSettings = "0xD3C8d372bFCd36c2B452639a7ED6ef7dbFDC56F8"; const snxGraphEndpoint = "https://api.studio.thegraph.com/query///"; // Replace with actual endpoint /*================================================== Main ==================================================*/ 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", // SNX ], }), 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", // sUSD ], }), 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, }; } // Uses graph protocol to run through SNX contract. Since there is a limit of 100 results per query // we can use graph-results-pager library to increase the limit. 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, // top 1000 SNX holders with collateral. At the time of this commit, there are 51,309 SNX holders. (7/27/2020) }); } 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(); } /*================================================== Exports ==================================================*/ module.exports = { name: "Synthetix", token: "SNX", category: "derivatives", start: 1565287200, // Fri Aug 09 2019 00:00:00 tvl, }; ``` Make sure to replace ``, ``, and `` with the actual values obtained from Subgraph Studio. This will ensure that the Synthetix project continues to function correctly with the new subgraph endpoint.
pairbot[bot] commented 3 months ago

Not Found