Docs
Поиск⌘ K
  • Главная страница
  • О The Graph
  • Поддерживаемые сети
  • Protocol Contracts
  • Субграфы
    • Субпотоки
      • Token API
        • AI Suite
          • Индексирование
            • Ресурсы
              Субграфы > Разработка

              6 минуты

              Developer FAQ

              На этой странице собраны некоторые из наиболее частых вопросов для разработчиков, использующих The Graph.

              Вопросы, связанные с субграфом

              1. What is a Subgraph?

              A Subgraph is a custom API built on blockchain data. Subgraphs are queried using the GraphQL query language and are deployed to a Graph Node using The Graph CLI. Once deployed and published to The Graph’s decentralized network, Indexers process Subgraphs and make them available for Subgraph consumers to query.

              2. What is the first step to create a Subgraph?

              To successfully create a Subgraph, you will need to install The Graph CLI. Review the Quick Start to get started. For detailed information, see Creating a Subgraph.

              3. Can I still create a Subgraph if my smart contracts don’t have events?

              It is highly recommended that you structure your smart contracts to have events associated with data you are interested in querying. Event handlers in the Subgraph are triggered by contract events and are the fastest way to retrieve useful data.

              If the contracts you work with do not contain events, your Subgraph can use call and block handlers to trigger indexing. However, this is not recommended, as performance will be significantly slower.

              4. Can I change the GitHub account associated with my Subgraph?

              No. Once a Subgraph is created, the associated GitHub account cannot be changed. Please make sure to carefully consider this before creating your Subgraph.

              5. How do I update a Subgraph on mainnet?

              You can deploy a new version of your Subgraph to Subgraph Studio using the CLI. This action maintains your Subgraph private, but once you’re happy with it, you can publish to Graph Explorer. This will create a new version of your Subgraph that Curators can start signaling on.

              6. Is it possible to duplicate a Subgraph to another account or endpoint without redeploying?

              You have to redeploy the Subgraph, but if the Subgraph ID (IPFS hash) doesn’t change, it won’t have to sync from the beginning.

              7. How do I call a contract function or access a public state variable from my Subgraph mappings?

              Take a look at Access to smart contract state inside the section AssemblyScript API.

              8. Can I import ethers.js or other JS libraries into my Subgraph mappings?

              В настоящее время нет, так как мэппинги написаны на языке AssemblyScript.

              Одним из возможных альтернативных решений является хранение необработанных данных в объектах и выполнение логики, для которой требуются библиотеки JS на клиенте.

              9. При прослушивании нескольких контрактов, возможно ли выбрать порядок прослушивания событий контрактов?

              Within a Subgraph, the events are always processed in the order they appear in the blocks, regardless of whether that is across multiple contracts or not.

              10. Чем шаблоны отличаются от источников данных?

              Templates allow you to create data sources quickly, while your Subgraph is indexing. Your contract might spawn new contracts as people interact with it. Since you know the shape of those contracts (ABI, events, etc.) upfront, you can define how you want to index them in a template. When they are spawned, your Subgraph will create a dynamic data source by supplying the contract address.

              Check out the “Instantiating a data source template” section on: Data Source Templates.

              11. Is it possible to set up a Subgraph using graph init from graph-cli with two contracts? Or should I manually add another dataSource in subgraph.yaml after running graph init?

              Yes. On graph init command itself you can add multiple dataSources by entering contracts one after the other.

              You can also use graph add command to add a new dataSource.

              12. В каком порядке вызываются обработчики событий, блоков и вызовов для источника данных?

              Event and call handlers are first ordered by transaction index within the block. Event and call handlers within the same transaction are ordered using a convention: event handlers first then call handlers, each type respecting the order they are defined in the manifest. Block handlers are run after event and call handlers, in the order they are defined in the manifest. Also these ordering rules are subject to change.

              When new dynamic data source are created, the handlers defined for dynamic data sources will only start processing after all existing data source handlers are processed, and will repeat in the same sequence whenever triggered.

              13. Как убедиться, что я использую последнюю версию graph-node для своих локальных развертываний?

              Вы можете запустить следующую команду:

              1docker pull graphprotocol/graph-node:latest

              Примечание: docker / docker-compose всегда будет использовать ту версию graph-node, которая была получена при первом запуске, поэтому убедитесь, что используете последнюю версию graph-node.

              14. Каков рекомендуемый способ создания “автоматически сгенерированных” идентификаторов для объекта при обработке событий?

              If only one entity is created during the event and if there’s nothing better available, then the transaction hash + log index would be unique. You can obfuscate these by converting that to Bytes and then piping it through crypto.keccak256 but this won’t make it more unique.

              15. Can I delete my Subgraph?

              Yes, you can delete and transfer your Subgraph.

              Вопросы, связанный с сетью

              16. Какие сети поддерживает The Graph?

              You can find the list of the supported networks here.

              17. Можно ли различать сети (майннет, Sepolia, локальную) внутри обработчиков событий?

              Yes. You can do this by importing graph-ts as per the example below:

              1import { dataSource } from '@graphprotocol/graph-ts'23dataSource.network()4dataSource.address()

              18. Поддерживаете ли Вы обработчики блоков и вызовов на Sepolia?

              Да. Sepolia поддерживает обработчики блоков, обработчики вызовов и обработчики событий. Следует отметить, что обработчики событий намного более эффективны, чем два других обработчика, и они поддерживаются в каждой сети, совместимой с EVM.

              Indexing & Querying Related

              19. Можно ли указать, с какого блока следует начинать индексирование?

              Yes. dataSources.source.startBlock in the subgraph.yaml file specifies the number of the block that the dataSource starts indexing from. In most cases, we suggest using the block where the contract was created: Start blocks

              20. What are some tips to increase the performance of indexing? My Subgraph is taking a very long time to sync

              Yes, you should take a look at the optional start block feature to start indexing from the block where the contract was deployed: Start blocks

              21. Is there a way to query the Subgraph directly to determine the latest block number it has indexed?

              Да! Попробуйте выполнить следующую команду, заменив “organization/subgraphName” на название организации, под которой она опубликована, и имя Вашего субграфа:

              1curl -X POST -d '{ "query": "{indexingStatusForCurrentVersion(subgraphName: \"organization/subgraphName\") { chains { latestBlock { hash number }}}}"}' https://api.thegraph.com/index-node/graphql

              22. Есть ли ограничение на количество объектов, которые The Graph может вернуть за один запрос?

              По умолчанию ответы на запросы ограничены 100 единицами на коллекцию. Если Вы хотите получить больше, Вы можете довести количество до 1000 единиц на коллекцию, а для получения ещё большего количества можно использовать пагинацию:

              1someCollection(first: 1000, skip: <number>) { ... }

              23. If my dapp frontend uses The Graph for querying, do I need to write my API key into the frontend directly? What if we pay query fees for users – will malicious users cause our query fees to be very high?

              Currently, the recommended approach for a dapp is to add the key to the frontend and expose it to end users. That said, you can limit that key to a hostname, like yourdapp.io and Subgraph. The gateway is currently being run by Edge & Node. Part of the responsibility of a gateway is to monitor for abusive behavior and block traffic from malicious clients.

              Прочее

              24. Можно ли использовать Apollo Federation поверх graph-node?

              Federation пока не поддерживается. В настоящее время Вы можете использовать объединение схем либо на клиенте, либо через прокси-сервис.

              25. Я хочу внести свой вклад или добавить задачу на GitHub. Где я могу найти репозитории с открытым исходным кодом?

              • graph-node⁠
              • graph-tooling⁠
              • graph-docs⁠
              • graph-client⁠
              ⁠Редактировать на GitHub⁠

              Удаление субграфаВыставление счетов
              На этой странице
              • Вопросы, связанные с субграфом
              • 1. What is a Subgraph?
              • 2. What is the first step to create a Subgraph?
              • 3. Can I still create a Subgraph if my smart contracts don’t have events?
              • 4. Can I change the GitHub account associated with my Subgraph?
              • 5. How do I update a Subgraph on mainnet?
              • 6. Is it possible to duplicate a Subgraph to another account or endpoint without redeploying?
              • 7. How do I call a contract function or access a public state variable from my Subgraph mappings?
              • 8. Can I import ethers.js or other JS libraries into my Subgraph mappings?
              • 9. При прослушивании нескольких контрактов, возможно ли выбрать порядок прослушивания событий контрактов?
              • 10. Чем шаблоны отличаются от источников данных?
              • 11. Is it possible to set up a Subgraph using graph init from graph-cli with two contracts? Or should I manually add another dataSource in subgraph.yaml after running graph init?
              • 12. В каком порядке вызываются обработчики событий, блоков и вызовов для источника данных?
              • 13. Как убедиться, что я использую последнюю версию graph-node для своих локальных развертываний?
              • 14. Каков рекомендуемый способ создания “автоматически сгенерированных” идентификаторов для объекта при обработке событий?
              • 15. Can I delete my Subgraph?
              • Вопросы, связанный с сетью
              • 16. Какие сети поддерживает The Graph?
              • 17. Можно ли различать сети (майннет, Sepolia, локальную) внутри обработчиков событий?
              • 18. Поддерживаете ли Вы обработчики блоков и вызовов на Sepolia?
              • Indexing & Querying Related
              • 19. Можно ли указать, с какого блока следует начинать индексирование?
              • 20. What are some tips to increase the performance of indexing? My Subgraph is taking a very long time to sync
              • 21. Is there a way to query the Subgraph directly to determine the latest block number it has indexed?
              • 22. Есть ли ограничение на количество объектов, которые The Graph может вернуть за один запрос?
              • 23. If my dapp frontend uses The Graph for querying, do I need to write my API key into the frontend directly? What if we pay query fees for users – will malicious users cause our query fees to be very high?
              • Прочее
              • 24. Можно ли использовать Apollo Federation поверх graph-node?
              • 25. Я хочу внести свой вклад или добавить задачу на GitHub. Где я могу найти репозитории с открытым исходным кодом?
              The GraphСтатусТестовая сетьБрундовые ресурсыФорумБезопасностьПолитика конфиденциальностиУсловия обслуживания