diff --git a/nginx.conf b/nginx.conf index ef61184c6feb..d14dc148e2f1 100644 --- a/nginx.conf +++ b/nginx.conf @@ -79,6 +79,7 @@ http { rewrite ^/docs/([a-zA-Z][a-zA-Z])/cookbook/timeseries/$ $scheme://$http_host/docs/$1/subgraphs/best-practices/timeseries/ permanent; rewrite ^/docs/([a-zA-Z][a-zA-Z])/subgraphs/cookbook/timeseries/$ $scheme://$http_host/docs/$1/subgraphs/best-practices/timeseries/ permanent; rewrite ^/docs/([a-zA-Z][a-zA-Z])/cookbook/transfer-to-the-graph/$ $scheme://$http_host/docs/$1/subgraphs/cookbook/transfer-to-the-graph/ permanent; + rewrite ^/docs/([a-zA-Z][a-zA-Z])/subgraphs/cookbook/(.*?)/?$ $scheme://$http_host/docs/$1/subgraphs/guides/$2/ permanent; rewrite ^/docs/([a-zA-Z][a-zA-Z])/curating/$ $scheme://$http_host/docs/$1/resources/roles/curating/ permanent; rewrite ^/docs/([a-zA-Z][a-zA-Z])/delegating/$ $scheme://$http_host/docs/$1/resources/roles/delegating/delegating/ permanent; rewrite ^/docs/([a-zA-Z][a-zA-Z])/deploying/deploy-using-subgraph-studio/$ $scheme://$http_host/docs/$1/subgraphs/developing/deploying/using-subgraph-studio/ permanent; diff --git a/website/src/pages/ar/subgraphs/_meta-titles.json b/website/src/pages/ar/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/ar/subgraphs/_meta-titles.json +++ b/website/src/pages/ar/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/ar/subgraphs/_meta.js b/website/src/pages/ar/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/ar/subgraphs/_meta.js +++ b/website/src/pages/ar/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/ar/subgraphs/cookbook/arweave.mdx b/website/src/pages/ar/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index c1ec421993b4..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Building Subgraphs on Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. - -## What is Arweave? - -The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. - -Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## What are Arweave Subgraphs? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Building an Arweave Subgraph - -To be able to build and deploy Arweave Subgraphs, you need two packages: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Subgraph's components - -There are three components of a subgraph: - -### 1. Manifest - `subgraph.yaml` - -Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. - -### 2. Schema - `schema.graphql` - -Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. - -During subgraph development there are two key commands: - -``` -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -## تعريف Subgraph Manifest - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet - -Arweave data sources support two types of handlers: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> The source.owner can be the owner's address, or their Public Key. -> -> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## تعريف المخطط - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Querying an Arweave Subgraph - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## أمثلة على الـ Subgraphs - -Here is an example subgraph for reference: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Can a subgraph index Arweave and other chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can I index the stored files on Arweave? - -Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). - -### Can I identify Bundlr bundles in my subgraph? - -This is not currently supported. - -### How can I filter transactions to a specific account? - -The source.owner can be the user's public key or account address. - -### What is the current encryption format? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/ar/subgraphs/cookbook/enums.mdx b/website/src/pages/ar/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 9508aa864b6c..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## مصادر إضافية - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ar/subgraphs/cookbook/grafting.mdx b/website/src/pages/ar/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 704e7df3f3f6..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Replace a Contract and Keep its History With Grafting ---- - -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. - -## What is Grafting? - -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. - -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: - -- يضيف أو يزيل أنواع الكيانات -- يزيل الصفات من أنواع الكيانات -- It adds nullable attributes to entity types -- It turns non-nullable attributes into nullable attributes -- It adds values to enums -- It adds or removes interfaces -- يغير للكيانات التي يتم تنفيذ الواجهة لها - -For more information, you can check: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## Building an Existing Subgraph - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## تعريف Subgraph Manifest - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Grafting Manifest Definition - -Grafting requires adding two new items to the original subgraph manifest: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Deploying the Base Subgraph - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It returns something like this: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. - -## Deploying the Grafting Subgraph - -The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It should return the following: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## مصادر إضافية - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ar/subgraphs/cookbook/near.mdx b/website/src/pages/ar/subgraphs/cookbook/near.mdx deleted file mode 100644 index bdbe8e518a6b..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: بناء Subgraphs على NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## ما هو NEAR؟ - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## ماهي NEAR subgraphs؟ - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- معالجات الكتل(Block handlers): يتم تشغيلها على كل كتلة جديدة -- معالجات الاستلام (Receipt handlers): يتم تشغيلها في كل مرة يتم فيها تنفيذ رسالة على حساب محدد - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> الاستلام (Receipt) هو الكائن الوحيد القابل للتنفيذ في النظام. عندما نتحدث عن "معالجة الإجراء" على منصة NEAR ، فإن هذا يعني في النهاية "تطبيق الاستلامات" في مرحلة ما. - -## بناء NEAR Subgraph - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. - -هناك ثلاثة جوانب لتعريف الـ subgraph: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -During subgraph development there are two key commands: - -```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -### تعريف Subgraph Manifest - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -مصادر بيانات NEAR تدعم نوعين من المعالجات: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### تعريف المخطط - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## نشر NEAR Subgraph - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -The node configuration will depend on where the subgraph is being deployed. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Local Graph Node (based on default configuration) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -بمجرد نشر الـ subgraph الخاص بك ، سيتم فهرسته بواسطة Graph Node. يمكنك التحقق من تقدمه عن طريق الاستعلام عن الـ subgraph نفسه: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexing NEAR with a Local Graph Node - -تشغيل Graph Node التي تقوم بفهرسة NEAR لها المتطلبات التشغيلية التالية: - -- NEAR Indexer Framework مع أجهزة Firehose -- مكونات NEAR Firehose -- تكوين Graph Node مع Firehose endpoint - -سوف نقدم المزيد من المعلومات حول تشغيل المكونات أعلاه قريبًا. - -## الاستعلام عن NEAR Subgraph - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## أمثلة على الـ Subgraphs - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### How does the beta work? - -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! - -### Can a subgraph index both NEAR and EVM chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can subgraphs react to more specific triggers? - -حاليًا ، يتم دعم مشغلات الكتلة(Block) والاستلام(Receipt). نحن نبحث في مشغلات استدعاءات الدوال لحساب محدد. نحن مهتمون أيضًا بدعم مشغلات الأحداث ، بمجرد حصول NEAR على دعم محلي للأحداث. - -### Will receipt handlers trigger for accounts and their sub-accounts? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? - -هذا غير مدعوم. نحن بصدد تقييم ما إذا كانت هذه الميزة مطلوبة للفهرسة. - -### Can I use data source templates in my NEAR subgraph? - -هذا غير مدعوم حاليا. نحن بصدد تقييم ما إذا كانت هذه الميزة مطلوبة للفهرسة. - -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? - -الوظيفة المعلقة ليست مدعومة لـ NEAR subgraphs. وفي غضون ذلك ، يمكنك نشر إصدار جديد على subgraph مختلف "مسمى" ، وبعد ذلك عندما تتم مزامنته مع رأس السلسلة ، يمكنك إعادة النشر إلى الـ subgraph الأساسي "المسمى" ، والذي سيستخدم نفس ID النشر الأساسي ، لذلك ستتم مزامنة الـ subgraph الرئيسي على الفور. - -### My question hasn't been answered, where can I get more help building NEAR subgraphs? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## المراجع - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ar/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/ar/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 485f597e25ba..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## نظره عامة - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ar/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/ar/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 3bacc1f60003..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Quick and Easy Subgraph Debugging Using Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## حسنا، ما هو؟ - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## ماذا؟! كيف؟ - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## من فضلك ، أرني بعض الأكواد! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -الطريقة المعتادة لمحاولة الإصلاح هي: - -1. إجراء تغيير في مصدر الـ mappings ، والذي تعتقد أنه سيحل المشكلة (وأنا أعلم أنه لن يحلها). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. الانتظار حتى تتم المزامنة. -4. إذا حدثت المشكلة مرة أخرى ، فارجع إلى 1! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. قم بإجراء تغيير في مصدر الـ mappings ، والذي تعتقد أنه سيحل المشكلة. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. إذا حدثت المشكلة مرة أخرى ، فارجع إلى 1! - -الآن ، قد يكون لديك سؤالان: - -1. ماهو fork-base؟؟؟ -2. ما الذي نقوم بتفريعه (Forking)؟! - -وأنا أجيب: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. الـتفريع سهل ، فلا داعي للقلق: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -لذلك ، هذا ما أفعله: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ar/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/ar/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index f713ec3a5e76..000000000000 --- a/website/src/pages/ar/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Example - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### مصادر إضافية - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/en/subgraphs/cookbook/_meta.js b/website/src/pages/ar/subgraphs/guides/_meta.js similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/_meta.js rename to website/src/pages/ar/subgraphs/guides/_meta.js diff --git a/website/src/pages/en/subgraphs/cookbook/arweave.mdx b/website/src/pages/ar/subgraphs/guides/arweave.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/arweave.mdx rename to website/src/pages/ar/subgraphs/guides/arweave.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/enums.mdx b/website/src/pages/ar/subgraphs/guides/enums.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/enums.mdx rename to website/src/pages/ar/subgraphs/guides/enums.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/grafting.mdx b/website/src/pages/ar/subgraphs/guides/grafting.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/grafting.mdx rename to website/src/pages/ar/subgraphs/guides/grafting.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/near.mdx b/website/src/pages/ar/subgraphs/guides/near.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/near.mdx rename to website/src/pages/ar/subgraphs/guides/near.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/polymarket.mdx b/website/src/pages/ar/subgraphs/guides/polymarket.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/polymarket.mdx rename to website/src/pages/ar/subgraphs/guides/polymarket.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/ar/subgraphs/guides/secure-api-keys-nextjs.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/secure-api-keys-nextjs.mdx rename to website/src/pages/ar/subgraphs/guides/secure-api-keys-nextjs.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/ar/subgraphs/guides/subgraph-debug-forking.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/subgraph-debug-forking.mdx rename to website/src/pages/ar/subgraphs/guides/subgraph-debug-forking.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/ar/subgraphs/guides/subgraph-uncrashable.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/subgraph-uncrashable.mdx rename to website/src/pages/ar/subgraphs/guides/subgraph-uncrashable.mdx diff --git a/website/src/pages/en/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/ar/subgraphs/guides/transfer-to-the-graph.mdx similarity index 100% rename from website/src/pages/en/subgraphs/cookbook/transfer-to-the-graph.mdx rename to website/src/pages/ar/subgraphs/guides/transfer-to-the-graph.mdx diff --git a/website/src/pages/cs/subgraphs/_meta-titles.json b/website/src/pages/cs/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/cs/subgraphs/_meta-titles.json +++ b/website/src/pages/cs/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/cs/subgraphs/_meta.js b/website/src/pages/cs/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/cs/subgraphs/_meta.js +++ b/website/src/pages/cs/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/cs/subgraphs/cookbook/arweave.mdx b/website/src/pages/cs/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index d59897ad4e03..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Vytváření podgrafů na Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -V této příručce se dozvíte, jak vytvořit a nasadit subgrafy pro indexování blockchainu Arweave. - -## Co je Arweave? - -Protokol Arweave umožňuje vývojářům ukládat data trvale a to je hlavní rozdíl mezi Arweave a IPFS, kde IPFS tuto funkci postrádá; trvalé uložení a soubory uložené na Arweave nelze měnit ani mazat. - -Společnost Arweave již vytvořila řadu knihoven pro integraci protokolu do řady různých programovacích jazyků. Další informace naleznete zde: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## Co jsou podgrafy Arweave? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Vytvoření podgrafu Arweave - -Abyste mohli sestavit a nasadit Arweave Subgraphs, potřebujete dva balíčky: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Komponenty podgrafu - -Podgraf má tři Komponenty: - -### 1. Manifest - `subgraph.yaml` - -Definuje zdroje dat, které jsou předmětem zájmu, a způsob jejich zpracování. Arweave je nový druh datového zdroje. - -### 2. Schema - `schema.graphql` - -Zde definujete, na která data se chcete po indexování subgrafu pomocí jazyka GraphQL dotazovat. Je to vlastně podobné modelu pro API, kde model definuje strukturu těla požadavku. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -Jedná se o logiku, která určuje, jak mají být data načtena a uložena, když někdo komunikuje se zdroji dat, kterým nasloucháte. Data se přeloží a uloží na základě schématu, které jste uvedli. - -Při vývoji podgrafů existují dva klíčové příkazy: - -``` -$ graph codegen # generuje typy ze souboru se schématem identifikovaným v manifestu -$ graph build # vygeneruje webové sestavení ze souborů AssemblyScript a připraví všechny dílčí soubory do složky /build -``` - -## Definice podgrafu Manifest - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Zdroje dat Arweave obsahují nepovinné pole source.owner, což je veřejný klíč peněženky Arweave - -Datové zdroje Arweave podporují dva typy zpracovatelů: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> Source.owner může být adresa vlastníka nebo jeho veřejný klíč. -> -> Transakce jsou stavebními kameny permaweb Arweave a jsou to objekty vytvořené koncovými uživateli. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Definice schématu - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript Mapování - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Nasazení podgrafu Arweave v Podgraf Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Dotazování podgrafu Arweave - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Příklady podgrafů - -Zde je příklad podgrafu pro referenci: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Může podgraf indexovat Arweave a další řetězce? - -Ne, podgraf může podporovat zdroje dat pouze z jednoho řetězce/sítě. - -### Mohu indexovat uložené soubory v Arweave? - -V současné době The Graph indexuje pouze Arweave jako blockchain (jeho bloky a transakce). - -### Mohu identifikovat svazky Bundlr ve svém podgrafu? - -Toto není aktuálně podporováno. - -### Jak mohu filtrovat transakce na určitý účet? - -Source.owner může být veřejný klíč uživatele nebo adresa účtu. - -### Jaký je aktuální formát šifrování? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/cs/subgraphs/cookbook/enums.mdx b/website/src/pages/cs/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 71f3f784a0eb..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Další zdroje - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/cs/subgraphs/cookbook/grafting.mdx b/website/src/pages/cs/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index ca0ab0367451..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Nahrazení smlouvy a zachování její historie pomocí roubování ---- - -V této příručce se dozvíte, jak vytvářet a nasazovat nové podgrafy roubováním stávajících podgrafů. - -## Co je to roubování? - -Při roubování se znovu použijí data z existujícího podgrafu a začne se indexovat v pozdějším bloku. To je užitečné během vývoje, abyste se rychle dostali přes jednoduché chyby v mapování nebo abyste dočasně znovu zprovoznili existující podgraf po jeho selhání. Také ji lze použít při přidávání funkce do podgrafu, které trvá dlouho, než se indexuje od začátku. - -Štěpovaný podgraf může používat schéma GraphQL, které není totožné se schématem základního podgrafu, ale je s ním pouze kompatibilní. Musí to být platné schéma podgrafu jako takové, ale může se od schématu základního podgrafu odchýlit následujícími způsoby: - -- Přidává nebo odebírá typy entit -- Odstraňuje atributy z typů entit -- Přidává nulovatelné atributy k typům entit -- Mění nenulovatelné atributy na nulovatelné atributy -- Přidává hodnoty do enums -- Přidává nebo odebírá rozhraní -- Mění se, pro které typy entit je rozhraní implementováno - -Další informace naleznete na: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Důležité upozornění k roubování při aktualizaci na síť - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Proč je to důležité? - -Štěpování je výkonná funkce, která umožňuje "naroubovat" jeden podgraf na druhý, čímž efektivně přenese historická data ze stávajícího podgrafu do nové verze. Podgraf není možné naroubovat ze Sítě grafů zpět do Podgraf Studio. - -### Osvědčené postupy - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -Dodržováním těchto pokynů minimalizujete rizika a zajistíte hladší průběh migrace. - -## Vytvoření existujícího podgrafu - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Definice podgrafu Manifest - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Definice manifestu roubování - -Roubování vyžaduje přidání dvou nových položek do původního manifestu podgrafu: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Nasazení základního podgrafu - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Po dokončení ověřte, zda se podgraf správně indexuje. Pokud spustíte následující příkaz v The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Vrátí něco takového: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Jakmile ověříte, že se podgraf správně indexuje, můžete jej rychle aktualizovat pomocí roubování. - -## Nasazení podgrafu roubování - -Náhradní podgraf.yaml bude mít novou adresu smlouvy. K tomu může dojít při aktualizaci dapp, novém nasazení kontraktu atd. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Po dokončení ověřte, zda se podgraf správně indexuje. Pokud spustíte následující příkaz v The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Měla by vrátit následující: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Gratulujeme! Úspěšně jste naroubovali podgraf na jiný podgraf. - -## Další zdroje - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/cs/subgraphs/cookbook/near.mdx b/website/src/pages/cs/subgraphs/cookbook/near.mdx deleted file mode 100644 index dc65c11da629..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Vytváření podgrafů v NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## Co je NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## Co jsou podgrafy NEAR? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Obsluhy bloků: jsou spouštěny při každém novém bloku. -- Obsluhy příjmu: spouštějí se pokaždé, když je zpráva provedena na zadaném účtu. - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Příjemka je jediným objektem, který lze v systému použít. Když na platformě NEAR hovoříme o "zpracování transakce", znamená to v určitém okamžiku "použití účtenky". - -## Sestavení podgrafu NEAR - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Vytváření subgrafu NEAR je velmi podobné vytváření subgrafu, který indexuje Ethereum. - -Definice podgrafů má tři aspekty: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -Při vývoji podgrafů existují dva klíčové příkazy: - -```bash -$ graph codegen # generuje typy ze souboru se schématem identifikovaným v manifestu -$ graph build # vygeneruje webové sestavení ze souborů AssemblyScript a připraví všechny dílčí soubory do složky /build -``` - -### Definice podgrafu Manifest - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -Zdroje dat NEAR podporují dva typy zpracovatelů: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Definice schématu - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript Mapování - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Nasazení podgrafu NEAR - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -Konfigurace uzlů závisí na tom, kde je podgraf nasazen. - -### Podgraf Studio - -```sh -graph auth -graph deploy -``` - -### Místní uzel grafu (na základě výchozí konfigurace) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Jakmile je podgraf nasazen, bude indexován pomocí Graph Node. Jeho průběh můžete zkontrolovat dotazem na samotný podgraf: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexování NEAR pomocí místního uzlu grafu - -Spuštění grafu uzlu, který indexuje NEAR, má následující provozní požadavky: - -- Framework NEAR Indexer s instrumentací Firehose -- Komponenta(y) NEAR Firehose -- Uzel Graph s nakonfigurovaným koncovým bodem Firehose - -Brzy vám poskytneme další informace o provozu výše uvedených komponent. - -## Dotazování podgrafu NEAR - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Příklady podgrafů - -Zde je několik příkladů podgrafů: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### Jak funguje beta verze? - -Podpora NEAR je ve fázi beta, což znamená, že v API může dojít ke změnám, protože budeme pokračovat ve zdokonalování integrace. Napište nám prosím na adresu near@thegraph.com, abychom vás mohli podpořit při vytváření podgrafů NEAR a informovat vás o nejnovějším vývoji! - -### Může podgraf indexovat řetězce NEAR i EVM? - -Ne, podgraf může podporovat zdroje dat pouze z jednoho řetězce/sítě. - -### Mohou podgrafy reagovat na specifičtější spouštěče? - -V současné době jsou podporovány pouze spouštěče Blok a Příjem. Zkoumáme spouštěče pro volání funkcí na zadaném účtu. Máme také zájem o podporu spouštěčů událostí, jakmile bude mít NEAR nativní podporu událostí. - -### Budou se obsluhy příjmu spouštět pro účty a jejich podúčty? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Mohou podgrafy NEAR během mapování volat zobrazení na účty NEAR? - -To není podporováno. Vyhodnocujeme, zda je tato funkce pro indexování nutná. - -### Mohu v podgrafu NEAR používat šablony zdrojů dat? - -Tato funkce není v současné době podporována. Vyhodnocujeme, zda je tato funkce pro indexování nutná. - -### Podgrafy Ethereum podporují verze "pending" a "current", jak mohu nasadit verzi "pending" podgrafu NEAR? - -Pro podgrafy NEAR zatím nejsou podporovány čekající funkce. V mezidobí můžete novou verzi nasadit do jiného "pojmenovaného" podgrafu a po jeho synchronizaci s hlavou řetězce ji můžete znovu nasadit do svého hlavního "pojmenovaného" podgrafu, který bude používat stejné ID nasazení, takže hlavní podgraf bude okamžitě synchronizován. - -### Moje otázka nebyla zodpovězena, kde mohu získat další pomoc při vytváření podgrafů NEAR? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## Odkazy: - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/cs/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/cs/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index de502a0ed526..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Jak zabezpečit klíče API pomocí komponent serveru Next.js ---- - -## Přehled - -K řádnému zabezpečení našeho klíče API před odhalením ve frontendu naší aplikace můžeme použít [komponenty serveru Next.js](https://nextjs.org/docs/app/building-your-application/rendering/server-components). Pro další zvýšení zabezpečení našeho klíče API můžeme také [omezit náš klíč API na určité podgrafy nebo domény v Podgraf Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -V této kuchařce probereme, jak vytvořit serverovou komponentu Next.js, která se dotazuje na podgraf a zároveň skrývá klíč API před frontend. - -### Upozornění - -- Součásti serveru Next.js nechrání klíče API před odčerpáním pomocí útoků typu odepření služby. -- Brány Graf síť mají zavedené strategie detekce a zmírňování odepření služby, avšak použití serverových komponent může tyto ochrany oslabit. -- Server komponenty Next.js přinášejí rizika centralizace, protože může dojít k výpadku serveru. - -### Proč je to důležité - -Ve standardní aplikaci React mohou být klíče API obsažené v kódu frontendu vystaveny na straně klienta, což představuje bezpečnostní riziko. Soubory `.env` se sice běžně používají, ale plně klíče nechrání, protože kód Reactu se spouští na straně klienta a vystavuje klíč API v hlavičkách. Serverové komponenty Next.js tento problém řeší tím, že citlivé operace zpracovávají na straně serveru. - -### Použití vykreslování na straně klienta k dotazování podgrafu - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- Klíč API od [Subgraph Studio](https://thegraph.com/studio) -- Základní znalosti Next.js a React. -- Existující projekt Next.js, který používá [App Router](https://nextjs.org/docs/app). - -## Kuchařka krok za krokem - -### Krok 1: Nastavení proměnných prostředí - -1. V kořeni našeho projektu Next.js vytvořte soubor `.env.local`. -2. Přidejte náš klíč API: `API_KEY=`. - -### Krok 2: Vytvoření součásti serveru - -1. V adresáři `components` vytvořte nový soubor `ServerComponent.js`. -2. K nastavení komponenty serveru použijte přiložený ukázkový kód. - -### Krok 3: Implementace požadavku API na straně serveru - -Do souboru `ServerComponent.js` přidejte následující kód: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Krok 4: Použití komponenty serveru - -1. V našem souboru stránky (např. `pages/index.js`) importujte `ServerComponent`. -2. Vykreslení komponenty: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Krok 5: Spusťte a otestujte náš Dapp - -Spusťte naši aplikaci Next.js pomocí `npm run dev`. Ověřte, že serverová komponenta načítá data bez vystavení klíče API. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Závěr - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/cs/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/cs/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 4673b362c360..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Rychlé a snadné ladění podgrafů pomocí vidliček ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## Ok, co to je? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## Co?! Jak? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## Ukažte mi prosím nějaký kód! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -Obvyklý způsob, jak se pokusit o opravu, je: - -1. Proveďte změnu ve zdroji mapování, která podle vás problém vyřeší (zatímco já vím, že ne). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Počkejte na synchronizaci. -4. Pokud se opět rozbije, vraťte se na 1, jinak: Hurá! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Proveďte změnu ve zdroji mapování, která podle vás problém vyřeší. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. Pokud se opět rozbije, vraťte se na 1, jinak: Hurá! - -Nyní můžete mít 2 otázky: - -1. fork-base co??? -2. Vidličkování kdo?! - -A já odpovídám: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Vidličkování je snadné, není třeba se potit: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -Takže to dělám takhle: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. Zkontroluji protokoly vytvořené místním graf uzlem a hurá, zdá se, že vše funguje. -5. Nasadím svůj nyní již bezchybný podgraf do vzdáleného uzlu Graf a žiji šťastně až do smrti! (bez brambor) diff --git a/website/src/pages/cs/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/cs/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 53750dd1cbee..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Generátor kódu bezpečného podgrafu ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Proč se integrovat s aplikací Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- Framework také obsahuje způsob (prostřednictvím konfiguračního souboru), jak vytvořit vlastní, ale bezpečné funkce setteru pro skupiny proměnných entit. Tímto způsobem není možné, aby uživatel načetl/použil zastaralou entitu grafu, a také není možné zapomenout uložit nebo nastavit proměnnou, kterou funkce vyžaduje. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Podgraf Uncrashable lze spustit jako volitelný příznak pomocí příkazu Graph CLI codegen. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/cs/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/cs/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 3e4f8eee8ccf..000000000000 --- a/website/src/pages/cs/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Použitím [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Příklad - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Další zdroje - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ar/subgraphs/cookbook/_meta.js b/website/src/pages/cs/subgraphs/guides/_meta.js similarity index 74% rename from website/src/pages/ar/subgraphs/cookbook/_meta.js rename to website/src/pages/cs/subgraphs/guides/_meta.js index 1093ca048416..e642f12ef11d 100644 --- a/website/src/pages/ar/subgraphs/cookbook/_meta.js +++ b/website/src/pages/cs/subgraphs/guides/_meta.js @@ -1,6 +1,4 @@ export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', 'subgraph-debug-forking': '', near: '', arweave: '', diff --git a/website/src/pages/it/subgraphs/cookbook/arweave.mdx b/website/src/pages/cs/subgraphs/guides/arweave.mdx similarity index 86% rename from website/src/pages/it/subgraphs/cookbook/arweave.mdx rename to website/src/pages/cs/subgraphs/guides/arweave.mdx index 2372025621d1..08e6c4257268 100644 --- a/website/src/pages/it/subgraphs/cookbook/arweave.mdx +++ b/website/src/pages/cs/subgraphs/guides/arweave.mdx @@ -2,7 +2,7 @@ title: Building Subgraphs on Arweave --- -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. @@ -25,12 +25,12 @@ The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are To be able to build and deploy Arweave Subgraphs, you need two packages: -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. ## Subgraph's components -There are three components of a subgraph: +There are three components of a Subgraph: ### 1. Manifest - `subgraph.yaml` @@ -40,25 +40,25 @@ Defines the data sources of interest, and how they should be processed. Arweave Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). ### 3. AssemblyScript Mappings - `mapping.ts` This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ``` $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: ```yaml -specVersion: 0.0.5 +specVersion: 1.3.0 description: Arweave Blocks Indexing schema: file: ./schema.graphql # link to the schema file @@ -70,7 +70,7 @@ dataSources: owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet startBlock: 0 # set this to 0 to start indexing from chain genesis mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript file: ./src/blocks.ts # link to the file with the Assemblyscript mappings entities: @@ -82,7 +82,7 @@ dataSources: - handler: handleTx # the function name in the mapping file ``` -- Arweave subgraphs introduce a new kind of data source (`arweave`) +- Arweave Subgraphs introduce a new kind of data source (`arweave`) - The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` - Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet @@ -92,14 +92,14 @@ Arweave data sources support two types of handlers: - `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` > The source.owner can be the owner's address, or their Public Key. -> + > Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> + > Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. ## Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ## AssemblyScript Mappings @@ -152,7 +152,7 @@ Writing the mappings of an Arweave Subgraph is very similar to writing the mappi ## Deploying an Arweave Subgraph in Subgraph Studio -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. ```bash graph deploy --access-token @@ -160,25 +160,25 @@ graph deploy --access-token ## Querying an Arweave Subgraph -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here is an example subgraph for reference: +Here is an example Subgraph for reference: -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) ## FAQ -### Can a subgraph index Arweave and other chains? +### Can a Subgraph index Arweave and other chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. ### Can I index the stored files on Arweave? Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). -### Can I identify Bundlr bundles in my subgraph? +### Can I identify Bundlr bundles in my Subgraph? This is not currently supported. @@ -188,7 +188,7 @@ The source.owner can be the user's public key or account address. ### What is the current encryption format? -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: diff --git a/website/src/pages/nl/subgraphs/cookbook/enums.mdx b/website/src/pages/cs/subgraphs/guides/enums.mdx similarity index 98% rename from website/src/pages/nl/subgraphs/cookbook/enums.mdx rename to website/src/pages/cs/subgraphs/guides/enums.mdx index a10970c1539f..9f55ae07c54b 100644 --- a/website/src/pages/nl/subgraphs/cookbook/enums.mdx +++ b/website/src/pages/cs/subgraphs/guides/enums.mdx @@ -10,7 +10,7 @@ Enums, or enumeration types, are a specific data type that allows you to define ### Example of Enums in Your Schema -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. @@ -65,7 +65,7 @@ Enums provide type safety, minimize typo risks, and ensure consistent and reliab > Note: The following guide uses the CryptoCoven NFT smart contract. -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: ```gql # Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) @@ -80,7 +80,7 @@ enum Marketplace { ## Using Enums for NFT Marketplaces -Once defined, enums can be used throughout your subgraph to categorize transactions or events. +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. diff --git a/website/src/pages/pl/subgraphs/cookbook/grafting.mdx b/website/src/pages/cs/subgraphs/guides/grafting.mdx similarity index 71% rename from website/src/pages/pl/subgraphs/cookbook/grafting.mdx rename to website/src/pages/cs/subgraphs/guides/grafting.mdx index 57d5169830a7..d9abe0e70d2a 100644 --- a/website/src/pages/pl/subgraphs/cookbook/grafting.mdx +++ b/website/src/pages/cs/subgraphs/guides/grafting.mdx @@ -2,13 +2,13 @@ title: Replace a Contract and Keep its History With Grafting --- -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. ## What is Grafting? -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: - It adds or removes entity types - It removes attributes from entity types @@ -22,38 +22,38 @@ For more information, you can check: - [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. ## Important Note on Grafting When Upgrading to the Network -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network ### Why Is This Important? -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. ### Best Practices -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. By adhering to these guidelines, you minimize risks and ensure a smoother migration process. ## Building an Existing Subgraph -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: - [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: ```yaml -specVersion: 0.0.4 +specVersion: 1.3.0 schema: file: ./schema.graphql dataSources: @@ -66,7 +66,7 @@ dataSources: startBlock: 5955690 mapping: kind: ethereum/events - apiVersion: 0.0.6 + apiVersion: 0.0.9 language: wasm/assemblyscript entities: - Withdrawal @@ -85,27 +85,27 @@ dataSources: ## Grafting Manifest Definition -Grafting requires adding two new items to the original subgraph manifest: +Grafting requires adding two new items to the original Subgraph manifest: ```yaml --- features: - grafting # feature name graft: - base: Qm... # subgraph ID of base subgraph + base: Qm... # Subgraph ID of base Subgraph block: 5956000 # block number ``` - `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting ## Deploying the Base Subgraph -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -138,16 +138,16 @@ It returns something like this: } ``` -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. ## Deploying the Grafting Subgraph The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -185,9 +185,9 @@ It should return the following: } ``` -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. -Congrats! You have successfully grafted a subgraph onto another subgraph. +Congrats! You have successfully grafted a Subgraph onto another Subgraph. ## Additional Resources diff --git a/website/src/pages/pl/subgraphs/cookbook/near.mdx b/website/src/pages/cs/subgraphs/guides/near.mdx similarity index 76% rename from website/src/pages/pl/subgraphs/cookbook/near.mdx rename to website/src/pages/cs/subgraphs/guides/near.mdx index 6060eb27e761..e78a69eb7fa2 100644 --- a/website/src/pages/pl/subgraphs/cookbook/near.mdx +++ b/website/src/pages/cs/subgraphs/guides/near.mdx @@ -2,17 +2,17 @@ title: Building Subgraphs on NEAR --- -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). ## What is NEAR? [NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. -## What are NEAR subgraphs? +## What are NEAR Subgraphs? -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: - Block handlers: these are run on every new block - Receipt handlers: run every time a message is executed at a specified account @@ -23,35 +23,35 @@ Subgraphs are event-based, which means that they listen for and then process onc ## Building a NEAR Subgraph -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. -`@graphprotocol/graph-ts` is a library of subgraph-specific types. +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. -There are three aspects of subgraph definition: +There are three aspects of Subgraph definition: -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). **AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ```bash $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ### Subgraph Manifest Definition -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: ```yaml -specVersion: 0.0.2 +specVersion: 1.3.0 schema: file: ./src/schema.graphql # link to the schema file dataSources: @@ -61,7 +61,7 @@ dataSources: account: app.good-morning.near # This data source will monitor this account startBlock: 10662188 # Required for NEAR mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript blockHandlers: - handler: handleNewBlock # the function name in the mapping file @@ -70,7 +70,7 @@ dataSources: file: ./src/mapping.ts # link to the file with the Assemblyscript mappings ``` -- NEAR subgraphs introduce a new `kind` of data source (`near`) +- NEAR Subgraphs introduce a new `kind` of data source (`near`) - The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` - NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. - NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. @@ -92,7 +92,7 @@ NEAR data sources support two types of handlers: ### Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ### AssemblyScript Mappings @@ -165,31 +165,31 @@ These types are passed to block & receipt handlers: - Block handlers will receive a `Block` - Receipt handlers will receive a `ReceiptWithOutcome` -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. ## Deploying a NEAR Subgraph -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - `near-mainnet` - `near-testnet` -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: ```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash ``` -The node configuration will depend on where the subgraph is being deployed. +The node configuration will depend on where the Subgraph is being deployed. ### Subgraph Studio @@ -204,7 +204,7 @@ graph deploy graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 ``` -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: ```graphql { @@ -228,11 +228,11 @@ We will provide more information on running the above components soon. ## Querying a NEAR Subgraph -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here are some example subgraphs for reference: +Here are some example Subgraphs for reference: [NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) @@ -242,13 +242,13 @@ Here are some example subgraphs for reference: ### How does the beta work? -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! -### Can a subgraph index both NEAR and EVM chains? +### Can a Subgraph index both NEAR and EVM chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. -### Can subgraphs react to more specific triggers? +### Can Subgraphs react to more specific triggers? Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. @@ -262,21 +262,21 @@ accounts: - mintbase1.near ``` -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? This is not supported. We are evaluating whether this functionality is required for indexing. -### Can I use data source templates in my NEAR subgraph? +### Can I use data source templates in my NEAR Subgraph? This is not currently supported. We are evaluating whether this functionality is required for indexing. -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. -### My question hasn't been answered, where can I get more help building NEAR subgraphs? +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. ## References diff --git a/website/src/pages/ar/subgraphs/cookbook/polymarket.mdx b/website/src/pages/cs/subgraphs/guides/polymarket.mdx similarity index 90% rename from website/src/pages/ar/subgraphs/cookbook/polymarket.mdx rename to website/src/pages/cs/subgraphs/guides/polymarket.mdx index 2edab84a377b..74efe387b0d7 100644 --- a/website/src/pages/ar/subgraphs/cookbook/polymarket.mdx +++ b/website/src/pages/cs/subgraphs/guides/polymarket.mdx @@ -3,17 +3,17 @@ title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph sidebarTitle: Query Polymarket Data --- -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. ## Polymarket Subgraph on Graph Explorer -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. ![Polymarket Playground](/img/Polymarket-playground.png) ## How to use the Visual Query Editor -The visual query editor helps you test sample queries from your subgraph. +The visual query editor helps you test sample queries from your Subgraph. You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. @@ -73,7 +73,7 @@ You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on ## Polymarket's GraphQL Schema -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). ### Polymarket Subgraph Endpoint @@ -88,7 +88,7 @@ The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegra 1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet 2. Go to https://thegraph.com/studio/apikeys/ to create an API key -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. 100k queries per month are free which is perfect for your side project! @@ -143,6 +143,6 @@ axios(graphQLRequest) ### Additional resources -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/nl/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/cs/subgraphs/guides/secure-api-keys-nextjs.mdx similarity index 95% rename from website/src/pages/nl/subgraphs/cookbook/secure-api-keys-nextjs.mdx rename to website/src/pages/cs/subgraphs/guides/secure-api-keys-nextjs.mdx index fc7e0ff52eb4..e17e594408ff 100644 --- a/website/src/pages/nl/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ b/website/src/pages/cs/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -4,9 +4,9 @@ title: How to Secure API Keys Using Next.js Server Components ## Overview -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. ### Caveats @@ -18,7 +18,7 @@ In this cookbook, we will go over how to create a Next.js server component that In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. -### Using client-side rendering to query a subgraph +### Using client-side rendering to query a Subgraph ![Client-side rendering](/img/api-key-client-side-rendering.png) diff --git a/website/src/pages/de/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/cs/subgraphs/guides/subgraph-debug-forking.mdx similarity index 76% rename from website/src/pages/de/subgraphs/cookbook/subgraph-debug-forking.mdx rename to website/src/pages/cs/subgraphs/guides/subgraph-debug-forking.mdx index 6610f19da66d..91aa7484d2ec 100644 --- a/website/src/pages/de/subgraphs/cookbook/subgraph-debug-forking.mdx +++ b/website/src/pages/cs/subgraphs/guides/subgraph-debug-forking.mdx @@ -2,23 +2,23 @@ title: Quick and Easy Subgraph Debugging Using Forks --- -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! ## Ok, what is it? -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. ## What?! How? -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. ## Please, show me some code! -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: @@ -44,22 +44,22 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { } ``` -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. The usual way to attempt a fix is: 1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). 3. Wait for it to sync-up. 4. If it breaks again go back to 1, otherwise: Hooray! It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: 0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. 1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. 3. If it breaks again, go back to 1, otherwise: Hooray! Now, you may have 2 questions: @@ -69,18 +69,18 @@ Now, you may have 2 questions: And I answer: -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. 2. Forking is easy, no need to sweat: ```bash $ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 ``` -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! So, here is what I do: -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). ``` $ cargo run -p graph-node --release -- \ @@ -91,11 +91,11 @@ $ cargo run -p graph-node --release -- \ ``` 2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: ```bash $ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 ``` 4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/de/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/cs/subgraphs/guides/subgraph-uncrashable.mdx similarity index 76% rename from website/src/pages/de/subgraphs/cookbook/subgraph-uncrashable.mdx rename to website/src/pages/cs/subgraphs/guides/subgraph-uncrashable.mdx index 0cc91a0fa2c3..a08e2a7ad8c9 100644 --- a/website/src/pages/de/subgraphs/cookbook/subgraph-uncrashable.mdx +++ b/website/src/pages/cs/subgraphs/guides/subgraph-uncrashable.mdx @@ -2,23 +2,23 @@ title: Safe Subgraph Code Generator --- -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. ## Why integrate with Subgraph Uncrashable? -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. **Key Features** -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. @@ -26,4 +26,4 @@ Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen graph codegen -u [options] [] ``` -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ro/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/cs/subgraphs/guides/transfer-to-the-graph.mdx similarity index 65% rename from website/src/pages/ro/subgraphs/cookbook/transfer-to-the-graph.mdx rename to website/src/pages/cs/subgraphs/guides/transfer-to-the-graph.mdx index 194deb018404..a62072c48373 100644 --- a/website/src/pages/ro/subgraphs/cookbook/transfer-to-the-graph.mdx +++ b/website/src/pages/cs/subgraphs/guides/transfer-to-the-graph.mdx @@ -1,29 +1,29 @@ --- -title: Tranfer to The Graph +title: Transfer to The Graph --- -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). ## Benefits of Switching to The Graph -- Use the same subgraph that your apps already use with zero-downtime migration. +- Use the same Subgraph that your apps already use with zero-downtime migration. - Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. ## Upgrade Your Subgraph to The Graph in 3 Easy Steps -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) ## 1. Set Up Your Studio Environment ### Create a Subgraph in Subgraph Studio - Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. ### Install the Graph CLI⁠ @@ -37,7 +37,7 @@ Using [npm](https://www.npmjs.com/): npm install -g @graphprotocol/graph-cli@latest ``` -Use the following command to create a subgraph in Studio using the CLI: +Use the following command to create a Subgraph in Studio using the CLI: ```sh graph init --product subgraph-studio @@ -53,7 +53,7 @@ graph auth ## 2. Deploy Your Subgraph to Studio -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. In The Graph CLI, run the following command: @@ -62,7 +62,7 @@ graph deploy --ipfs-hash ``` -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). ## 3. Publish Your Subgraph to The Graph Network @@ -70,17 +70,17 @@ graph deploy --ipfs-hash ### Query Your Subgraph -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. #### Example -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: ![Query URL](/img/cryptopunks-screenshot-transfer.png) -The query URL for this subgraph is: +The query URL for this Subgraph is: ```sh https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK @@ -96,9 +96,9 @@ You can create API Keys in Subgraph Studio under the “API Keys” menu at the ### Monitor Subgraph Status -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). ### Additional Resources -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/de/subgraphs/_meta-titles.json b/website/src/pages/de/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/de/subgraphs/_meta-titles.json +++ b/website/src/pages/de/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/de/subgraphs/_meta.js b/website/src/pages/de/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/de/subgraphs/_meta.js +++ b/website/src/pages/de/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/de/subgraphs/cookbook/arweave.mdx b/website/src/pages/de/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 02dd4f8398fc..000000000000 --- a/website/src/pages/de/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Building Subgraphs on Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. - -## What is Arweave? - -The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. - -Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## What are Arweave Subgraphs? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Building an Arweave Subgraph - -To be able to build and deploy Arweave Subgraphs, you need two packages: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Subgraph's components - -There are three components of a subgraph: - -### 1. Manifest - `subgraph.yaml` - -Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. - -### 2. Schema - `schema.graphql` - -Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. - -During subgraph development there are two key commands: - -``` -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -## Subgraf-Manifest-Definition - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet - -Arweave data sources support two types of handlers: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> The source.owner can be the owner's address, or their Public Key. -> -> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Schema-Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript-Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Querying an Arweave Subgraph - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Beispiele von Subgrafen - -Here is an example subgraph for reference: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Can a subgraph index Arweave and other chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can I index the stored files on Arweave? - -Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). - -### Can I identify Bundlr bundles in my subgraph? - -This is not currently supported. - -### How can I filter transactions to a specific account? - -The source.owner can be the user's public key or account address. - -### What is the current encryption format? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/de/subgraphs/cookbook/enums.mdx b/website/src/pages/de/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 0b2fe58b4e34..000000000000 --- a/website/src/pages/de/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Warum ist das ein Problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Zusätzliche Ressourcen - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/de/subgraphs/cookbook/grafting.mdx b/website/src/pages/de/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index ee92710b3059..000000000000 --- a/website/src/pages/de/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Replace a Contract and Keep its History With Grafting ---- - -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. - -## What is Grafting? - -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. - -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: - -- It adds or removes entity types -- It removes attributes from entity types -- It adds nullable attributes to entity types -- It turns non-nullable attributes into nullable attributes -- It adds values to enums -- It adds or removes interfaces -- It changes for which entity types an interface is implemented - -For more information, you can check: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## Building an Existing Subgraph - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Subgraf-Manifest-Definition - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Grafting Manifest Definition - -Grafting requires adding two new items to the original subgraph manifest: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Deploying the Base Subgraph - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It returns something like this: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. - -## Deploying the Grafting Subgraph - -The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It should return the following: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Zusätzliche Ressourcen - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/de/subgraphs/cookbook/near.mdx b/website/src/pages/de/subgraphs/cookbook/near.mdx deleted file mode 100644 index d748e4787563..000000000000 --- a/website/src/pages/de/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Building Subgraphs on NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## What is NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## What are NEAR subgraphs? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Block handlers: these are run on every new block -- Receipt handlers: run every time a message is executed at a specified account - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. - -## Building a NEAR Subgraph - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. - -There are three aspects of subgraph definition: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -During subgraph development there are two key commands: - -```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -### Subgraf-Manifest-Definition - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR data sources support two types of handlers: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Schema-Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript-Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Deploying a NEAR Subgraph - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -The node configuration will depend on where the subgraph is being deployed. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Local Graph Node (based on default configuration) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexing NEAR with a Local Graph Node - -Running a Graph Node that indexes NEAR has the following operational requirements: - -- NEAR Indexer Framework with Firehose instrumentation -- NEAR Firehose Component(s) -- Graph Node with Firehose endpoint configured - -We will provide more information on running the above components soon. - -## Querying a NEAR Subgraph - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Beispiele von Subgrafen - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### How does the beta work? - -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! - -### Can a subgraph index both NEAR and EVM chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can subgraphs react to more specific triggers? - -Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. - -### Will receipt handlers trigger for accounts and their sub-accounts? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? - -This is not supported. We are evaluating whether this functionality is required for indexing. - -### Can I use data source templates in my NEAR subgraph? - -This is not currently supported. We are evaluating whether this functionality is required for indexing. - -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? - -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. - -### My question hasn't been answered, where can I get more help building NEAR subgraphs? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## References - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/de/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/de/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 4122439152b8..000000000000 --- a/website/src/pages/de/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## Überblick - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/de/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/de/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index a97a3c618c03..000000000000 --- a/website/src/pages/de/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Gehen Sie zu [Subgraph Studio] (https://thegraph.com/studio/) und verbinden Sie Ihre Wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Verwendung von [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Beispiel - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Zusätzliche Ressourcen - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/cs/subgraphs/cookbook/_meta.js b/website/src/pages/de/subgraphs/guides/_meta.js similarity index 74% rename from website/src/pages/cs/subgraphs/cookbook/_meta.js rename to website/src/pages/de/subgraphs/guides/_meta.js index 1093ca048416..e642f12ef11d 100644 --- a/website/src/pages/cs/subgraphs/cookbook/_meta.js +++ b/website/src/pages/de/subgraphs/guides/_meta.js @@ -1,6 +1,4 @@ export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', 'subgraph-debug-forking': '', near: '', arweave: '', diff --git a/website/src/pages/ro/subgraphs/cookbook/arweave.mdx b/website/src/pages/de/subgraphs/guides/arweave.mdx similarity index 86% rename from website/src/pages/ro/subgraphs/cookbook/arweave.mdx rename to website/src/pages/de/subgraphs/guides/arweave.mdx index 2372025621d1..08e6c4257268 100644 --- a/website/src/pages/ro/subgraphs/cookbook/arweave.mdx +++ b/website/src/pages/de/subgraphs/guides/arweave.mdx @@ -2,7 +2,7 @@ title: Building Subgraphs on Arweave --- -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. @@ -25,12 +25,12 @@ The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are To be able to build and deploy Arweave Subgraphs, you need two packages: -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. ## Subgraph's components -There are three components of a subgraph: +There are three components of a Subgraph: ### 1. Manifest - `subgraph.yaml` @@ -40,25 +40,25 @@ Defines the data sources of interest, and how they should be processed. Arweave Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). ### 3. AssemblyScript Mappings - `mapping.ts` This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ``` $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: ```yaml -specVersion: 0.0.5 +specVersion: 1.3.0 description: Arweave Blocks Indexing schema: file: ./schema.graphql # link to the schema file @@ -70,7 +70,7 @@ dataSources: owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet startBlock: 0 # set this to 0 to start indexing from chain genesis mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript file: ./src/blocks.ts # link to the file with the Assemblyscript mappings entities: @@ -82,7 +82,7 @@ dataSources: - handler: handleTx # the function name in the mapping file ``` -- Arweave subgraphs introduce a new kind of data source (`arweave`) +- Arweave Subgraphs introduce a new kind of data source (`arweave`) - The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` - Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet @@ -92,14 +92,14 @@ Arweave data sources support two types of handlers: - `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` > The source.owner can be the owner's address, or their Public Key. -> + > Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> + > Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. ## Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ## AssemblyScript Mappings @@ -152,7 +152,7 @@ Writing the mappings of an Arweave Subgraph is very similar to writing the mappi ## Deploying an Arweave Subgraph in Subgraph Studio -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. ```bash graph deploy --access-token @@ -160,25 +160,25 @@ graph deploy --access-token ## Querying an Arweave Subgraph -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here is an example subgraph for reference: +Here is an example Subgraph for reference: -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) ## FAQ -### Can a subgraph index Arweave and other chains? +### Can a Subgraph index Arweave and other chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. ### Can I index the stored files on Arweave? Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). -### Can I identify Bundlr bundles in my subgraph? +### Can I identify Bundlr bundles in my Subgraph? This is not currently supported. @@ -188,7 +188,7 @@ The source.owner can be the user's public key or account address. ### What is the current encryption format? -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: diff --git a/website/src/pages/it/subgraphs/cookbook/enums.mdx b/website/src/pages/de/subgraphs/guides/enums.mdx similarity index 98% rename from website/src/pages/it/subgraphs/cookbook/enums.mdx rename to website/src/pages/de/subgraphs/guides/enums.mdx index a10970c1539f..9f55ae07c54b 100644 --- a/website/src/pages/it/subgraphs/cookbook/enums.mdx +++ b/website/src/pages/de/subgraphs/guides/enums.mdx @@ -10,7 +10,7 @@ Enums, or enumeration types, are a specific data type that allows you to define ### Example of Enums in Your Schema -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. @@ -65,7 +65,7 @@ Enums provide type safety, minimize typo risks, and ensure consistent and reliab > Note: The following guide uses the CryptoCoven NFT smart contract. -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: ```gql # Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) @@ -80,7 +80,7 @@ enum Marketplace { ## Using Enums for NFT Marketplaces -Once defined, enums can be used throughout your subgraph to categorize transactions or events. +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. diff --git a/website/src/pages/it/subgraphs/cookbook/grafting.mdx b/website/src/pages/de/subgraphs/guides/grafting.mdx similarity index 71% rename from website/src/pages/it/subgraphs/cookbook/grafting.mdx rename to website/src/pages/de/subgraphs/guides/grafting.mdx index 57d5169830a7..d9abe0e70d2a 100644 --- a/website/src/pages/it/subgraphs/cookbook/grafting.mdx +++ b/website/src/pages/de/subgraphs/guides/grafting.mdx @@ -2,13 +2,13 @@ title: Replace a Contract and Keep its History With Grafting --- -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. ## What is Grafting? -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: - It adds or removes entity types - It removes attributes from entity types @@ -22,38 +22,38 @@ For more information, you can check: - [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. ## Important Note on Grafting When Upgrading to the Network -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network ### Why Is This Important? -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. ### Best Practices -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. By adhering to these guidelines, you minimize risks and ensure a smoother migration process. ## Building an Existing Subgraph -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: - [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: ```yaml -specVersion: 0.0.4 +specVersion: 1.3.0 schema: file: ./schema.graphql dataSources: @@ -66,7 +66,7 @@ dataSources: startBlock: 5955690 mapping: kind: ethereum/events - apiVersion: 0.0.6 + apiVersion: 0.0.9 language: wasm/assemblyscript entities: - Withdrawal @@ -85,27 +85,27 @@ dataSources: ## Grafting Manifest Definition -Grafting requires adding two new items to the original subgraph manifest: +Grafting requires adding two new items to the original Subgraph manifest: ```yaml --- features: - grafting # feature name graft: - base: Qm... # subgraph ID of base subgraph + base: Qm... # Subgraph ID of base Subgraph block: 5956000 # block number ``` - `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting ## Deploying the Base Subgraph -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -138,16 +138,16 @@ It returns something like this: } ``` -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. ## Deploying the Grafting Subgraph The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -185,9 +185,9 @@ It should return the following: } ``` -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. -Congrats! You have successfully grafted a subgraph onto another subgraph. +Congrats! You have successfully grafted a Subgraph onto another Subgraph. ## Additional Resources diff --git a/website/src/pages/ro/subgraphs/cookbook/near.mdx b/website/src/pages/de/subgraphs/guides/near.mdx similarity index 76% rename from website/src/pages/ro/subgraphs/cookbook/near.mdx rename to website/src/pages/de/subgraphs/guides/near.mdx index 6060eb27e761..e78a69eb7fa2 100644 --- a/website/src/pages/ro/subgraphs/cookbook/near.mdx +++ b/website/src/pages/de/subgraphs/guides/near.mdx @@ -2,17 +2,17 @@ title: Building Subgraphs on NEAR --- -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). ## What is NEAR? [NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. -## What are NEAR subgraphs? +## What are NEAR Subgraphs? -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: - Block handlers: these are run on every new block - Receipt handlers: run every time a message is executed at a specified account @@ -23,35 +23,35 @@ Subgraphs are event-based, which means that they listen for and then process onc ## Building a NEAR Subgraph -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. -`@graphprotocol/graph-ts` is a library of subgraph-specific types. +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. -There are three aspects of subgraph definition: +There are three aspects of Subgraph definition: -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). **AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ```bash $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ### Subgraph Manifest Definition -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: ```yaml -specVersion: 0.0.2 +specVersion: 1.3.0 schema: file: ./src/schema.graphql # link to the schema file dataSources: @@ -61,7 +61,7 @@ dataSources: account: app.good-morning.near # This data source will monitor this account startBlock: 10662188 # Required for NEAR mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript blockHandlers: - handler: handleNewBlock # the function name in the mapping file @@ -70,7 +70,7 @@ dataSources: file: ./src/mapping.ts # link to the file with the Assemblyscript mappings ``` -- NEAR subgraphs introduce a new `kind` of data source (`near`) +- NEAR Subgraphs introduce a new `kind` of data source (`near`) - The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` - NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. - NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. @@ -92,7 +92,7 @@ NEAR data sources support two types of handlers: ### Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ### AssemblyScript Mappings @@ -165,31 +165,31 @@ These types are passed to block & receipt handlers: - Block handlers will receive a `Block` - Receipt handlers will receive a `ReceiptWithOutcome` -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. ## Deploying a NEAR Subgraph -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - `near-mainnet` - `near-testnet` -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: ```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash ``` -The node configuration will depend on where the subgraph is being deployed. +The node configuration will depend on where the Subgraph is being deployed. ### Subgraph Studio @@ -204,7 +204,7 @@ graph deploy graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 ``` -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: ```graphql { @@ -228,11 +228,11 @@ We will provide more information on running the above components soon. ## Querying a NEAR Subgraph -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here are some example subgraphs for reference: +Here are some example Subgraphs for reference: [NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) @@ -242,13 +242,13 @@ Here are some example subgraphs for reference: ### How does the beta work? -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! -### Can a subgraph index both NEAR and EVM chains? +### Can a Subgraph index both NEAR and EVM chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. -### Can subgraphs react to more specific triggers? +### Can Subgraphs react to more specific triggers? Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. @@ -262,21 +262,21 @@ accounts: - mintbase1.near ``` -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? This is not supported. We are evaluating whether this functionality is required for indexing. -### Can I use data source templates in my NEAR subgraph? +### Can I use data source templates in my NEAR Subgraph? This is not currently supported. We are evaluating whether this functionality is required for indexing. -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. -### My question hasn't been answered, where can I get more help building NEAR subgraphs? +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. ## References diff --git a/website/src/pages/de/subgraphs/cookbook/polymarket.mdx b/website/src/pages/de/subgraphs/guides/polymarket.mdx similarity index 90% rename from website/src/pages/de/subgraphs/cookbook/polymarket.mdx rename to website/src/pages/de/subgraphs/guides/polymarket.mdx index 2edab84a377b..74efe387b0d7 100644 --- a/website/src/pages/de/subgraphs/cookbook/polymarket.mdx +++ b/website/src/pages/de/subgraphs/guides/polymarket.mdx @@ -3,17 +3,17 @@ title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph sidebarTitle: Query Polymarket Data --- -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. ## Polymarket Subgraph on Graph Explorer -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. ![Polymarket Playground](/img/Polymarket-playground.png) ## How to use the Visual Query Editor -The visual query editor helps you test sample queries from your subgraph. +The visual query editor helps you test sample queries from your Subgraph. You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. @@ -73,7 +73,7 @@ You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on ## Polymarket's GraphQL Schema -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). ### Polymarket Subgraph Endpoint @@ -88,7 +88,7 @@ The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegra 1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet 2. Go to https://thegraph.com/studio/apikeys/ to create an API key -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. 100k queries per month are free which is perfect for your side project! @@ -143,6 +143,6 @@ axios(graphQLRequest) ### Additional resources -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ro/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/de/subgraphs/guides/secure-api-keys-nextjs.mdx similarity index 95% rename from website/src/pages/ro/subgraphs/cookbook/secure-api-keys-nextjs.mdx rename to website/src/pages/de/subgraphs/guides/secure-api-keys-nextjs.mdx index fc7e0ff52eb4..e17e594408ff 100644 --- a/website/src/pages/ro/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ b/website/src/pages/de/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -4,9 +4,9 @@ title: How to Secure API Keys Using Next.js Server Components ## Overview -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. ### Caveats @@ -18,7 +18,7 @@ In this cookbook, we will go over how to create a Next.js server component that In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. -### Using client-side rendering to query a subgraph +### Using client-side rendering to query a Subgraph ![Client-side rendering](/img/api-key-client-side-rendering.png) diff --git a/website/src/pages/nl/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/de/subgraphs/guides/subgraph-debug-forking.mdx similarity index 76% rename from website/src/pages/nl/subgraphs/cookbook/subgraph-debug-forking.mdx rename to website/src/pages/de/subgraphs/guides/subgraph-debug-forking.mdx index 6610f19da66d..91aa7484d2ec 100644 --- a/website/src/pages/nl/subgraphs/cookbook/subgraph-debug-forking.mdx +++ b/website/src/pages/de/subgraphs/guides/subgraph-debug-forking.mdx @@ -2,23 +2,23 @@ title: Quick and Easy Subgraph Debugging Using Forks --- -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! ## Ok, what is it? -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. ## What?! How? -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. ## Please, show me some code! -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: @@ -44,22 +44,22 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { } ``` -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. The usual way to attempt a fix is: 1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). 3. Wait for it to sync-up. 4. If it breaks again go back to 1, otherwise: Hooray! It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: 0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. 1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. 3. If it breaks again, go back to 1, otherwise: Hooray! Now, you may have 2 questions: @@ -69,18 +69,18 @@ Now, you may have 2 questions: And I answer: -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. 2. Forking is easy, no need to sweat: ```bash $ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 ``` -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! So, here is what I do: -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). ``` $ cargo run -p graph-node --release -- \ @@ -91,11 +91,11 @@ $ cargo run -p graph-node --release -- \ ``` 2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: ```bash $ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 ``` 4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ar/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/de/subgraphs/guides/subgraph-uncrashable.mdx similarity index 76% rename from website/src/pages/ar/subgraphs/cookbook/subgraph-uncrashable.mdx rename to website/src/pages/de/subgraphs/guides/subgraph-uncrashable.mdx index 0cc91a0fa2c3..a08e2a7ad8c9 100644 --- a/website/src/pages/ar/subgraphs/cookbook/subgraph-uncrashable.mdx +++ b/website/src/pages/de/subgraphs/guides/subgraph-uncrashable.mdx @@ -2,23 +2,23 @@ title: Safe Subgraph Code Generator --- -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. ## Why integrate with Subgraph Uncrashable? -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. **Key Features** -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. @@ -26,4 +26,4 @@ Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen graph codegen -u [options] [] ``` -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ko/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/de/subgraphs/guides/transfer-to-the-graph.mdx similarity index 65% rename from website/src/pages/ko/subgraphs/cookbook/transfer-to-the-graph.mdx rename to website/src/pages/de/subgraphs/guides/transfer-to-the-graph.mdx index 194deb018404..a62072c48373 100644 --- a/website/src/pages/ko/subgraphs/cookbook/transfer-to-the-graph.mdx +++ b/website/src/pages/de/subgraphs/guides/transfer-to-the-graph.mdx @@ -1,29 +1,29 @@ --- -title: Tranfer to The Graph +title: Transfer to The Graph --- -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). ## Benefits of Switching to The Graph -- Use the same subgraph that your apps already use with zero-downtime migration. +- Use the same Subgraph that your apps already use with zero-downtime migration. - Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. ## Upgrade Your Subgraph to The Graph in 3 Easy Steps -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) ## 1. Set Up Your Studio Environment ### Create a Subgraph in Subgraph Studio - Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. ### Install the Graph CLI⁠ @@ -37,7 +37,7 @@ Using [npm](https://www.npmjs.com/): npm install -g @graphprotocol/graph-cli@latest ``` -Use the following command to create a subgraph in Studio using the CLI: +Use the following command to create a Subgraph in Studio using the CLI: ```sh graph init --product subgraph-studio @@ -53,7 +53,7 @@ graph auth ## 2. Deploy Your Subgraph to Studio -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. In The Graph CLI, run the following command: @@ -62,7 +62,7 @@ graph deploy --ipfs-hash ``` -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). ## 3. Publish Your Subgraph to The Graph Network @@ -70,17 +70,17 @@ graph deploy --ipfs-hash ### Query Your Subgraph -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. #### Example -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: ![Query URL](/img/cryptopunks-screenshot-transfer.png) -The query URL for this subgraph is: +The query URL for this Subgraph is: ```sh https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK @@ -96,9 +96,9 @@ You can create API Keys in Subgraph Studio under the “API Keys” menu at the ### Monitor Subgraph Status -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). ### Additional Resources -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/en/subgraphs/_meta-titles.json b/website/src/pages/en/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/en/subgraphs/_meta-titles.json +++ b/website/src/pages/en/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/en/subgraphs/_meta.js b/website/src/pages/en/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/en/subgraphs/_meta.js +++ b/website/src/pages/en/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/de/subgraphs/cookbook/_meta.js b/website/src/pages/en/subgraphs/guides/_meta.js similarity index 74% rename from website/src/pages/de/subgraphs/cookbook/_meta.js rename to website/src/pages/en/subgraphs/guides/_meta.js index 1093ca048416..e642f12ef11d 100644 --- a/website/src/pages/de/subgraphs/cookbook/_meta.js +++ b/website/src/pages/en/subgraphs/guides/_meta.js @@ -1,6 +1,4 @@ export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', 'subgraph-debug-forking': '', near: '', arweave: '', diff --git a/website/src/pages/ko/subgraphs/cookbook/arweave.mdx b/website/src/pages/en/subgraphs/guides/arweave.mdx similarity index 86% rename from website/src/pages/ko/subgraphs/cookbook/arweave.mdx rename to website/src/pages/en/subgraphs/guides/arweave.mdx index 2372025621d1..08e6c4257268 100644 --- a/website/src/pages/ko/subgraphs/cookbook/arweave.mdx +++ b/website/src/pages/en/subgraphs/guides/arweave.mdx @@ -2,7 +2,7 @@ title: Building Subgraphs on Arweave --- -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. @@ -25,12 +25,12 @@ The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are To be able to build and deploy Arweave Subgraphs, you need two packages: -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. ## Subgraph's components -There are three components of a subgraph: +There are three components of a Subgraph: ### 1. Manifest - `subgraph.yaml` @@ -40,25 +40,25 @@ Defines the data sources of interest, and how they should be processed. Arweave Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). ### 3. AssemblyScript Mappings - `mapping.ts` This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ``` $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: ```yaml -specVersion: 0.0.5 +specVersion: 1.3.0 description: Arweave Blocks Indexing schema: file: ./schema.graphql # link to the schema file @@ -70,7 +70,7 @@ dataSources: owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet startBlock: 0 # set this to 0 to start indexing from chain genesis mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript file: ./src/blocks.ts # link to the file with the Assemblyscript mappings entities: @@ -82,7 +82,7 @@ dataSources: - handler: handleTx # the function name in the mapping file ``` -- Arweave subgraphs introduce a new kind of data source (`arweave`) +- Arweave Subgraphs introduce a new kind of data source (`arweave`) - The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` - Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet @@ -92,14 +92,14 @@ Arweave data sources support two types of handlers: - `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` > The source.owner can be the owner's address, or their Public Key. -> + > Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> + > Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. ## Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ## AssemblyScript Mappings @@ -152,7 +152,7 @@ Writing the mappings of an Arweave Subgraph is very similar to writing the mappi ## Deploying an Arweave Subgraph in Subgraph Studio -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. ```bash graph deploy --access-token @@ -160,25 +160,25 @@ graph deploy --access-token ## Querying an Arweave Subgraph -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here is an example subgraph for reference: +Here is an example Subgraph for reference: -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) ## FAQ -### Can a subgraph index Arweave and other chains? +### Can a Subgraph index Arweave and other chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. ### Can I index the stored files on Arweave? Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). -### Can I identify Bundlr bundles in my subgraph? +### Can I identify Bundlr bundles in my Subgraph? This is not currently supported. @@ -188,7 +188,7 @@ The source.owner can be the user's public key or account address. ### What is the current encryption format? -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: diff --git a/website/src/pages/ko/subgraphs/cookbook/enums.mdx b/website/src/pages/en/subgraphs/guides/enums.mdx similarity index 98% rename from website/src/pages/ko/subgraphs/cookbook/enums.mdx rename to website/src/pages/en/subgraphs/guides/enums.mdx index a10970c1539f..9f55ae07c54b 100644 --- a/website/src/pages/ko/subgraphs/cookbook/enums.mdx +++ b/website/src/pages/en/subgraphs/guides/enums.mdx @@ -10,7 +10,7 @@ Enums, or enumeration types, are a specific data type that allows you to define ### Example of Enums in Your Schema -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. @@ -65,7 +65,7 @@ Enums provide type safety, minimize typo risks, and ensure consistent and reliab > Note: The following guide uses the CryptoCoven NFT smart contract. -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: ```gql # Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) @@ -80,7 +80,7 @@ enum Marketplace { ## Using Enums for NFT Marketplaces -Once defined, enums can be used throughout your subgraph to categorize transactions or events. +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. diff --git a/website/src/pages/ko/subgraphs/cookbook/grafting.mdx b/website/src/pages/en/subgraphs/guides/grafting.mdx similarity index 71% rename from website/src/pages/ko/subgraphs/cookbook/grafting.mdx rename to website/src/pages/en/subgraphs/guides/grafting.mdx index 57d5169830a7..d9abe0e70d2a 100644 --- a/website/src/pages/ko/subgraphs/cookbook/grafting.mdx +++ b/website/src/pages/en/subgraphs/guides/grafting.mdx @@ -2,13 +2,13 @@ title: Replace a Contract and Keep its History With Grafting --- -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. ## What is Grafting? -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: - It adds or removes entity types - It removes attributes from entity types @@ -22,38 +22,38 @@ For more information, you can check: - [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. ## Important Note on Grafting When Upgrading to the Network -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network ### Why Is This Important? -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. ### Best Practices -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. By adhering to these guidelines, you minimize risks and ensure a smoother migration process. ## Building an Existing Subgraph -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: - [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: ```yaml -specVersion: 0.0.4 +specVersion: 1.3.0 schema: file: ./schema.graphql dataSources: @@ -66,7 +66,7 @@ dataSources: startBlock: 5955690 mapping: kind: ethereum/events - apiVersion: 0.0.6 + apiVersion: 0.0.9 language: wasm/assemblyscript entities: - Withdrawal @@ -85,27 +85,27 @@ dataSources: ## Grafting Manifest Definition -Grafting requires adding two new items to the original subgraph manifest: +Grafting requires adding two new items to the original Subgraph manifest: ```yaml --- features: - grafting # feature name graft: - base: Qm... # subgraph ID of base subgraph + base: Qm... # Subgraph ID of base Subgraph block: 5956000 # block number ``` - `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting ## Deploying the Base Subgraph -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -138,16 +138,16 @@ It returns something like this: } ``` -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. ## Deploying the Grafting Subgraph The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -185,9 +185,9 @@ It should return the following: } ``` -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. -Congrats! You have successfully grafted a subgraph onto another subgraph. +Congrats! You have successfully grafted a Subgraph onto another Subgraph. ## Additional Resources diff --git a/website/src/pages/vi/subgraphs/cookbook/near.mdx b/website/src/pages/en/subgraphs/guides/near.mdx similarity index 76% rename from website/src/pages/vi/subgraphs/cookbook/near.mdx rename to website/src/pages/en/subgraphs/guides/near.mdx index 6060eb27e761..e78a69eb7fa2 100644 --- a/website/src/pages/vi/subgraphs/cookbook/near.mdx +++ b/website/src/pages/en/subgraphs/guides/near.mdx @@ -2,17 +2,17 @@ title: Building Subgraphs on NEAR --- -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). ## What is NEAR? [NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. -## What are NEAR subgraphs? +## What are NEAR Subgraphs? -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: - Block handlers: these are run on every new block - Receipt handlers: run every time a message is executed at a specified account @@ -23,35 +23,35 @@ Subgraphs are event-based, which means that they listen for and then process onc ## Building a NEAR Subgraph -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. -`@graphprotocol/graph-ts` is a library of subgraph-specific types. +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. -There are three aspects of subgraph definition: +There are three aspects of Subgraph definition: -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). **AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ```bash $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ### Subgraph Manifest Definition -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: ```yaml -specVersion: 0.0.2 +specVersion: 1.3.0 schema: file: ./src/schema.graphql # link to the schema file dataSources: @@ -61,7 +61,7 @@ dataSources: account: app.good-morning.near # This data source will monitor this account startBlock: 10662188 # Required for NEAR mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript blockHandlers: - handler: handleNewBlock # the function name in the mapping file @@ -70,7 +70,7 @@ dataSources: file: ./src/mapping.ts # link to the file with the Assemblyscript mappings ``` -- NEAR subgraphs introduce a new `kind` of data source (`near`) +- NEAR Subgraphs introduce a new `kind` of data source (`near`) - The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` - NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. - NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. @@ -92,7 +92,7 @@ NEAR data sources support two types of handlers: ### Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ### AssemblyScript Mappings @@ -165,31 +165,31 @@ These types are passed to block & receipt handlers: - Block handlers will receive a `Block` - Receipt handlers will receive a `ReceiptWithOutcome` -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. ## Deploying a NEAR Subgraph -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - `near-mainnet` - `near-testnet` -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: ```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash ``` -The node configuration will depend on where the subgraph is being deployed. +The node configuration will depend on where the Subgraph is being deployed. ### Subgraph Studio @@ -204,7 +204,7 @@ graph deploy graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 ``` -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: ```graphql { @@ -228,11 +228,11 @@ We will provide more information on running the above components soon. ## Querying a NEAR Subgraph -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here are some example subgraphs for reference: +Here are some example Subgraphs for reference: [NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) @@ -242,13 +242,13 @@ Here are some example subgraphs for reference: ### How does the beta work? -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! -### Can a subgraph index both NEAR and EVM chains? +### Can a Subgraph index both NEAR and EVM chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. -### Can subgraphs react to more specific triggers? +### Can Subgraphs react to more specific triggers? Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. @@ -262,21 +262,21 @@ accounts: - mintbase1.near ``` -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? This is not supported. We are evaluating whether this functionality is required for indexing. -### Can I use data source templates in my NEAR subgraph? +### Can I use data source templates in my NEAR Subgraph? This is not currently supported. We are evaluating whether this functionality is required for indexing. -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. -### My question hasn't been answered, where can I get more help building NEAR subgraphs? +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. ## References diff --git a/website/src/pages/cs/subgraphs/cookbook/polymarket.mdx b/website/src/pages/en/subgraphs/guides/polymarket.mdx similarity index 90% rename from website/src/pages/cs/subgraphs/cookbook/polymarket.mdx rename to website/src/pages/en/subgraphs/guides/polymarket.mdx index 2edab84a377b..74efe387b0d7 100644 --- a/website/src/pages/cs/subgraphs/cookbook/polymarket.mdx +++ b/website/src/pages/en/subgraphs/guides/polymarket.mdx @@ -3,17 +3,17 @@ title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph sidebarTitle: Query Polymarket Data --- -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. ## Polymarket Subgraph on Graph Explorer -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. ![Polymarket Playground](/img/Polymarket-playground.png) ## How to use the Visual Query Editor -The visual query editor helps you test sample queries from your subgraph. +The visual query editor helps you test sample queries from your Subgraph. You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. @@ -73,7 +73,7 @@ You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on ## Polymarket's GraphQL Schema -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). ### Polymarket Subgraph Endpoint @@ -88,7 +88,7 @@ The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegra 1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet 2. Go to https://thegraph.com/studio/apikeys/ to create an API key -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. 100k queries per month are free which is perfect for your side project! @@ -143,6 +143,6 @@ axios(graphQLRequest) ### Additional resources -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pl/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/en/subgraphs/guides/secure-api-keys-nextjs.mdx similarity index 95% rename from website/src/pages/pl/subgraphs/cookbook/secure-api-keys-nextjs.mdx rename to website/src/pages/en/subgraphs/guides/secure-api-keys-nextjs.mdx index fc7e0ff52eb4..e17e594408ff 100644 --- a/website/src/pages/pl/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ b/website/src/pages/en/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -4,9 +4,9 @@ title: How to Secure API Keys Using Next.js Server Components ## Overview -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. ### Caveats @@ -18,7 +18,7 @@ In this cookbook, we will go over how to create a Next.js server component that In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. -### Using client-side rendering to query a subgraph +### Using client-side rendering to query a Subgraph ![Client-side rendering](/img/api-key-client-side-rendering.png) diff --git a/website/src/pages/it/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/en/subgraphs/guides/subgraph-debug-forking.mdx similarity index 76% rename from website/src/pages/it/subgraphs/cookbook/subgraph-debug-forking.mdx rename to website/src/pages/en/subgraphs/guides/subgraph-debug-forking.mdx index 6610f19da66d..91aa7484d2ec 100644 --- a/website/src/pages/it/subgraphs/cookbook/subgraph-debug-forking.mdx +++ b/website/src/pages/en/subgraphs/guides/subgraph-debug-forking.mdx @@ -2,23 +2,23 @@ title: Quick and Easy Subgraph Debugging Using Forks --- -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! ## Ok, what is it? -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. ## What?! How? -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. ## Please, show me some code! -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: @@ -44,22 +44,22 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { } ``` -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. The usual way to attempt a fix is: 1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). 3. Wait for it to sync-up. 4. If it breaks again go back to 1, otherwise: Hooray! It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: 0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. 1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. 3. If it breaks again, go back to 1, otherwise: Hooray! Now, you may have 2 questions: @@ -69,18 +69,18 @@ Now, you may have 2 questions: And I answer: -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. 2. Forking is easy, no need to sweat: ```bash $ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 ``` -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! So, here is what I do: -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). ``` $ cargo run -p graph-node --release -- \ @@ -91,11 +91,11 @@ $ cargo run -p graph-node --release -- \ ``` 2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: ```bash $ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 ``` 4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/it/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/en/subgraphs/guides/subgraph-uncrashable.mdx similarity index 76% rename from website/src/pages/it/subgraphs/cookbook/subgraph-uncrashable.mdx rename to website/src/pages/en/subgraphs/guides/subgraph-uncrashable.mdx index 0cc91a0fa2c3..a08e2a7ad8c9 100644 --- a/website/src/pages/it/subgraphs/cookbook/subgraph-uncrashable.mdx +++ b/website/src/pages/en/subgraphs/guides/subgraph-uncrashable.mdx @@ -2,23 +2,23 @@ title: Safe Subgraph Code Generator --- -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. ## Why integrate with Subgraph Uncrashable? -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. **Key Features** -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. @@ -26,4 +26,4 @@ Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen graph codegen -u [options] [] ``` -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/nl/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/en/subgraphs/guides/transfer-to-the-graph.mdx similarity index 65% rename from website/src/pages/nl/subgraphs/cookbook/transfer-to-the-graph.mdx rename to website/src/pages/en/subgraphs/guides/transfer-to-the-graph.mdx index 194deb018404..a62072c48373 100644 --- a/website/src/pages/nl/subgraphs/cookbook/transfer-to-the-graph.mdx +++ b/website/src/pages/en/subgraphs/guides/transfer-to-the-graph.mdx @@ -1,29 +1,29 @@ --- -title: Tranfer to The Graph +title: Transfer to The Graph --- -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). ## Benefits of Switching to The Graph -- Use the same subgraph that your apps already use with zero-downtime migration. +- Use the same Subgraph that your apps already use with zero-downtime migration. - Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. ## Upgrade Your Subgraph to The Graph in 3 Easy Steps -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) ## 1. Set Up Your Studio Environment ### Create a Subgraph in Subgraph Studio - Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. ### Install the Graph CLI⁠ @@ -37,7 +37,7 @@ Using [npm](https://www.npmjs.com/): npm install -g @graphprotocol/graph-cli@latest ``` -Use the following command to create a subgraph in Studio using the CLI: +Use the following command to create a Subgraph in Studio using the CLI: ```sh graph init --product subgraph-studio @@ -53,7 +53,7 @@ graph auth ## 2. Deploy Your Subgraph to Studio -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. In The Graph CLI, run the following command: @@ -62,7 +62,7 @@ graph deploy --ipfs-hash ``` -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). ## 3. Publish Your Subgraph to The Graph Network @@ -70,17 +70,17 @@ graph deploy --ipfs-hash ### Query Your Subgraph -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. #### Example -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: ![Query URL](/img/cryptopunks-screenshot-transfer.png) -The query URL for this subgraph is: +The query URL for this Subgraph is: ```sh https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK @@ -96,9 +96,9 @@ You can create API Keys in Subgraph Studio under the “API Keys” menu at the ### Monitor Subgraph Status -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). ### Additional Resources -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/es/subgraphs/_meta-titles.json b/website/src/pages/es/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/es/subgraphs/_meta-titles.json +++ b/website/src/pages/es/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/es/subgraphs/_meta.js b/website/src/pages/es/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/es/subgraphs/_meta.js +++ b/website/src/pages/es/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/es/subgraphs/cookbook/arweave.mdx b/website/src/pages/es/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index c0333e3dadf8..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Construyendo Subgrafos en Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -En esta guía, aprenderás a construir y deployar subgrafos para indexar la blockchain de Arweave. - -## ¿Qué es Arweave? - -El protocolo Arweave permite a los developers almacenar datos de forma permanente y esa es la principal diferencia entre Arweave e IPFS, donde IPFS carece de la característica; permanencia, y los archivos almacenados en Arweave no pueden ser modificados o eliminados. - -Arweave ya ha construido numerosas bibliotecas para integrar el protocolo en varios lenguajes de programación. Para más información puede consultar: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## ¿Qué son los subgrafos Arweave? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Construcción de un subgrafo Arweave - -Para poder construir y deployar subgrafos Arweave, necesita dos paquetes: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Componentes del subgrafo - -Hay tres componentes de un subgrafo: - -### 1. Manifest - `subgraph.yaml` - -Define las fuentes de datos de interés y cómo deben ser procesadas. Arweave es un nuevo tipo de fuente de datos. - -### 2. Schema - `schema.graphql` - -Aquí defines qué datos quieres poder consultar después de indexar tu Subgrafo usando GraphQL. Esto es en realidad similar a un modelo para una API, donde el modelo define la estructura de un cuerpo de solicitud. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -Esta es la lógica que determina cómo los datos deben ser recuperados y almacenados cuando alguien interactúa con las fuentes de datos que estás escuchando. Los datos se traducen y se almacenan basándose en el esquema que has listado. - -Durante el desarrollo del subgrafo hay dos comandos clave: - -``` -$ graph codegen # genera tipos a partir del archivo de esquema identificado en el manifiesto -$ graph build # genera Web Assembly a partir de los archivos de AssemblyScript y prepara todos los archivos de subgrafo en una carpeta /build -``` - -## Definición de manifiesto del subgrafo - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -descripción: Indexación de bloques Arweave -esquema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Las fuentes de datos de Arweave introducen un campo opcional "source.owner", que es la clave pública de una billetera Arweave - -Las fuentes de datos de Arweave admiten dos tipos de handlers: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> El source.owner puede ser la dirección del propietario o su clave pública. -> -> Las transacciones son los bloques de construcción de la permaweb de Arweave y son objetos creados por los usuarios finales. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Definición de esquema - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## Asignaciones de AssemblyScript - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Consultando un subgrafo de Arweave - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Subgrafos de ejemplo - -A continuación se muestra un ejemplo de subgrafo como referencia: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### ¿Puede un subgrafo indexar Arweave y otras cadenas? - -No, un subgrafo sólo puede admitir fuentes de datos de una cadena/red. - -### ¿Puedo indexar los archivos almacenados en Arweave? - -Actualmente, The Graph sólo indexa Arweave como blockchain (sus bloques y transacciones). - -### ¿Puedo identificar los paquetes de Bundlr en mi subgrafo? - -Actualmente no se admite. - -### ¿Cómo puedo filtrar las transacciones a una cuenta específica? - -El source.owner puede ser la clave pública del usuario o la dirección de la cuenta. - -### ¿Cuál es el formato actual de encriptación? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/es/subgraphs/cookbook/enums.mdx b/website/src/pages/es/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 29b5b2d0bf38..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Recursos Adicionales - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/es/subgraphs/cookbook/grafting.mdx b/website/src/pages/es/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 4a98c7ab352b..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Reemplazar un contrato y mantener su historia con el grafting ---- - -En esta guía, aprenderás a construir y deployar nuevos subgrafos mediante grafting (injerto) de subgrafos existentes. - -## ¿Qué es el Grafting? - -El grafting reutiliza los datos de un subgrafo existente y comienza a indexarlo en un bloque posterior. Esto es útil durante el desarrollo para superar rápidamente errores simples en los mapeos o para hacer funcionar temporalmente un subgrafo existente después de que haya fallado. También se puede utilizar cuando se añade un feature a un subgrafo que tarda en indexarse desde cero. - -El subgrafo grafteado puede utilizar un esquema GraphQL que no es idéntico al del subgrafo base, sino simplemente compatible con él. Tiene que ser un esquema de subgrafo válido por sí mismo, pero puede diferir del esquema del subgrafo base de las siguientes maneras: - -- Agrega o elimina tipos de entidades -- Elimina los atributos de los tipos de entidad -- Agrega atributos anulables a los tipos de entidad -- Convierte los atributos no anulables en atributos anulables -- Añade valores a los enums -- Agrega o elimina interfaces -- Cambia para qué tipos de entidades se implementa una interfaz - -Para más información, puedes consultar: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## Construcción de un subgrafo existente - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Definición de manifiesto del subgrafo - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Definición del manifiesto de grafting - -El grafting requiere añadir dos nuevos items al manifiesto original del subgrafo: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Deploy del subgrafo base - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Una vez que hayas terminado, verifica que el subgrafo se está indexando correctamente. Si ejecutas el siguiente comando en The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Devuelve algo como esto: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Una vez que hayas verificado que el subgrafo se está indexando correctamente, puedes actualizar rápidamente el subgrafo con grafting. - -## Deploy del subgrafo grafting - -El subgraph.yaml de sustitución del graft tendrá una nueva dirección de contrato. Esto podría ocurrir cuando actualices tu dApp, vuelvas a deployar un contrato, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Una vez que hayas terminado, verifica que el subgrafo se está indexando correctamente. Si ejecutas el siguiente comando en The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Debería devolver lo siguiente: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Recursos Adicionales - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/es/subgraphs/cookbook/near.mdx b/website/src/pages/es/subgraphs/cookbook/near.mdx deleted file mode 100644 index 67db2b1278cb..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Construcción de subgrafos en NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## ¿Qué es NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## ¿Qué son los subgrafos NEAR? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Handlers de bloques: se ejecutan en cada nuevo bloque -- Handlers de recibos: se realizan cada vez que se ejecuta un mensaje en una cuenta específica - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Un recibo es el único objeto procesable del sistema. Cuando hablamos de "procesar una transacción" en la plataforma NEAR, esto significa eventualmente "aplicar recibos" en algún momento. - -## Construcción de un subgrafo NEAR - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Construir un subgrafo NEAR es muy similar a construir un subgrafo que indexa Ethereum. - -Hay tres aspectos de la definición de subgrafo: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -Durante el desarrollo del subgrafo hay dos comandos clave: - -```bash -$ graph codegen # genera tipos a partir del archivo de esquema identificado en el manifiesto -$ graph build # genera Web Assembly a partir de los archivos de AssemblyScript y prepara todos los archivos de subgrafo en una carpeta /build -``` - -### Definición de manifiesto del subgrafo - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -Las fuentes de datos NEAR admiten dos tipos de handlers: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Definición de esquema - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### Asignaciones de AssemblyScript - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Deployando un subgrafo NEAR - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -La configuración del nodo dependerá de dónde se implemente el subgrafo. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Graph Node Local (basado en la configuración predeterminada) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Una vez que se haya implementado su subgrafo, Graph Node lo indexará. Puede comprobar su progreso consultando el propio subgrafo: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexación NEAR con un Graph Node local - -Ejecutar un Graph Node que indexa NEAR tiene los siguientes requisitos operativos: - -- NEAR Indexer Framework con instrumentación Firehose -- Componente(s) NEAR Firehose -- Graph Node con endpoint de Firehose configurado - -Pronto proporcionaremos más información sobre cómo ejecutar los componentes anteriores. - -## Consultando un subgrafo NEAR - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Subgrafos de ejemplo - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### ¿Cómo funciona la beta? - -El soporte NEAR está en versión beta, lo que significa que puede haber cambios en la API a medida que continuamos trabajando para mejorar la integración. Envíe un correo electrónico a near@thegraph.com para que podamos ayudarlo a crear subgrafos NEAR y mantenerte actualizado sobre los últimos desarrollos! - -### ¿Puede un subgrafo indexar las cadenas NEAR y EVM? - -No, un subgrafo sólo puede admitir fuentes de datos de una cadena/red. - -### ¿Pueden los subgrafos reaccionar a activadores más específicos? - -Actualmente, solo se admiten los activadores de Bloque y Recibo. Estamos investigando activadores para llamadas a funciones a una cuenta específica. También estamos interesados en admitir activadores de eventos, una vez que NEAR tenga soporte nativo para eventos. - -### ¿Se activarán los handlers de recibos para las cuentas y sus subcuentas? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### ¿Pueden los subgrafos NEAR realizar view calls a cuentas NEAR durante las asignaciones? - -Esto no es compatible. Estamos evaluando si esta funcionalidad es necesaria para la indexación. - -### ¿Puedo usar plantillas de fuente de datos en mi subgrafo NEAR? - -Esto no es compatible actualmente. Estamos evaluando si esta funcionalidad es necesaria para la indexación. - -### Los subgrafos de Ethereum admiten versiones "pendientes" y "actuales", ¿cómo puedo implementar una versión "pendiente" de un subgrafo NEAR? - -La funcionalidad pendiente aún no es compatible con los subgrafos NEAR. Mientras tanto, puedes implementar una nueva versión en un subgrafo "nombrado" diferente y luego, cuando se sincroniza con el encabezado de la cadena, puedes volver a implementarlo en su subgrafo principal "nombrado", que usará el mismo ID de implementación subyacente, por lo que el subgrafo principal se sincronizará instantáneamente. - -### Mi pregunta no ha sido respondida, ¿dónde puedo obtener más ayuda para crear subgrafos NEAR? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## Referencias - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/es/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/es/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 07b297aff006..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## Descripción - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/es/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/es/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 163a16d59e00..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Debugging rápido y sencillo de subgrafos mediante Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## ¿Bien, qué es? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## ¡¿Qué?! ¿Cómo? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## ¡Por favor, muéstrame algo de código! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -La forma habitual de intentar una solución es: - -1. Realiza un cambio en la fuente de mapeos, que crees que resolverá el problema (aunque sé que no lo hará). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Espera a que se sincronice. -4. Si se vuelve a romper vuelve a 1, de lo contrario: ¡Hurra! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Realiza un cambio en la fuente de mapeos, que crees que resolverá el problema. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. Si se vuelve a romper, vuelve a 1, de lo contrario: ¡Hurra! - -Ahora, puedes tener 2 preguntas: - -1. fork-base que??? -2. Bifurcando a quien?! - -Y yo respondo: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Bifurcar es fácil, no hay necesidad de sudar: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -Entonces, esto es lo que hago: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/es/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/es/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 59b33568a1f2..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Generador de código de subgrafo seguro ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## ¿Por qué integrarse con Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- El marco también incluye una forma (a través del archivo de configuración) para crear funciones de establecimiento personalizadas, pero seguras, para grupos de variables de entidad. De esta forma, es imposible que el usuario cargue/utilice una entidad gráfica obsoleta y también es imposible olvidarse de guardar o configurar una variable requerida por la función. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable se puede ejecutar como un indicador opcional mediante el comando codegen Graph CLI. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/es/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/es/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 339032915f35..000000000000 --- a/website/src/pages/es/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Ejemplo - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Recursos Adicionales - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/es/subgraphs/cookbook/_meta.js b/website/src/pages/es/subgraphs/guides/_meta.js similarity index 74% rename from website/src/pages/es/subgraphs/cookbook/_meta.js rename to website/src/pages/es/subgraphs/guides/_meta.js index 1093ca048416..e642f12ef11d 100644 --- a/website/src/pages/es/subgraphs/cookbook/_meta.js +++ b/website/src/pages/es/subgraphs/guides/_meta.js @@ -1,6 +1,4 @@ export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', 'subgraph-debug-forking': '', near: '', arweave: '', diff --git a/website/src/pages/pl/subgraphs/cookbook/arweave.mdx b/website/src/pages/es/subgraphs/guides/arweave.mdx similarity index 86% rename from website/src/pages/pl/subgraphs/cookbook/arweave.mdx rename to website/src/pages/es/subgraphs/guides/arweave.mdx index 2372025621d1..08e6c4257268 100644 --- a/website/src/pages/pl/subgraphs/cookbook/arweave.mdx +++ b/website/src/pages/es/subgraphs/guides/arweave.mdx @@ -2,7 +2,7 @@ title: Building Subgraphs on Arweave --- -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. @@ -25,12 +25,12 @@ The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are To be able to build and deploy Arweave Subgraphs, you need two packages: -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. ## Subgraph's components -There are three components of a subgraph: +There are three components of a Subgraph: ### 1. Manifest - `subgraph.yaml` @@ -40,25 +40,25 @@ Defines the data sources of interest, and how they should be processed. Arweave Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). ### 3. AssemblyScript Mappings - `mapping.ts` This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ``` $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: ```yaml -specVersion: 0.0.5 +specVersion: 1.3.0 description: Arweave Blocks Indexing schema: file: ./schema.graphql # link to the schema file @@ -70,7 +70,7 @@ dataSources: owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet startBlock: 0 # set this to 0 to start indexing from chain genesis mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript file: ./src/blocks.ts # link to the file with the Assemblyscript mappings entities: @@ -82,7 +82,7 @@ dataSources: - handler: handleTx # the function name in the mapping file ``` -- Arweave subgraphs introduce a new kind of data source (`arweave`) +- Arweave Subgraphs introduce a new kind of data source (`arweave`) - The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` - Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet @@ -92,14 +92,14 @@ Arweave data sources support two types of handlers: - `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` > The source.owner can be the owner's address, or their Public Key. -> + > Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> + > Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. ## Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ## AssemblyScript Mappings @@ -152,7 +152,7 @@ Writing the mappings of an Arweave Subgraph is very similar to writing the mappi ## Deploying an Arweave Subgraph in Subgraph Studio -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. ```bash graph deploy --access-token @@ -160,25 +160,25 @@ graph deploy --access-token ## Querying an Arweave Subgraph -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here is an example subgraph for reference: +Here is an example Subgraph for reference: -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) ## FAQ -### Can a subgraph index Arweave and other chains? +### Can a Subgraph index Arweave and other chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. ### Can I index the stored files on Arweave? Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). -### Can I identify Bundlr bundles in my subgraph? +### Can I identify Bundlr bundles in my Subgraph? This is not currently supported. @@ -188,7 +188,7 @@ The source.owner can be the user's public key or account address. ### What is the current encryption format? -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: diff --git a/website/src/pages/pl/subgraphs/cookbook/enums.mdx b/website/src/pages/es/subgraphs/guides/enums.mdx similarity index 98% rename from website/src/pages/pl/subgraphs/cookbook/enums.mdx rename to website/src/pages/es/subgraphs/guides/enums.mdx index a10970c1539f..9f55ae07c54b 100644 --- a/website/src/pages/pl/subgraphs/cookbook/enums.mdx +++ b/website/src/pages/es/subgraphs/guides/enums.mdx @@ -10,7 +10,7 @@ Enums, or enumeration types, are a specific data type that allows you to define ### Example of Enums in Your Schema -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. @@ -65,7 +65,7 @@ Enums provide type safety, minimize typo risks, and ensure consistent and reliab > Note: The following guide uses the CryptoCoven NFT smart contract. -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: ```gql # Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) @@ -80,7 +80,7 @@ enum Marketplace { ## Using Enums for NFT Marketplaces -Once defined, enums can be used throughout your subgraph to categorize transactions or events. +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. diff --git a/website/src/pages/nl/subgraphs/cookbook/grafting.mdx b/website/src/pages/es/subgraphs/guides/grafting.mdx similarity index 71% rename from website/src/pages/nl/subgraphs/cookbook/grafting.mdx rename to website/src/pages/es/subgraphs/guides/grafting.mdx index 57d5169830a7..d9abe0e70d2a 100644 --- a/website/src/pages/nl/subgraphs/cookbook/grafting.mdx +++ b/website/src/pages/es/subgraphs/guides/grafting.mdx @@ -2,13 +2,13 @@ title: Replace a Contract and Keep its History With Grafting --- -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. ## What is Grafting? -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: - It adds or removes entity types - It removes attributes from entity types @@ -22,38 +22,38 @@ For more information, you can check: - [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. ## Important Note on Grafting When Upgrading to the Network -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network ### Why Is This Important? -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. ### Best Practices -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. By adhering to these guidelines, you minimize risks and ensure a smoother migration process. ## Building an Existing Subgraph -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: - [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). ## Subgraph Manifest Definition -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: ```yaml -specVersion: 0.0.4 +specVersion: 1.3.0 schema: file: ./schema.graphql dataSources: @@ -66,7 +66,7 @@ dataSources: startBlock: 5955690 mapping: kind: ethereum/events - apiVersion: 0.0.6 + apiVersion: 0.0.9 language: wasm/assemblyscript entities: - Withdrawal @@ -85,27 +85,27 @@ dataSources: ## Grafting Manifest Definition -Grafting requires adding two new items to the original subgraph manifest: +Grafting requires adding two new items to the original Subgraph manifest: ```yaml --- features: - grafting # feature name graft: - base: Qm... # subgraph ID of base subgraph + base: Qm... # Subgraph ID of base Subgraph block: 5956000 # block number ``` - `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting ## Deploying the Base Subgraph -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -138,16 +138,16 @@ It returns something like this: } ``` -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. ## Deploying the Grafting Subgraph The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground ```graphql { @@ -185,9 +185,9 @@ It should return the following: } ``` -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. -Congrats! You have successfully grafted a subgraph onto another subgraph. +Congrats! You have successfully grafted a Subgraph onto another Subgraph. ## Additional Resources diff --git a/website/src/pages/ko/subgraphs/cookbook/near.mdx b/website/src/pages/es/subgraphs/guides/near.mdx similarity index 76% rename from website/src/pages/ko/subgraphs/cookbook/near.mdx rename to website/src/pages/es/subgraphs/guides/near.mdx index 6060eb27e761..e78a69eb7fa2 100644 --- a/website/src/pages/ko/subgraphs/cookbook/near.mdx +++ b/website/src/pages/es/subgraphs/guides/near.mdx @@ -2,17 +2,17 @@ title: Building Subgraphs on NEAR --- -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). ## What is NEAR? [NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. -## What are NEAR subgraphs? +## What are NEAR Subgraphs? -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: - Block handlers: these are run on every new block - Receipt handlers: run every time a message is executed at a specified account @@ -23,35 +23,35 @@ Subgraphs are event-based, which means that they listen for and then process onc ## Building a NEAR Subgraph -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. -`@graphprotocol/graph-ts` is a library of subgraph-specific types. +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. -There are three aspects of subgraph definition: +There are three aspects of Subgraph definition: -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). **AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. -During subgraph development there are two key commands: +During Subgraph development there are two key commands: ```bash $ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder ``` ### Subgraph Manifest Definition -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: ```yaml -specVersion: 0.0.2 +specVersion: 1.3.0 schema: file: ./src/schema.graphql # link to the schema file dataSources: @@ -61,7 +61,7 @@ dataSources: account: app.good-morning.near # This data source will monitor this account startBlock: 10662188 # Required for NEAR mapping: - apiVersion: 0.0.5 + apiVersion: 0.0.9 language: wasm/assemblyscript blockHandlers: - handler: handleNewBlock # the function name in the mapping file @@ -70,7 +70,7 @@ dataSources: file: ./src/mapping.ts # link to the file with the Assemblyscript mappings ``` -- NEAR subgraphs introduce a new `kind` of data source (`near`) +- NEAR Subgraphs introduce a new `kind` of data source (`near`) - The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` - NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. - NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. @@ -92,7 +92,7 @@ NEAR data sources support two types of handlers: ### Schema Definition -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). ### AssemblyScript Mappings @@ -165,31 +165,31 @@ These types are passed to block & receipt handlers: - Block handlers will receive a `Block` - Receipt handlers will receive a `ReceiptWithOutcome` -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. ## Deploying a NEAR Subgraph -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - `near-mainnet` - `near-testnet` -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: ```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash ``` -The node configuration will depend on where the subgraph is being deployed. +The node configuration will depend on where the Subgraph is being deployed. ### Subgraph Studio @@ -204,7 +204,7 @@ graph deploy graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 ``` -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: ```graphql { @@ -228,11 +228,11 @@ We will provide more information on running the above components soon. ## Querying a NEAR Subgraph -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. ## Example Subgraphs -Here are some example subgraphs for reference: +Here are some example Subgraphs for reference: [NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) @@ -242,13 +242,13 @@ Here are some example subgraphs for reference: ### How does the beta work? -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! -### Can a subgraph index both NEAR and EVM chains? +### Can a Subgraph index both NEAR and EVM chains? -No, a subgraph can only support data sources from one chain/network. +No, a Subgraph can only support data sources from one chain/network. -### Can subgraphs react to more specific triggers? +### Can Subgraphs react to more specific triggers? Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. @@ -262,21 +262,21 @@ accounts: - mintbase1.near ``` -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? This is not supported. We are evaluating whether this functionality is required for indexing. -### Can I use data source templates in my NEAR subgraph? +### Can I use data source templates in my NEAR Subgraph? This is not currently supported. We are evaluating whether this functionality is required for indexing. -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. -### My question hasn't been answered, where can I get more help building NEAR subgraphs? +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. ## References diff --git a/website/src/pages/es/subgraphs/cookbook/polymarket.mdx b/website/src/pages/es/subgraphs/guides/polymarket.mdx similarity index 90% rename from website/src/pages/es/subgraphs/cookbook/polymarket.mdx rename to website/src/pages/es/subgraphs/guides/polymarket.mdx index 2edab84a377b..74efe387b0d7 100644 --- a/website/src/pages/es/subgraphs/cookbook/polymarket.mdx +++ b/website/src/pages/es/subgraphs/guides/polymarket.mdx @@ -3,17 +3,17 @@ title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph sidebarTitle: Query Polymarket Data --- -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. ## Polymarket Subgraph on Graph Explorer -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. ![Polymarket Playground](/img/Polymarket-playground.png) ## How to use the Visual Query Editor -The visual query editor helps you test sample queries from your subgraph. +The visual query editor helps you test sample queries from your Subgraph. You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. @@ -73,7 +73,7 @@ You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on ## Polymarket's GraphQL Schema -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). ### Polymarket Subgraph Endpoint @@ -88,7 +88,7 @@ The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegra 1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet 2. Go to https://thegraph.com/studio/apikeys/ to create an API key -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. 100k queries per month are free which is perfect for your side project! @@ -143,6 +143,6 @@ axios(graphQLRequest) ### Additional resources -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ko/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/es/subgraphs/guides/secure-api-keys-nextjs.mdx similarity index 95% rename from website/src/pages/ko/subgraphs/cookbook/secure-api-keys-nextjs.mdx rename to website/src/pages/es/subgraphs/guides/secure-api-keys-nextjs.mdx index fc7e0ff52eb4..e17e594408ff 100644 --- a/website/src/pages/ko/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ b/website/src/pages/es/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -4,9 +4,9 @@ title: How to Secure API Keys Using Next.js Server Components ## Overview -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. ### Caveats @@ -18,7 +18,7 @@ In this cookbook, we will go over how to create a Next.js server component that In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. -### Using client-side rendering to query a subgraph +### Using client-side rendering to query a Subgraph ![Client-side rendering](/img/api-key-client-side-rendering.png) diff --git a/website/src/pages/ko/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/es/subgraphs/guides/subgraph-debug-forking.mdx similarity index 76% rename from website/src/pages/ko/subgraphs/cookbook/subgraph-debug-forking.mdx rename to website/src/pages/es/subgraphs/guides/subgraph-debug-forking.mdx index 6610f19da66d..91aa7484d2ec 100644 --- a/website/src/pages/ko/subgraphs/cookbook/subgraph-debug-forking.mdx +++ b/website/src/pages/es/subgraphs/guides/subgraph-debug-forking.mdx @@ -2,23 +2,23 @@ title: Quick and Easy Subgraph Debugging Using Forks --- -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! ## Ok, what is it? -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. ## What?! How? -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. ## Please, show me some code! -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: @@ -44,22 +44,22 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { } ``` -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. The usual way to attempt a fix is: 1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). 3. Wait for it to sync-up. 4. If it breaks again go back to 1, otherwise: Hooray! It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: 0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. 1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. 3. If it breaks again, go back to 1, otherwise: Hooray! Now, you may have 2 questions: @@ -69,18 +69,18 @@ Now, you may have 2 questions: And I answer: -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. 2. Forking is easy, no need to sweat: ```bash $ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 ``` -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! So, here is what I do: -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). ``` $ cargo run -p graph-node --release -- \ @@ -91,11 +91,11 @@ $ cargo run -p graph-node --release -- \ ``` 2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: ```bash $ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 ``` 4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ko/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/es/subgraphs/guides/subgraph-uncrashable.mdx similarity index 76% rename from website/src/pages/ko/subgraphs/cookbook/subgraph-uncrashable.mdx rename to website/src/pages/es/subgraphs/guides/subgraph-uncrashable.mdx index 0cc91a0fa2c3..a08e2a7ad8c9 100644 --- a/website/src/pages/ko/subgraphs/cookbook/subgraph-uncrashable.mdx +++ b/website/src/pages/es/subgraphs/guides/subgraph-uncrashable.mdx @@ -2,23 +2,23 @@ title: Safe Subgraph Code Generator --- -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. ## Why integrate with Subgraph Uncrashable? -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. **Key Features** -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. @@ -26,4 +26,4 @@ Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen graph codegen -u [options] [] ``` -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/pl/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/es/subgraphs/guides/transfer-to-the-graph.mdx similarity index 65% rename from website/src/pages/pl/subgraphs/cookbook/transfer-to-the-graph.mdx rename to website/src/pages/es/subgraphs/guides/transfer-to-the-graph.mdx index 194deb018404..a62072c48373 100644 --- a/website/src/pages/pl/subgraphs/cookbook/transfer-to-the-graph.mdx +++ b/website/src/pages/es/subgraphs/guides/transfer-to-the-graph.mdx @@ -1,29 +1,29 @@ --- -title: Tranfer to The Graph +title: Transfer to The Graph --- -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). ## Benefits of Switching to The Graph -- Use the same subgraph that your apps already use with zero-downtime migration. +- Use the same Subgraph that your apps already use with zero-downtime migration. - Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. ## Upgrade Your Subgraph to The Graph in 3 Easy Steps -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) ## 1. Set Up Your Studio Environment ### Create a Subgraph in Subgraph Studio - Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. ### Install the Graph CLI⁠ @@ -37,7 +37,7 @@ Using [npm](https://www.npmjs.com/): npm install -g @graphprotocol/graph-cli@latest ``` -Use the following command to create a subgraph in Studio using the CLI: +Use the following command to create a Subgraph in Studio using the CLI: ```sh graph init --product subgraph-studio @@ -53,7 +53,7 @@ graph auth ## 2. Deploy Your Subgraph to Studio -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. In The Graph CLI, run the following command: @@ -62,7 +62,7 @@ graph deploy --ipfs-hash ``` -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). ## 3. Publish Your Subgraph to The Graph Network @@ -70,17 +70,17 @@ graph deploy --ipfs-hash ### Query Your Subgraph -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. #### Example -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: ![Query URL](/img/cryptopunks-screenshot-transfer.png) -The query URL for this subgraph is: +The query URL for this Subgraph is: ```sh https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK @@ -96,9 +96,9 @@ You can create API Keys in Subgraph Studio under the “API Keys” menu at the ### Monitor Subgraph Status -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). ### Additional Resources -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/fr/subgraphs/_meta-titles.json b/website/src/pages/fr/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/fr/subgraphs/_meta-titles.json +++ b/website/src/pages/fr/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/fr/subgraphs/_meta.js b/website/src/pages/fr/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/fr/subgraphs/_meta.js +++ b/website/src/pages/fr/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/fr/subgraphs/cookbook/_meta.js b/website/src/pages/fr/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/fr/subgraphs/cookbook/arweave.mdx b/website/src/pages/fr/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 2b11f5ea02a1..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Construction de subgraphs pour Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -Dans ce guide, vous apprendrez comment créer et déployer des subgraphs pour indexer la blockchain Arweave. - -## Qu’est-ce qu’Arweave ? - -Arweave est un protocole qui permet aux développeurs de stocker des données de façon permanente. C'est cette caractéristique qui constitue la principale différence entre Arweave et IPFS. En effet, IPFS n'a pas la caractéristique de permanence, et les fichiers stockés sur Arweave ne peuvent pas être modifiés ou supprimés. - -Arweave a déjà construit de nombreuses bibliothèques pour intégrer le protocole dans plusieurs langages de programmation différents. Pour plus d'informations, vous pouvez consulter : - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## À quoi servent les subgraphs d'Arweave ? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Construire un subgraph Arweave - -Pour pouvoir créer et déployer des Arweave Subgraphs, vous avez besoin de deux packages : - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Caractéristique des subgraphs - -Il y a trois composants d'un subgraph : - -### 1. Manifest - `subgraph.yaml` - -Définit les sources de données intéressantes et la manière dont elles doivent être traitées. Arweave est un nouveau type de source de données. - -### 2. Schema - `schema.graphql` - -Vous définissez ici les données que vous souhaitez pouvoir interroger après avoir indexé votre subgraph à l'aide de GraphQL. Ceci est en fait similaire à un modèle pour une API, où le modèle définit la structure d'un corps de requête. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -Il s'agit de la logique qui détermine comment les données doivent être récupérées et stockées lorsqu'une personne interagit avec les sources de données que vous interrogez. Les données sont traduites et stockées sur la base du schema que vous avez répertorié. - -Lors du développement du subgraph, il y a deux commandes clés : - -``` -$ graph codegen # génère des types à partir du fichier de schéma identifié dans le manifeste -$ graph build # génère le Web Assembly à partir des fichiers AssemblyScript, et prépare tous les fichiers de subgraphes dans un dossier /build -``` - -## Définition du manifeste du subgraph - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # lien vers le fichier de schéma -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph ne supporte que le Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # La clé publique d'un porte-monnaie Arweave - startBlock: 0 # mettez cette valeur à 0 pour commencer l'indexation à partir de la genèse de la chaîne. - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # lien vers le fichier contenant les mappages d'Assemblyscript - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # le nom de la fonction dans le fichier de mapping - transactionHandlers: - - handler: handleTx # le nom de la fonction dans le fichier de mapping -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Les sources de données Arweave introduisent un champ source.owner facultatif, qui est la clé publique d'un portefeuille Arweave - -Les sources de données Arweave prennent en charge deux types de gestionnaires : - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> Source.owner peut être l’adresse du propriétaire ou sa clé publique. -> -> Les transactions sont les éléments constitutifs du permaweb Arweave et ce sont des objets créés par les utilisateurs finaux. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Définition de schéma - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## Cartographies AssemblyScript - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Déploiement d'un subgraph Arweave dans Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Interroger un subgraph d'Arweave - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Exemples de subgraphs - -Voici un exemple de modèle subgraph : - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Un subgraph peut-il indexer Arweave et d'autres chaînes ? - -Non, un subgraph ne peut supporter que les sources de données d'une seule chaîne/réseau. - -### Puis-je indexer les fichiers enregistrés sur Arweave ? - -Actuellement, The Graph n'indexe Arweave qu'en tant que blockchain (ses blocs et ses transactions). - -### Puis-je identifier les bundles de Bundlr dans mon subgraph ? - -Cette fonction n'est pas prise en charge actuellement. - -### Comment puis-je filtrer les transactions sur un compte spécifique ? - -La source.owner peut être la clé publique de l'utilisateur ou l'adresse de son compte. - -### Quel est le format de chiffrement actuel ? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/fr/subgraphs/cookbook/enums.mdx b/website/src/pages/fr/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 5784cb991330..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Catégoriser les marketplaces NFT à l’aide d’Enums ---- - -Utilisez des Enums pour rendre votre code plus propre et moins sujet aux erreurs. Voici un exemple complet d'utilisation des Enums sur les marketplaces NFT. - -## Que sont les Enums ? - -Les Enums, ou types d'énumération, sont un type de données spécifique qui vous permet de définir un ensemble de valeurs spécifiques et autorisées. - -### Exemple d'Enums dans Votre Schéma - -Si vous construisez un subgraph pour suivre l'historique de propriété des tokens sur une marketplace, chaque token peut passer par différentes propriétés, telles que`OriginalOwner`, `SecondOwner`, et `ThirdOwner`. En utilisant des enums, vous pouvez définir ces propriétés spécifiques, garantissant que seules des valeurs prédéfinies sont utilisées. - -Vous pouvez définir des enums dans votre schéma et, une fois définis, vous pouvez utiliser la représentation en chaîne de caractères des valeurs enum pour définir un champ enum sur une entité. - -Voici à quoi pourrait ressembler une définition d'enum dans votre schéma, basée sur l'exemple ci-dessus : - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -Ceci signifie que lorsque vous utilisez le type `TokenStatus` dans votre schéma, vous attendez qu'il soit exactement l'une des valeurs prédéfinies : `OriginalOwner`, `SecondOwner`, ou `ThirdOwner`, garantissant la cohérence et la validité des données. - -Pour en savoir plus sur les enums, consultez [Création d'un Subgraph](/developing/creating-a-subgraph/#enums) et [documentation GraphQL ](https://graphql.org/learn/schema/#enumeration-types). - -## Avantages de l'Utilisation des Enums - -- **Clarté** : Les enums fournissent des noms significatifs pour les valeurs, rendant les données plus faciles à comprendre. -- **Validation** : Les enums imposent des définitions de valeurs strictes, empêchant les entrées de données invalides. -- **Maintenabilité** : Lorsque vous avez besoin de changer ou d'ajouter de nouvelles catégories, les enums vous permettent de le faire de manière ciblée. - -### Sans Enums - -Si vous choisissez de définir le type comme une chaîne de caractères au lieu d'utiliser un Enum, votre code pourrait ressembler à ceci : - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Propriétaire du jeton - tokenStatus: String! # Champ de type chaîne pour suivre l'état du jeton - timestamp: BigInt! -} -``` - -Dans ce schéma, `TokenStatus` est une simple chaîne de caractères sans valeurs spécifiques autorisées. - -#### Pourquoi est-ce un problème ? - -- Il n'y a aucune restriction sur les valeurs de `TokenStatus` : n’importe quelle chaîne de caractères peut être affectée par inadvertance. Difficile donc de s'assurer que seules des valeurs valides comme comme `OriginalOwner`, `SecondOwner`, ou `ThirdOwner` soient utilisées. -- Il est facile de faire des fautes de frappe comme `Orgnalowner` au lieu de `OriginalOwner`, rendant les données et les requêtes potentielles peu fiables. - -### Avec Enums - -Au lieu d'assigner des chaînes de caractères libres, vous pouvez définir un enum pour `TokenStatus` avec des valeurs spécifiques : `OriginalOwner`, `SecondOwner`, ou `ThirdOwner`. L'utilisation d'un enum garantit que seules les valeurs autorisées sont utilisées. - -Les Enums assurent la sécurité des types, minimisent les risques de fautes de frappe et garantissent des résultats cohérents et fiables. - -## Définition des Enums pour les Marketplaces NFT - -> Note: Le guide suivant utilise le smart contract CryptoCoven NFT. - -Pour définir des enums pour les différents marketplaces où les NFTs sont échangés, utilisez ce qui suit dans votre schéma de subgraph : - -```gql -# Enum pour les Marketplaces avec lesquelles le contrat CryptoCoven a interagi (probablement une vente ou un mint) -enum Marketplace { - OpenSeaV1 # Représente lorsque un NFT CryptoCoven est échangé sur la marketplace - OpenSeaV2 # Représente lorsque un NFT CryptoCoven est échangé sur la marketplace OpenSeaV2 - SeaPort # Représente lorsque un NFT CryptoCoven est échangé sur la marketplace SeaPort - LooksRare # Représente lorsque un NFT CryptoCoven est échangé sur la marketplace LooksRare - # ...et d'autres marketplaces -} -``` - -## Utilisation des Enums pour les Marketplaces NFT - -Une fois définis, les enums peuvent être utilisés tout au long de votre subgraph pour catégoriser les transactions ou les événements. - -Par exemple, lors de la journalisation des ventes de NFT, vous pouvez spécifier la marketplace impliqué dans la transaction en utilisant l'enum. - -### Implémenter une Fonction pour les Marketplaces NFT - -Voici comment vous pouvez implémenter une fonction pour récupérer le nom de la marketplace à partir de l'enum sous forme de chaîne de caractères : - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Utilisation des instructions if-else pour mapper la valeur de l'enum à une chaîne de caractères - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // Si le marketplace est OpenSea, renvoie sa représentation en chaîne de caractères - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // Si le marketplace est SeaPort, renvoie sa représentation en chaîne de caractères - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // Si le marketplace est LooksRare, renvoie sa représentation en chaîne de caractères - // ... et d'autres marketplaces - } -} -``` - -## Bonnes Pratiques pour l'Utilisation des Enums - -- **Nommer avec cohérence** : Utilisez des noms clairs et descriptifs pour les valeurs d'enum pour améliorer la lisibilité. -- **Gestion Centralisée** : Gardez les enums dans un fichier unique pour plus de cohérence. Ainsi, il est plus simple de les mettre à jour et de garantir qu’ils sont votre unique source de vérité. -- **Documentation** : Ajoutez des commentaires aux enums pour clarifier leur objectif et leur utilisation. - -## Utilisation des Enums dans les Requêtes - -Les enums dans les requêtes aident à améliorer la qualité des données et à rendre les résultats plus faciles à interpréter. Ils fonctionnent comme des filtres et des éléments de réponse, assurant la cohérence et réduisant les erreurs dans les valeurs des marketplaces. - -Spécificités - -- **Filtrer avec des Enums**: Les Enums offrent des filtres clairs, vous permettant d’inclure ou d’exclure facilement des marketplaces spécifiques. -- **Enums dans les Réponses**: Les Enums garantissent que seules des valeurs de marketplace reconnues sont renvoyées, ce qui rend les résultats standardisés et précis. - -### Exemples de requêtes - -#### Requête 1 : Compte avec le Plus d'Interactions sur les Marketplaces NFT - -Cette requête fait ce qui suit : - -- Elle trouve le compte avec le plus grand nombre unique d'interactions sur les marketplaces NFT, ce qui est excellent pour analyser l'activité inter-marketplaces. -- Le champ marketplaces utilise l'enum marketplace, garantissant des valeurs de marketplace cohérentes et validées dans la réponse. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # Ce champ retourne la valeur enum représentant la marketplace - } - } -} -``` - -#### Résultats - -Cette réponse fournit les détails du compte et une liste des interactions uniques sur les marketplaces avec des valeurs enum pour une clarté standardisée : - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Requête 2 : Marketplace la Plus Active pour les Transactions CryptoCoven - -Cette requête fait ce qui suit : - -- Elle identifie la marketplace avec le plus grand volume de transactions CryptoCoven. -- Il utilise l'enum marketplace pour s'assurer que seuls les types de marketplace valides apparaissent dans la réponse, ajoutant fiabilité et cohérence à vos données. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Résultat 2 - -La réponse attendue inclut la marketplace et le nombre de transactions correspondant, en utilisant l'enum pour indiquer le type de marketplace : - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Requête 3: Interactions sur les marketplaces avec un haut volume de transactions - -Cette requête fait ce qui suit : - -- Elle récupère les quatre principales marketplaces avec plus de 100 transactions, en excluant les marketplaces "Unknown". -- Elle utilise des enums comme filtres pour s'assurer que seuls les types de marketplace valides sont inclus, augmentant ainsi la précision. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Résultat 3 - -La sortie attendue inclut les marketplaces qui répondent aux critères, chacune représentée par une valeur enum : - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Ressources supplémentaires - -Pour des informations supplémentaires, consultez le [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums) de ce guide. diff --git a/website/src/pages/fr/subgraphs/cookbook/grafting.mdx b/website/src/pages/fr/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index a81cf0ddf30a..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Remplacer un contrat et conserver son historique grâce au « greffage » ---- - -Dans ce guide, vous apprendrez à construire et à déployer de nouveaux subgraphs en utilisant le greffage sur des subgraphs existants. - -## Qu'est-ce qu'une greffe ? - -C'est une méthode qui réutilise les données d'un subgraph existant et commence à les indexer à un bloc ultérieur. Elle est utile lors du développement pour contourner rapidement les erreurs simples dans les mappings ou pour remettre temporairement en service un subgraph existant qui a échoué. Elle peut également être utilisée pour ajouter une fonctionnalité à un subgraphe dont l'indexation depuis la genèse prend un temps considérable. - -Le subgraph greffé peut utiliser un schema GraphQL qui n'est pas identique à celui du subgraph de base, mais simplement compatible avec lui. Il doit s'agir d'un schema de subgraph valide en tant que tel, mais il peut s'écarter du schema du subgraph de base de la manière suivante : - -- Il ajoute ou supprime des types d'entité -- Il supprime les attributs des types d'entité -- Il ajoute des attributs nullables aux types d'entités -- Il transforme les attributs non nullables en attributs nuls -- Cela ajoute des valeurs aux énumérations -- Il ajoute ou supprime des interfaces -- Cela change pour quels types d'entités une interface est implémentée - -Pour plus d’informations, vous pouvez vérifier : - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -Dans ce tutoriel, nous couvrirons un cas d'utilisation de base. Nous remplacerons un contrat existant par un contrat identique (avec une nouvelle adresse, mais le même code). Ensuite, nous grefferons le subgraph existant sur le subgraph "de base" qui suit le nouveau contrat. - -## Remarque importante sur le greffage lors de la mise à niveau vers le réseau - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Pourquoi est-ce important? - -Le greffage est une fonctionnalité puissante qui vous permet de "greffer" un subgraph sur un autre, transférant efficacement les données historiques du subgraph existant vers une nouvelle version. Il n'est pas possible de greffer un subgraph de The Graph Network vers Subgraph Studio. - -### Les meilleures pratiques - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -En respectant ces lignes directrices, vous minimisez les risques et vous vous assurez que le processus de migration se déroule sans heurts. - -## Création d'un subgraph existant - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Définition du manifeste du subgraph - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Définition de manifeste de greffage - -Le greffage nécessite l'ajout de deux nouveaux éléments au manifeste du subgraph original : - -```yaml ---- -features: - - grafting # nom de la fonctionnalité -graft: - base: Qm... # ID du subgraph de base - block: 5956000 # numéro du bloc -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Déploiement du subgraph de base - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Une fois terminé, vérifiez que le subgraph s'indexe correctement. Si vous exécutez la commande suivante dans The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Cela renvoie quelque chose comme ceci : - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Une fois que vous avez vérifié que le subgraph s'indexe correctement, vous pouvez rapidement le mettre à jour grâce à la méthode du graffage. - -## Déploiement du subgraph greffé - -Le subgraph.yaml de remplacement du greffon aura une nouvelle adresse de contrat. Cela peut arriver lorsque vous mettez à jour votre dapp, redéployez un contrat, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Une fois terminé, vérifiez que le subgraph s'indexe correctement. Si vous exécutez la commande suivante dans The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Le résultat devrait être le suivant : - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Félicitations ! Vous avez réussi à greffer un subgraph sur un autre subgraph. - -## Ressources supplémentaires - -Si vous souhaitez acquérir plus d'expérience avec le greffage, voici quelques exemples pour des contrats populaires : - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/fr/subgraphs/cookbook/near.mdx b/website/src/pages/fr/subgraphs/cookbook/near.mdx deleted file mode 100644 index 0e6830668726..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Construction de subgraphs sur NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## Que signifie NEAR ? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## Que sont les subgraphs NEAR ? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Gestionnaires de blocs : ceux-ci sont exécutés à chaque nouveau bloc -- Gestionnaires de reçus : exécutés à chaque fois qu'un message est exécuté sur un compte spécifié - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Un reçu est le seul objet actionnable dans le système. Lorsque nous parlons de "traitement d'une transaction" sur la plateforme NEAR, cela signifie en fin de compte "appliquer des reçus" à un moment ou à un autre. - -## Construction d'un subgraph NEAR - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> La construction d'un subgraph NEAR est très similaire à la construction d'un subgraph qui indexe Ethereum. - -La définition d'un subgraph comporte trois aspects : - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -Lors du développement du subgraph, il y a deux commandes clés : - -```bash -$ graph codegen # génère des types à partir du fichier de schéma identifié dans le manifeste -$ graph build # génère le Web Assembly à partir des fichiers AssemblyScript, et prépare tous les fichiers de subgraphes dans un dossier /build -``` - -### Définition du manifeste du subgraph - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # lien vers le fichier de schéma -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # Cette source de données surveillera ce compte - startBlock: 10662188 # Requis pour NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # le nom de la fonction dans le fichier de mapping - receiptHandlers: - - handler: handleReceipt # le nom de la fonction dans le fichier de mappage - file: ./src/mapping.ts # lien vers le fichier contenant les mappings Assemblyscript -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -comptes: - préfixes: - - application - - bien - suffixes: - - matin.près - - matin.testnet -``` - -Les fichiers de données NEAR prennent en charge deux types de gestionnaires : - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Définition de schéma - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### Cartographies AssemblyScript - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Déploiement d'un subgraph NEAR - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio et l'Indexeur de mise à niveau sur The Graph Network prennent en charge actuellement l'indexation du mainnet et du testnet NEAR en bêta, avec les noms de réseau suivants : - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -La configuration du nœud dépend de l'endroit où le subgraph est déployé. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Nœud Graph local ( en fonction de la configuration par défaut) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Une fois que votre subgraph a été déployé, il sera indexé par le nœud The Graph. Vous pouvez vérifier sa progression en interrogeant le subgraph lui-même : - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexation de NEAR avec un nœud The graph local - -L'exécution d'un nœud de Graph qui indexe NEAR répond aux exigences opérationnelles suivantes : - -- Cadre d'indexation NEAR avec instrumentation Firehose -- Composant(s) du NEAR Firehose -- Nœud Gaph avec point d'extrémité Firehose configuré - -Nous fournirons bientôt plus d'informations sur l'utilisation des composants ci-dessus. - -## Interrogation d'un subgraph NEAR - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Exemples de subgraphs - -Voici quelques exemples de subgraphs pour référence : - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### Comment fonctionne la bêta ? - -Le support de NEAR est en version bêta, ce qui signifie qu'il peut y avoir des changements dans l'API alors que nous continuons à travailler sur l'amélioration de l'intégration. Veuillez envoyer un e-mail à near@thegraph.com pour que nous puissions vous aider à construire des subgraphs NEAR et vous tenir au courant des derniers développements ! - -### Un subgraph peut-il indexer à la fois les chaînes NEAR et EVM ? - -Non, un subgraph ne peut supporter que les sources de données d'une seule chaîne/réseau. - -### Les subgraphs peuvent-ils réagir à des déclencheurs plus spécifiques ? - -Actuellement, seuls les déclencheurs de blocage et de réception sont pris en charge. Nous étudions les déclencheurs pour les appels de fonction à un compte spécifique. Nous souhaitons également prendre en charge les déclencheurs d'événements, une fois que NEAR disposera d'un support natif pour les événements. - -### Les gestionnaires de reçus se déclencheront-ils pour les comptes et leurs sous-comptes ? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -comptes: - suffixes: - - mintbase1.near -``` - -### Les subgraphs NEAR peuvent-ils faire des appels de view aux comptes NEAR pendant les mappings? - -Cette fonction n'est pas prise en charge. Nous sommes en train d'évaluer si cette fonctionnalité est nécessaire pour l'indexation. - -### Puis-je utiliser des modèles de sources de données dans mon subgraph NEAR ? - -Ceci n’est actuellement pas pris en charge. Nous évaluons si cette fonctionnalité est requise pour l'indexation. - -### Les subgraphs Ethereum supportent les versions "pending" et "current", comment puis-je déployer une version "pending" d'un subgraph NEAR ? - -La fonctionnalité "pending" n'est pas encore prise en charge pour les subgraphs NEAR. Dans l'intervalle, vous pouvez déployer une nouvelle version dans un autre subgraph "named", puis, lorsque celui-ci est synchronisé avec la tête de chaîne, vous pouvez redéployer dans votre subgraph principal "named", qui utilisera le même ID de déploiement sous-jacent, de sorte que le subgraph principal sera instantanément synchronisé. - -### Ma question n'a pas reçu de réponse, où puis-je obtenir plus d'aide concernant la création de subgraphs NEAR ? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## Les Références - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/fr/subgraphs/cookbook/polymarket.mdx b/website/src/pages/fr/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/fr/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/fr/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index cd3b3b46b7f9..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Comment sécuriser les clés d'API en utilisant les composants serveur de Next.js ---- - -## Aperçu - -Nous pouvons utiliser [les composants serveur de Next.js](https://nextjs.org/docs/app/building-your-application/rendering/server-components) pour sécuriser correctement notre clé API contre l'exposition dans le frontend de notre dapp. Pour augmenter encore la sécurité de notre clé API, nous pouvons également [restreindre notre clé API à certains subgraphs ou domaines dans Subgraph Studio.](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -Dans ce guide pratique, nous allons passer en revue la création d'un composant de serveur Next.js qui interroge un subgraph tout en masquant la clé API du frontend. - -### Mise en garde - -- Les composants serveur de Next.js ne protègent pas les clés API contre les attaques de déni de service. -- Les passerelles de The Graph Network disposent de stratégies de détection et d'atténuation des attaques de déni de service, cependant, l'utilisation des composants serveur peut affaiblir ces protections. -- Les composants serveur de Next.js introduisent des risques de centralisation car le serveur peut tomber en panne. - -### Pourquoi est-ce nécessaire - -Dans une application React standard, les clés API incluses dans le code frontend peuvent être exposées du côté client, posant un risque de sécurité. Bien que les fichiers `.env` soient couramment utilisés, ils ne protègent pas complètement les clés car le code de React est exécuté côté client, exposant ainsi la clé API dans les headers. Les composants serveur Next.js résolvent ce problème en gérant les opérations sensibles côté serveur. - -### Utilisation du rendu côté client pour interroger un subgraph - -![rendu côté client](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- Une clé API provenant de [Subgraph Studio](https://thegraph.com/studio) -- Une connaissance de base de Next.js et React. -- Un projet Next.js existant qui utilise l'[App Router](https://nextjs.org/docs/app). - -## Guide étape par étape - -### Étape 1 : Configurer les Variables d'Environnement - -1. À la racine de notre projet Next.js, créer un fichier `.env.local` . -2. Ajouter notre clé API :: `API_KEY=`. - -### Étape 2 : Créer un Composant Serveur - -1. Dans notre répertoire`components` , créer un nouveau fichier, `ServerComponent.js`. -2. Utiliser le code exemple fourni pour configurer le composant serveur. - -### Étape 3 : Implémenter la Requête API Côté Serveur - -Dans `ServerComponent.js`, ajouter le code suivant : - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Étape 4 : Utiliser le Composant Serveur - -1. Dans notre fichier de page (par exemple, `pages/index.js`), importer `ServerComponent`. -2. Rendu du composant: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Étape 5 : Lancer et tester notre Dapp - -Démarrez notre application Next.js en utilisant `npm run dev`. Vérifiez que le composant serveur récupère les données sans exposer la clé API. - -![Rendu côté serveur](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/fr/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/fr/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index cedcf3ece5c4..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Débogage rapide et facile des subgraph à l'aide de Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## D'accord, qu'est-ce que c'est ? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## Quoi ? Comment ? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## S'il vous plaît, montrez-moi du code ! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar introuvable!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -La méthode habituelle pour tenter de résoudre le problème est la suivante : - -1. Apportez une modification à la source des mappages, ce qui, selon vous, résoudra le problème (même si je sais que ce ne sera pas le cas). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Attendez qu’il soit synchronisé. -4. S'il se casse à nouveau, revenez au point 1, sinon : Hourra ! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Apportez une modification à la source des mappings qui, selon vous, résoudra le problème. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. S'il casse à nouveau, revenez à 1, sinon : Hourra ! - -Maintenant, vous pouvez avoir 2 questions : - -1. base de fourche quoi ??? -2. Fourcher qui ?! - -Je réponds : - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Fourcher est facile, pas besoin de transpirer : - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -Voici donc ce que je fais : - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NOM_RÉSEAU : [CAPABILITIES] :URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. J'inspecte les logs générés par le Graph Node local et, Hourra!, tout semble fonctionner. -5. Je déploie mon subgraph, désormais débarrassé de tout bug, sur un Graph Node distant et vis heureux pour toujours ! (Malheureusement pas de patates, mais c’est la vie…) diff --git a/website/src/pages/fr/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/fr/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index fadcd9b98faf..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Générateur de code de subgraph sécurisé ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Pourquoi intégrer Subgraph Uncrashable ? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- Le cadre comprend également un moyen (via le fichier de configuration) de créer des fonctions de définition personnalisées, mais sûres, pour des groupes de variables d'entité. De cette façon, il est impossible pour l'utilisateur de charger/utiliser une entité de graph obsolète et il est également impossible d'oublier de sauvegarder ou définissez une variable requise par la fonction. - -- Les logs d'avertissement sont enregistrés sous forme de logs indiquant où il y a une violation de la logique du subgraph pour aider à corriger le problème afin d'assurer l'exactitude des données. - -Subgraph Uncrashable peut être exécuté en tant qu'indicateur facultatif à l'aide de la commande Graph CLI codegen. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/fr/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/fr/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index d34a88327c64..000000000000 --- a/website/src/pages/fr/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Transférer vers The Graph ---- - -Mettez rapidement à jour vos subgraphs depuis n'importe quelle plateforme vers [le réseau décentralisé de The Graph](https://thegraph.com/networks/). - -## Avantages du passage à The Graph - -- Utilisez le même subgraph que vos applications utilisent déjà avec une migration sans interruption de service. -- Améliorez la fiabilité grâce à un réseau mondial pris en charge par plus de 100 Indexers. -- Bénéficiez d’un support ultra-rapide pour vos subgraphs 24/7, avec une équipe d’ingénieurs de garde. - -## Mettez à jour votre Subgraph vers The Graph en 3 étapes simples - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Configurer votre environnement Studio - -### Créer un subgraph dans Subgraph Studio - -- Accédez à [Subgraph Studio](https://thegraph.com/studio/) et connectez votre portefeuille. -- Cliquez sur « Créer un subgraph ». Il est recommandé de nommer le subgraph en majuscule : « Nom du subgraph Nom de la chaîne ». - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Installer Graph CLI - -Vous devez avoir Node.js et un gestionnaire de paquets de votre choix (`npm` or `pnpm`) installés pour utiliser Graph CLI. Vérifiez la version la [plus récente](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) de CLI. - -Sur votre machine locale, exécutez la commande suivante : - -Utilisation de [npm](https://www.npmjs.com/) : - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Utilisez la commande suivante pour créer un subgraph dans Studio en utilisant CLI : - -```sh -graph init --product subgraph-studio -``` - -### Authentifiez votre subgraph - -Dans Graph CLI, utilisez la commande auth vue dans Subgraph Studio : - -```sh -graph auth -``` - -## 2. Déployez votre Subgraph sur Studio - -Si vous avez votre code source, vous pouvez facilement le déployer sur Studio. Si vous ne l'avez pas, voici un moyen rapide de déployer votre subgraph. - -Dans Graph CLI, exécutez la commande suivante : - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:**: Chaque subgraph a un hash IPFS (ID de déploiement), qui ressemble à ceci : "Qmasdfad...". Pour déployer, utilisez simplement ce **hash IPFS**. Vous serez invité à entrer une version (par exemple, v0.0.1). - -## 3. Publier votre Subgraph sur The Graph Network - -![bouton de publication](/img/publish-sub-transfer.png) - -### Interroger votre Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Exemple - -[Subgraph Ethereum CryptoPunks](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) par Messari: - -![L'URL de requête](/img/cryptopunks-screenshot-transfer.png) - -L'URL de requête pour ce subgraph est : - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**votre-propre-clé-Api**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Maintenant, il vous suffit de remplir **votre propre clé API** pour commencer à envoyer des requêtes GraphQL à ce point de terminaison. - -### Obtenir votre propre clé API - -Vous pouvez créer des clés API dans Subgraph Studio sous le menu "API Keys" en haut de la page : - -![clés API](/img/Api-keys-screenshot.png) - -### Surveiller l'état du Subgraph - -Une fois que vous avez mis à jour, vous pouvez accéder et gérer vos subgraphs dans [Subgraph Studio](https://thegraph.com/studio/) et explorer tous les subgraphs dans [The Graph Explorer](https://thegraph.com/networks/). - -### Ressources supplémentaires - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- Pour explorer toutes les façons d'optimiser et de personnaliser votre subgraph pour de meilleures performances, lisez plus sur [la création d'un subgraph ici](/developing/creating-a-subgraph/). diff --git a/website/src/pages/fr/subgraphs/guides/_meta.js b/website/src/pages/fr/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/fr/subgraphs/guides/arweave.mdx b/website/src/pages/fr/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/fr/subgraphs/guides/enums.mdx b/website/src/pages/fr/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/fr/subgraphs/guides/grafting.mdx b/website/src/pages/fr/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/fr/subgraphs/guides/near.mdx b/website/src/pages/fr/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/fr/subgraphs/guides/polymarket.mdx b/website/src/pages/fr/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/fr/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/fr/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/fr/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/fr/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/fr/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/fr/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/fr/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/fr/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/fr/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/hi/subgraphs/_meta-titles.json b/website/src/pages/hi/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/hi/subgraphs/_meta-titles.json +++ b/website/src/pages/hi/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/hi/subgraphs/_meta.js b/website/src/pages/hi/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/hi/subgraphs/_meta.js +++ b/website/src/pages/hi/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/hi/subgraphs/cookbook/_meta.js b/website/src/pages/hi/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/hi/subgraphs/cookbook/arweave.mdx b/website/src/pages/hi/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index b51d9a5405bc..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: आरवीव पर सब-ग्राफ्र्स बनाना ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -इस गाइड में आप आरवीव ब्लॉकचेन पर सब ग्राफ्स बनाना और डेप्लॉय करना सीखेंगे! - -## आरवीव क्या है? - -आरवीव प्रोटोकॉल डेवेलपर्स को स्थायी तौर पर डाटा स्टोर करने की क्षमता देता है जो कि IPFS और आरवीव के बीच का मुख्या अंतर भी है, जहाँ IPFS में इस क्षमता की कमी है, वहीँ आरवीवे पर फाइल्स डिलीट या बदली नहीं जा सकती | - -अरवीव द्वारा पहले से ही कई लाइब्रेरी विभिन्न प्रोग्रामिंग भाषाओं में विकशित की गई हैं| अधिक जानकारी के लिए आप इनका रुख कर सकते हैं: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## आरवीवे सब ग्राफ्स क्या हैं? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## एक आरवीव सब ग्राफ बनाना - -आरवीवे पर सब ग्राफ बनाने के लिए हमे दो पैकेजेस की जरूरत है: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## सब ग्राफ के कॉम्पोनेन्ट - -सब ग्राफ के तीन कॉम्पोनेन्ट होते हैं: - -### 1. Manifest - `subgraph.yaml` - -डाटा का स्रोत्र और उनको प्रोसेस करने के बारे में बताता है| आरवीव एक नए प्रकार का डाटा सोर्स है| - -### 2. Schema - `schema.graphql` - -यहाँ आप बताते हैं की आप कौन सा डाटा इंडेक्सिंग के बाद क्वेरी करना चाहते हैं| दरसअल यह एक API के मॉडल जैसा है, जहाँ मॉडल द्वारा रिक्वेस्ट बॉडी का स्ट्रक्चर परिभाषित किया जाता है| - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -यह किसी के द्वारा इस्तेमाल किये जा रहे डाटा सोर्स से डाटा को पुनः प्राप्त करने और स्टोर करने के लॉजिक को बताता है| डाटा अनुवादित होकर आपके द्वारा सूचीबद्ध स्कीमा के अनुसार स्टोर हो जाता है| - -सब ग्राफ को बनाते वक़्त दो मुख्य कमांड हैं: - -``` -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -## सब ग्राफ मैनिफेस्ट की परिभाषा - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- अरवीव डाटा सोर्स द्वारा एक वैकल्पिक source.owner फील्ड लाया गया, जो की एक आरवीव वॉलेट का मपब्लिक key है| - -आरवीव डाटा सोर्स द्वारा दो प्रकार के हैंडलर्स उपयोग किये जा सकते हैं: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> यहां source.owner ओनर का एड्रेस या उनका पब्लिक की हो सकता है| -> -> ट्रांसक्शन आरवीव परमावेब के लिए निर्माण खंड (बिल्डिंग ब्लॉक्स) की तरह होते हैं और एन्ड-यूजर के द्वारा बनाये गए ऑब्जेक्ट होते हैं| -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## स्कीमा की परिभाषा - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## असेंबली स्क्रिप्ट मैप्पिंग्स - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## आरवीव सब-ग्राफ क्वेरी करना - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## सब-ग्राफ के उदाहरण - -सहायता के एक सब-ग्राफ का उदाहरण - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### क्या एक सब-ग्राफ आरवीव और बाकी चेन्स को इंडेक्स कर सकता है? - -नहीं, एक सब-ग्राफ केवल एक चेन/नेटवर्क से डाटा सोर्स को सपोर्ट कर सकता है - -### क्या मैं आरवीव पर स्टोर की फाइल्स को इंडेक्स कर सकता हूँ? - -वर्तमान में द ग्राफ आरवीव को केवल एक ब्लॉकचेन की तरह इंडेक्स करता है (उसके ब्लॉक्स और ट्रांसक्शन्स)| - -### क्या मैं अपने सब-ग्राफ में Bundlr बंडल्स को पहचान सकता हूँ? - -यह वर्तमान में सपोर्टेड नहीं है| - -### क्या मैं किसी विशिष्ट अकाउंट से ट्रांसक्शन्स छाँट सकता हूँ? - -एक यूजर का पब्लिक की या अकाउंट एड्रेस source.owner हो सकता है - -### वर्तमान एन्क्रिप्शन फॉर्मेट क्या है? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/hi/subgraphs/cookbook/enums.mdx b/website/src/pages/hi/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 3c588eace670..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: NFT मार्केटप्लेस को Enums का उपयोग करके श्रेणीबद्ध करें ---- - -Enams का उपयोग करके अपने कोड को साफ और कम त्रुटिपूर्ण बनाएं। यहां NFT मार्केटप्लेस पर Enams के उपयोग का एक पूरा उदाहरण है। - -## Enums क्या हैं? - -Enums, या enumeration types, एक विशिष्ट डेटा प्रकार होते हैं जो आपको विशिष्ट, अनुमत मानों का एक सेट परिभाषित करने की अनुमति देते हैं। - -### अपने Schema में Enums का उदाहरण - -यदि आप एक subgraph बना रहे हैं जो एक मार्केटप्लेस पर टोकन के स्वामित्व इतिहास को ट्रैक करता है, तो प्रत्येक टोकन विभिन्न स्वामित्वों से गुजर सकता है, जैसे कि OriginalOwner, SecondOwner, और ThirdOwner। enums का उपयोग करके, आप इन विशिष्ट स्वामित्वों को परिभाषित कर सकते हैं, यह सुनिश्चित करते हुए कि केवल पूर्वनिर्धारित मान ही सौंपे जाएं। - -आप अपनी स्कीमा में एन्सम्स (enums) को परिभाषित कर सकते हैं, और एक बार परिभाषित हो जाने के बाद, आप एन्सम के मानों की स्ट्रिंग प्रस्तुति का उपयोग करके एक एन्सम फ़ील्ड को एक entities पर सेट कर सकते हैं। - -यहां आपके स्कीमा में एक enum परिभाषा इस प्रकार हो सकती है, उपरोक्त उदाहरण के आधार पर: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -यह इसका मतलब है कि जब आप अपने स्कीमा में TokenStatus प्रकार का उपयोग करते हैं, तो आप इसकी अपेक्षा करते हैं कि यह पहले से परिभाषित मानों में से एक हो: OriginalOwner, SecondOwner, या ThirdOwner, जिससे निरंतरता और वैधता सुनिश्चित होती है। - -इस बारे में अधिक जानने के लिए Creating a Subgraph(/developing/creating-a-subgraph/#enums) और GraphQL documentation(https://graphql.org/learn/schema/#enumeration-types) देखें। - -## Enums का उपयोग करने के लाभ - -- स्पष्टता: Enums एन्उम्स मानों के लिए सार्थक नाम प्रदान करते हैं, जिससे डेटा को समझना आसान होता है। -- सत्यापन: Enums कड़े मान मान्यताएँ लागू करते हैं, जो अवैध डेटा प्रविष्टियों को रोकते हैं। -- रखरखाव: जब आपको नए श्रेणियाँ या ईनम्स (enums) जोड़ने या बदलने की आवश्यकता हो, तो आप इसे एक केंद्रित तरीके से कर सकते हैं। - -### बिना Enums - -यदि आप Enum का उपयोग करने के बजाय प्रकार को एक स्ट्रिंग के रूप में परिभाषित करते हैं, तो आपका कोड इस प्रकार दिख सकता है: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -इस स्कीमा में, TokenStatus एक साधारण स्ट्रिंग है जिसमें कोई विशिष्ट, अनुमत मान नहीं होते हैं। - -#### यह एक समस्या क्यों है? - -- TokenStatus मानों की कोई सीमा नहीं है, इसलिए कोई भी स्ट्रिंग गलती से असाइन की जा सकती है। इससे यह सुनिश्चित करना कठिन हो जाता है कि केवल वैध स्टेटस जैसे OriginalOwner, SecondOwner, या ThirdOwner सेट किए जाएं। -- यह टाइपो करना आसान है जैसे Orgnalowner को OriginalOwner के बजाय, जिससे डेटा और संभावित queries अप्रतिबद्ध हो सकती हैं। - -### Enums के साथ - -इसके बजाय कि आप फ्री-फॉर्म स्ट्रिंग्स असाइन करें, आप TokenStatus के लिए एक enum परिभाषित कर सकते हैं जिसमें विशिष्ट मान हों: OriginalOwner, SecondOwner, या ThirdOwner। enum का उपयोग करने से यह सुनिश्चित होता है कि केवल अनुमत मान ही उपयोग किए जाएं। - -Enums प्रकार सुरक्षा प्रदान करते हैं, टाइपो के जोखिम को कम करते हैं, और सुनिश्चित करते हैं कि परिणाम लगातार और विश्वसनीय हों। - -## NFT मार्केटप्लेस के लिए एन्उम्स को परिभाषित करना - -> नोट: निम्नलिखित guide CryptoCoven NFT स्मार्ट कॉन्ट्रैक्ट का उपयोग करती है। - -NFTs जहां ट्रेड होते हैं, उन विभिन्न मार्केटप्लेस के लिए enums को परिभाषित करने के लिए, अपने Subgraph स्कीमा में निम्नलिखित का उपयोग करें: - -```gql -#मार्केटप्लेस के लिए Enum जो CryptoCoven कॉन्ट्रैक्ट के साथ इंटरएक्टेड हैं (संभवत: ट्रेड/मिंट) -enum Marketplace { - OpenSeaV1 # जब CryptoCoven NFT को इस बाजार में व्यापार किया जाता है - OpenSeaV2 # जब CryptoCoven NFT को OpenSeaV2 बाजार में व्यापार किया जाता है - SeaPort # जब CryptoCoven NFT को SeaPort बाजार में व्यापार किया जाता है - LooksRare # जब CryptoCoven NFT को LooksRare बाजार में व्यापार किया जाता है - # ...और अन्य बाजार -} -``` - -## NFT Marketplaces के लिए Enums का उपयोग - -एक बार परिभाषित होने पर, enums का उपयोग आपके subgraph में transactions या events को श्रेणीबद्ध करने के लिए किया जा सकता है। - -उदाहरण के लिए, जब logging NFT बिक्री लॉग करते हैं, तो आप ट्रेड में शामिल मार्केटप्लेस को enum का उपयोग करके निर्दिष्ट कर सकते हैं। - -### NFT मार्केटप्लेस के लिए एक फंक्शन लागू करना - -यहाँ बताया गया है कि आप एक फ़ंक्शन को कैसे लागू कर सकते हैं जो enum से मार्केटप्लेस का नाम एक स्ट्रिंग के रूप में प्राप्त करता है: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // यदि-और-else कथनों का उपयोग करके enum मान को एक स्ट्रिंग में मैप करें - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // यदि बाज़ार OpenSea है, तो इसकी स्ट्रिंग प्रतिनिधित्व लौटाएँ - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // यदि बाज़ार SeaPort है, तो इसकी स्ट्रिंग प्रतिनिधित्व लौटाएँ - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // यदि बाज़ार LooksRare है, तो इसकी स्ट्रिंग प्रतिनिधित्व लौटाएँ - // ... और अन्य बाज़ार - } -} -``` - -## Enums का उपयोग करने के लिए सर्वोत्तम प्रथाएँ - -- सुसंगत नामकरण: पठनीयता को बेहतर बनाने के लिए enum मानों के लिए स्पष्ट, वर्णनात्मक नामों का उपयोग करें। -- केंद्रीकृत प्रबंधन: एकल फ़ाइल में enums रखें ताकि सुसंगतता बनी रहे। इससे enums को अपडेट करना आसान हो जाता है और यह सत्य का एकमात्र source बनता है। -- दस्तावेज़ीकरण: एनम में उनकी उद्देश्य और उपयोग को स्पष्ट करने के लिए टिप्पणियाँ जोड़ें। - -## queries में Enums का उपयोग करना - -क्वेरी में Enums आपके डेटा की गुणवत्ता में सुधार करने और आपके परिणामों को समझने में आसान बनाने में मदद करते हैं। ये फ़िल्टर और प्रतिक्रिया तत्व के रूप में कार्य करते हैं, बाज़ार के मूल्यों में स्थिरता सुनिश्चित करते हैं और त्रुटियों को कम करते हैं। - -**विशिष्टताएँ** - -- **Enums के साथ फ़िल्टरिंग:** Enums स्पष्ट फ़िल्टर प्रदान करते हैं, जिससे आप निश्चित रूप से विशिष्ट मार्केटप्लेस को शामिल या बाहर कर सकते हैं। -- **प्रतिसादों में Enums:** एन्‍यम्‍स यह सुनिश्चित करते हैं कि केवल मान्यता प्राप्त मार्केटप्लेस नाम ही वापस आएं, जिससे परिणाम मानकीकृत और सटीक हों। - -### नमूना queries - -#### Query 1: सबसे अधिक NFT मार्केटप्लेस इंटरएक्शन वाला खाता - -यह क्वेरी निम्नलिखित कार्य करती है: - -- यह खाते को खोजता है जिसमें सबसे अधिक अनूठे NFT मार्केटप्लेस इंटरैक्शन होते हैं, जो क्रॉस-मार्केटप्लेस गतिविधि का विश्लेषण करने के लिए बेहतरीन है। -- मार्केटप्लेस फील्ड marketplace एनम का उपयोग करता है, जो प्रतिक्रिया में सुसंगत और मान्य मार्केटप्लेस मान सुनिश्चित करता है। - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### रिटर्न्स - -यह प्रतिक्रिया खाता विवरण और मानकीकृत स्पष्टता के लिए एनम मानों के साथ अद्वितीय मार्केटप्लेस इंटरैक्शन्स की सूची प्रदान करती है: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: CryptoCoven transactions के लिए सबसे सक्रिय बाज़ार - -यह क्वेरी निम्नलिखित कार्य करती है: - -- यह उस मार्केटप्लेस की पहचान करता है जहां CryptoCoven लेनदेन का सबसे अधिक वॉल्यूम होता है। -- यह मार्केटप्लेस enum का उपयोग करता है ताकि प्रतिक्रिया में केवल मान्य मार्केटप्लेस प्रकार ही दिखाई दें, जिससे आपके डेटा में विश्वसनीयता और स्थिरता बनी रहती है। - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### परिणाम 2 - -अपेक्षित प्रतिक्रिया में मार्केटप्लेस और संबंधित transaction संख्या शामिल है, जो मार्केटप्लेस प्रकार को संकेत करने के लिए enum का उपयोग करती है: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### प्रश्न 3: उच्च लेन-देन गणना के साथ बाज़ार परस्पर क्रियाएँ - -यह क्वेरी निम्नलिखित कार्य करती है: - -- यह 100 से अधिक transactions वाले शीर्ष चार बाजारों को पुनः प्राप्त करता है, "Unknown" बाजारों को छोड़कर। -- यह केवल वैध मार्केटप्लेस प्रकारों को शामिल करने के लिए फ़िल्टर के रूप में एंनम का उपयोग करता है, जिससे सटीकता बढ़ती है। - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### परिणाम 3 - -अपेक्षित आउटपुट में उन मार्केटप्लेस का समावेश है जो मानदंडों को पूरा करते हैं, प्रत्येक को एक enum मान द्वारा प्रदर्शित किया जाता है: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Additional Resources - -अधिक जानकारी के लिए, इस guide's के [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums) को देखें। diff --git a/website/src/pages/hi/subgraphs/cookbook/grafting.mdx b/website/src/pages/hi/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index c0703bcfb101..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: एक कॉन्ट्रैक्ट बदलें और उसका इतिहास ग्राफ्टिंग के साथ रखें ---- - -इस गाइड में, आप सीखेंगे कि मौजूदा सबग्राफ को ग्राफ्ट करके नए सबग्राफ कैसे बनाएं और तैनात करें। - -## ग्राफ्टिंग क्या है? - -ग्राफ्टिंग एक वर्तमान सब-ग्राफ के डाटा का दोबारा इस्तेमाल करता है और उसे बाद के ब्लॉक्स में इंडेक्स करना चालू कर देता है| यह विकास की प्रक्रिया में उपयोगी है क्यूंकि इसकी वजह से मैप्पिंग्स में छोटी-मोटी त्रुटियों से छुटकारा पाया जा सकता है या फिर एक मौजूदा सब-ग्राफ को विफल होने के बाद दोबारा चालू किया जा सकता है| साथ हीं, इसका इस्तेमाल ऐसे सब-ग्राफ में कोई खूबी जोड़ते वक़्त भी किया जा सकता है जिसमे शुरुआत से इंडेक्स करने में काफी लम्बा वक़्त लगता हो| - -ग्राफ्टेड सबग्राफ एक ग्राफक्यूएल स्कीमा का उपयोग कर सकता है जो बेस सबग्राफ के समान नहीं है, लेकिन इसके अनुकूल हो। यह अपने आप में एक मान्य सबग्राफ स्कीमा होना चाहिए, लेकिन निम्नलिखित तरीकों से बेस सबग्राफ के स्कीमा से विचलित हो सकता है: - -- यह इकाई के प्रकारों को जोड़ या हटा सकता है| -- यह इकाई प्रकारों में से गुणों को हटाता है| -- यह प्रभावहीन गुणों को इकाई प्रकारों में जोड़ता है| -- यह प्रभाव वाले गुणों को प्रभावहीन गुणों में बदल देता है| -- यह इनम्स में महत्व देता है| -- यह इंटरफेस जोड़ता या हटाता है| -- यह कि, किन इकाई प्रकारों के लिए इंटरफ़ेस लागू होगा, इसे बदल देता है| - -अधिक जानकारी के लिए आप देख सकते हैं: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -इस ट्यूटोरियल में, हम एक बुनियादी उपयोग मामले को कवर करेंगे। हम एक मौजूदा कॉन्ट्रैक्ट को एक समान कॉन्ट्रैक्ट (नए पते के साथ, लेकिन वही कोड) से बदलेंगे। फिर, मौजूदा Subgraph को "बेस" Subgraph पर जोड़ेंगे, जो नए कॉन्ट्रैक्ट को ट्रैक करता है। - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting एक शक्तिशाली विशेषता है जो आपको एक सबग्राफ़ को दूसरे पर "graft" करने की अनुमति देती है, जिससे मौजूदा सबग्राफ़ से नए संस्करण में ऐतिहासिक डेटा को प्रभावी ढंग से स्थानांतरित किया जा सके।The Graph Network से सबग्राफ़ को Subgraph Studioमें वापस graft करना संभव नहीं है। - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## एक मौजूदा सब-ग्राफ बनाना - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## सब ग्राफ मैनिफेस्ट की परिभाषा - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## ग्राफ्टिंग मैनिफेस्ट की परिभाषा - -ग्राफ्टिंग करने के लिए मूल सब-ग्राफ मैनिफेस्ट में 2 नई चीज़ें जोड़ने की आवश्यकता है: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## बेस सब-ग्राफ को तैनात करना - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. एक बार पूरा होने पर, सत्यापित करें की इंडेक्सिंग सही ढंग से हो गयी है| यदि आप निम्न कमांड ग्राफ प्लेग्राउंड में चलाते हैं - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -तो हमे कुछ ऐसा दिखता है: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -एक बार आपका सत्यापित सब-ग्राफ ढंग से इंडेक्स हो जाता है तो आप बिना किसी देरी के अपना सब-ग्राफ को ग्राफ्टिंग से अपडेट कर सकते हैं| - -## ग्राफ्टिंग सब-ग्राफ तैनात करना - -ग्राफ्ट प्रतिस्तापित subgraph.yaml में एक नया कॉन्ट्रैक्ट एड्रेस होगा| यह तब हो सकता है जब आप अपना डैप अपडेट करें, कॉन्ट्रैक्ट को दोबारा तैनात करें, इत्यादि| - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. एक बार पूरा होने पर, सत्यापित करें की इंडेक्सिंग सही ढंग से हो गयी है| यदि आप निम्न कमांड ग्राफ प्लेग्राउंड में चलाते हैं - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -आपको यह वापस मिलना चाहिए: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Additional Resources - -यदि आप grafting के साथ अधिक अनुभव प्राप्त करना चाहते हैं, तो यहां कुछ लोकप्रिय कॉन्ट्रैक्ट्स के उदाहरण दिए गए हैं: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/hi/subgraphs/cookbook/near.mdx b/website/src/pages/hi/subgraphs/cookbook/near.mdx deleted file mode 100644 index 6aab3eeedbb4..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: NEAR पर सबग्राफ बनाना ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## NEAR क्या है? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## NEAR सबग्राफ क्या हैं? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- ब्लॉक हैंडलर्स: ये हर नए ब्लॉक पर चलते हैं -- रसीद हैंडलर: किसी निर्दिष्ट खाते पर संदेश निष्पादित होने पर हर बार चलें - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> रसीद सिस्टम में एकमात्र कार्रवाई योग्य वस्तु है। जब हम NEAR प्लेटफॉर्म पर "एक लेन-देन को संसाधित करने" के बारे में बात करते हैं, तो अंततः इसका अर्थ किसी बिंदु पर "रसीदें लागू करना" होता है। - -## NEAR सबग्राफ बनाना - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> NEAR सबग्राफ का निर्माण वह सबग्राफ के निर्माण के समान है जो एथेरियम को अनुक्रमित करता है। - -सबग्राफ परिभाषा के तीन पहलू हैं: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -सब ग्राफ को बनाते वक़्त दो मुख्य कमांड हैं: - -```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -### सब ग्राफ मैनिफेस्ट की परिभाषा - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR डेटा स्रोत दो प्रकार के हैंडलर का समर्थन करते हैं: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### स्कीमा की परिभाषा - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### असेंबली स्क्रिप्ट मैप्पिंग्स - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## एक NEAR सबग्राफ की तैनाती - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -नोड कॉन्फ़िगरेशन इस बात पर निर्भर करेगा कि सबग्राफ को कहाँ तैनात किया जा रहा है। - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### स्थानीय ग्राफ़ नोड (डिफ़ॉल्ट कॉन्फ़िगरेशन पर आधारित) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -एक बार आपका सबग्राफ तैनात हो जाने के बाद, इसे ग्राफ़ नोड द्वारा अनुक्रमित किया जाएगा। आप सबग्राफ को क्वेरी करके इसकी प्रगति की जांच कर सकते हैं: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### एक स्थानीय ग्राफ़ नोड के साथ NEAR को अनुक्रमणित करना - -NEAR को अनुक्रमित करने वाले ग्राफ़ नोड को चलाने के लिए निम्नलिखित परिचालन आवश्यकताएँ हैं: - -- Firehose इंस्ट्रूमेंटेशन के साथ NEAR इंडेक्सर फ्रेमवर्क -- NEAR Firehose कंपोनेंट्(स) -- Firehose एंडपॉइन्ट के साथ ग्राफ़ नोड कॉन्फ़िगर किया गया - -हम जल्द ही उपरोक्त कंपोनेंट्स को चलाने के बारे में और जानकारी प्रदान करेंगे। - -## NEAR सबग्राफ को क्वेरी करना - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## सब-ग्राफ के उदाहरण - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### बीटा कैसे काम करता है? - -NEAR समर्थन बीटा में है, जिसका मतलब है कि एपीआई में बदलाव हो सकते हैं क्योंकि हम इंटीग्रेशन में सुधार पर काम करना जारी रखेंगे। कृपया near@thegraph.com पर ईमेल करें ताकि हम NEAR सबग्राफ बनाने में आपकी सहायता कर सकें, और आपको नवीनतम विकासों के बारे में अपडेट रख सकें! - -### Can a subgraph index both NEAR and EVM chains? - -नहीं, एक सब-ग्राफ केवल एक चेन/नेटवर्क से डाटा सोर्स को सपोर्ट कर सकता है - -### क्या सबग्राफ अधिक विशिष्ट ट्रिगर्स पर प्रतिक्रिया कर सकते हैं? - -वर्तमान में, केवल अवरोधित करें और प्राप्त करें ट्रिगर समर्थित हैं। हम एक निर्दिष्ट खाते में फ़ंक्शन कॉल के लिए ट्रिगर्स की जांच कर रहे हैं। एक बार जब NEAR को नेटिव ईवेंट समर्थन मिल जाता है, तो हम ईवेंट ट्रिगर्स का समर्थन करने में भी रुचि रखते हैं। - -### क्या रसीद हैंडलर खातों और उनके उप-खातों के लिए ट्रिगर करेंगे? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### क्या मैपिंग के दौरान NEAR सबग्राफ, NEAR खातों को व्यू कॉल कर सकते हैं? - -यह समर्थित नहीं है। हम मूल्यांकन कर रहे हैं कि अनुक्रमण के लिए यह कार्यक्षमता आवश्यक है या नहीं। - -### क्या मैं अपने NEAR सबग्राफ में डेटा स्रोत टेम्प्लेट का उपयोग कर सकता हूँ? - -यह वर्तमान में समर्थित नहीं है। हम मूल्यांकन कर रहे हैं कि अनुक्रमण के लिए यह कार्यक्षमता आवश्यक है या नहीं। - -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? - -NEAR सबग्राफ के लिए पेंडिंग कार्यक्षमता अभी तक समर्थित नहीं है। अंतरिम में, आप एक अलग "नामित" सबग्राफ के लिए एक नया संस्करण तैनात कर सकते हैं, और फिर जब वह चेन हेड के साथ सिंक हो जाता है, तो आप अपने प्राथमिक "नामित" सबग्राफ में फिर से तैनात कर सकते हैं, जो उसी अंतर्निहित डेप्लॉयमेंट आईडी का उपयोग करेगा, इसलिए मुख्य सबग्राफ तुरंत सिंक हो जाएगा। - -### My question hasn't been answered, where can I get more help building NEAR subgraphs? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## संदर्भ - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/hi/subgraphs/cookbook/polymarket.mdx b/website/src/pages/hi/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/hi/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/hi/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 4e690b3b4f7e..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: कैसे सुरक्षित करें API Keys का उपयोग करके Next.js Server Components ---- - -## अवलोकन - -हम Next.js server components(https://nextjs.org/docs/app/building-your-application/rendering/server-components) का उपयोग करके अपने dapp के frontend में API key को exposure से सुरक्षित रख सकते हैं। API key की सुरक्षा को और बढ़ाने के लिए, हम Subgraph Studio में अपनी API key को कुछ subgraphs या domains तक सीमित कर सकते हैं(/cookbook/upgrading-a-subgraph/#securing-your-api-key) - -इस cookbook में, हम यह समझेंगे कि कैसे एक Next.js server component बनाया जाए जो subgraph से query करता है, साथ ही API key को frontend से छिपाने का तरीका भी शामिल है। - -### चेतावनी - -- Next.js सर्वर घटक डिनायल ऑफ़ सर्विस अटैक का उपयोग करके API कुंजियों को समाप्त होने से सुरक्षित नहीं कर सकते। -- The Graph Network gateways में सेवा को बाधित करने के हमलों का पता लगाने और उन्हें रोकने की रणनीतियाँ मौजूद हैं, हालांकि server components का उपयोग करने से ये सुरक्षा कमजोर हो सकती है। -- Next.js server components केंद्रीकरण के जोखिम प्रस्तुत करते हैं क्योंकि सर्वर बंद हो सकता है। - -### यह क्यों आवश्यक है - -एक मानक React एप्लिकेशन में, फ्रंटेंड कोड में शामिल API कुंजियाँ क्लाइंट-साइड पर उजागर हो सकती हैं, जिससे सुरक्षा का जोखिम बढ़ता है। जबकि.env फ़ाइलें सामान्यत: उपयोग की जाती हैं, ये कुंजियों की पूरी सुरक्षा नहीं करतीं क्योंकि React का कोड क्लाइंट साइड पर निष्पादित होता है, जो API कुंजी को हेडर में उजागर करता है। Next.js सर्वर घटक इस मुद्दे का समाधान करते हैं द्वारा संवेदनशील कार्यों को सर्वर-साइड पर संभालना। - -### क्लाइंट-साइड रेंडरिंग का उपयोग करके एक subgraph को क्वेरी करना - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- [Subgraph Studio](https://thegraph.com/studio) से एक API कुंजी -- Next.js और React का बुनियादी ज्ञान -- एक मौजूदा Next.js प्रोजेक्ट जो App Router (https://nextjs.org/docs/app). का उपयोग करता है। - -## स्टेप-बाय-स्टेप कुकबुक - -### चरण 1: पर्यावरण चर सेट करें - -1. हमारे Next.js प्रोजेक्ट की जड़ में, एक.env.local फ़ाइल बनाएं। -2. हमारा API कुंजी जोड़ें: `API_KEY=`. - -### चरण 2: एक सर्वर घटक बनाएं - -1. हमारे components निर्देशिका में, एक नया फ़ाइल बनाएं, ServerComponent.js। -2. प्रदान किए गए उदाहरण कोड का उपयोग करके सर्वर घटक सेट करें। - -### चरण 3: सर्वर-साइड API अनुरोध को लागू करें - -ServerComponent.js में, निम्नलिखित कोड जोड़ें: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### चरण 4: सर्वर घटक का उपयोग करें - -1. हमारी पृष्ठ फ़ाइल (जैसे, pages/index.js) में ServerComponent आयात करें। -2. कंपोनेंट को रेंडर करें: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### चरण 5: हमारा Dapp चलाएँ और परीक्षण करें - -अपने Next.js एप्लिकेशन को npm run dev का उपयोग करके प्रारंभ करें। सत्यापित करें कि सर्वर कंपोनेंट डेटा प्राप्त कर रहा है बिना API कुंजी को उजागर किए। - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### निष्कर्ष - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/hi/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/hi/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 0dc044459311..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: फोर्क्स का उपयोग करके त्वरित और आसान सबग्राफ डिबगिंग ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## ठीक है वो क्या है? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## क्या?! कैसे? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## कृपया मुझे कुछ कोड दिखाओ! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -फिक्स का प्रयास करने का सामान्य तरीका है: - -1. मैपिंग सोर्स में बदलाव करें, जो आपको लगता है कि समस्या का समाधान करेगा (जबकि मुझे पता है कि यह नहीं होगा)। -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. इसके सिंक-अप होने की प्रतीक्षा करें। -4. यदि यह फिर से टूट जाता है तो 1 पर वापस जाएँ, अन्यथा: हुर्रे! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. मैपिंग सोर्स में परिवर्तन करें, जिसके बारे में आपको लगता है कि इससे समस्या हल हो जाएगी. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. यदि यह फिर से ब्रेक जाता है, तो 1 पर वापस जाएँ, अन्यथा: हुर्रे! - -अब, आपके 2 प्रश्न हो सकते हैं: - -1. फोर्क-बेस क्या??? -2. फोर्किंग कौन?! - -और मैं उत्तर देता हूं: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. फोर्किंग आसान है, पसीना बहाने की जरूरत नहीं: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -तो, यहाँ मैं क्या करता हूँ: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/hi/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/hi/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index ace90495aef8..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: सुरक्षित सबग्राफ कोड जेनरेटर ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## सबग्राफ अनक्रैशेबल के साथ एकीकृत क्यों करें? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- फ्रेमवर्क में इकाई वैरिएबल के समूहों के लिए कस्टम, लेकिन सुरक्षित, सेटर फ़ंक्शन बनाने का एक तरीका (कॉन्फिग फ़ाइल के माध्यम से) भी शामिल है। इस तरह उपयोगकर्ता के लिए एक पुरानी ग्राफ़ इकाई को लोड/उपयोग करना असंभव है और फ़ंक्शन द्वारा आवश्यक वैरिएबल को सहेजना या सेट करना भूलना भी असंभव है। - -- चेतावनी लॉग को लॉग के रूप में रिकॉर्ड किया जाता है, जो यह इंगित करता है कि Subgraph लॉजिक में कहां उल्लंघन हो रहा है, ताकि समस्या को ठीक किया जा सके और डेटा की सटीकता सुनिश्चित हो सके। - -सबग्राफ अनक्रैशेबल को ग्राफ़ CLI codegen कमांड का उपयोग करके एक वैकल्पिक फ़्लैग के रूप में चलाया जा सकता है। - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/hi/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/hi/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index ae5023b492a4..000000000000 --- a/website/src/pages/hi/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: The Graph पर ट्रांसफर करें ---- - -अपने subgraphs को किसी भी प्लेटफ़ॉर्म से The Graph's decentralized network(https://thegraph.com/networks/) में जल्दी से अपग्रेड करें। - -## The Graph पर स्विच करने के लाभ - -- आपके ऐप्स द्वारा पहले से उपयोग किए जा रहे वही subgraph को बिना किसी डाउनटाइम के माइग्रेशन के लिए उपयोग करें। -- 100+ Indexers द्वारा समर्थित एक वैश्विक नेटवर्क से विश्वसनीयता बढ़ाएं। -- सबग्राफ के लिए 24/7 तेज़ और तुरंत समर्थन प्राप्त करें, एक ऑन-कॉल इंजीनियरिंग टीम के साथ। - -## अपने Subgraph को The Graph में 3 आसान कदमों में अपग्रेड करें - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. अपने स्टूडियो वातावरण को सेट करें - -### सबग्राफ बनाएँ Subgraph Studio में - -- [Subgraph Studio](https://thegraph.com/studio/) पर जाएँ और अपने वॉलेट को कनेक्ट करें। -- "एक सबग्राफ बनाएं" पर क्लिक करें। सबग्राफ का नाम टाइटल केस में रखनाrecommended है: "सबग्राफ नाम चेन नाम"। - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Graph CLI स्थापित करें - -आपको Node.js(https://nodejs.org/) और अपनी पसंद का पैकेज मैनेजर (npm या pnpm) इंस्टॉल करना होगा ताकि आप Graph CLI का उपयोग कर सकें। सबसे हालिया(https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI संस्करण चेक करें। - -अपने लोकल मशीन पर, निम्नलिखित कमांड चलाएँ: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -इस कमांड का उपयोग करें और CLI का उपयोग करके Studio में एक subgraph बनाएँ: - -```sh -graph init --product subgraph-studio -``` - -### अपने Subgraph को प्रमाणित करें - -The Graph CLI में, 'auth' कमांड का उपयोग करें जो Subgraph Studio में देखा गया है: - -```sh -graph auth -``` - -## 2. अपने Subgraph को Studio पर डिप्लॉय करें - -यदि आपके पास अपना सोर्स कोड है, तो आप इसे आसानी से Studio में डिप्लॉय कर सकते हैं। यदि आपके पास यह नहीं है, तो यहां एक त्वरित तरीका है अपनी subgraph को डिप्लॉय करने का। - -The Graph CLI में, निम्नलिखित कमांड चलाएँ: - -```sh -graph deploy --ipfs-hash - -``` - -> नोट: प्रत्येक subgraph का एक IPFS हैश (Deployment ID) होता है, जो इस प्रकार दिखता है: "Qmasdfad...". बस इसे deploy करने के लिए इस IPFS हैश का उपयोग करें। आपको एक संस्करण दर्ज करने के लिए कहा जाएगा (जैसे, v0.0.1)। - -## 3. अपने Subgraph को The Graph Network पर प्रकाशित करें - -![पब्लिश बटन](/img/publish-sub-transfer.png) - -### अपने Subgraph को क्वेरी करें - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### उदाहरण - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -इस subgraph का क्वेरी URL है: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -अब, आपको केवल अपना API Key भरने की आवश्यकता है ताकि आप इस endpoint पर GraphQL queries भेज सकें। - -### अपनी खुद की API Key प्राप्त करना - -आप Subgraph Studio में पृष्ठ के शीर्ष पर “API Keys” मेनू के तहत API Keys बना सकते हैं: - -![API keys](/img/Api-keys-screenshot.png) - -### सबग्राफ की स्थिति की निगरानी करें - -एक बार जब आप अपग्रेड करते हैं, तो आप Subgraph Studio(https://thegraph.com/studio/) में अपने सबग्राफ्स को एक्सेस और प्रबंधित कर सकते हैं और The Graph Explorer(https://thegraph.com/networks/) में सभी सबग्राफ्स को एक्सप्लोर कर सकते हैं। - -### Additional Resources - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- आप अपने subgraph के प्रदर्शन को बेहतर बनाने के लिए इसे अनुकूलित और कस्टमाइज़ करने के सभी तरीकों का पता लगाने के लिए, creating a subgraph here(/developing/creating-a-subgraph/) पर और पढ़ें। diff --git a/website/src/pages/hi/subgraphs/guides/_meta.js b/website/src/pages/hi/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/hi/subgraphs/guides/arweave.mdx b/website/src/pages/hi/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/hi/subgraphs/guides/enums.mdx b/website/src/pages/hi/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/hi/subgraphs/guides/grafting.mdx b/website/src/pages/hi/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/hi/subgraphs/guides/near.mdx b/website/src/pages/hi/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/hi/subgraphs/guides/polymarket.mdx b/website/src/pages/hi/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/hi/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/hi/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/hi/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/hi/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/hi/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/hi/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/hi/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/hi/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/hi/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/it/subgraphs/_meta-titles.json b/website/src/pages/it/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/it/subgraphs/_meta-titles.json +++ b/website/src/pages/it/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/it/subgraphs/_meta.js b/website/src/pages/it/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/it/subgraphs/_meta.js +++ b/website/src/pages/it/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/it/subgraphs/cookbook/_meta.js b/website/src/pages/it/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/it/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/it/subgraphs/cookbook/near.mdx b/website/src/pages/it/subgraphs/cookbook/near.mdx deleted file mode 100644 index 809574aa81cd..000000000000 --- a/website/src/pages/it/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Building Subgraphs on NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## What is NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## What are NEAR subgraphs? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Block handlers: these are run on every new block -- Receipt handlers: run every time a message is executed at a specified account - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. - -## Building a NEAR Subgraph - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. - -There are three aspects of subgraph definition: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -During subgraph development there are two key commands: - -```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -### Subgraph Manifest Definition - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR data sources support two types of handlers: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Schema Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Deploying a NEAR Subgraph - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -The node configuration will depend on where the subgraph is being deployed. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Local Graph Node (based on default configuration) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexing NEAR with a Local Graph Node - -Running a Graph Node that indexes NEAR has the following operational requirements: - -- NEAR Indexer Framework with Firehose instrumentation -- NEAR Firehose Component(s) -- Graph Node with Firehose endpoint configured - -We will provide more information on running the above components soon. - -## Querying a NEAR Subgraph - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Example Subgraphs - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### How does the beta work? - -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! - -### Can a subgraph index both NEAR and EVM chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can subgraphs react to more specific triggers? - -Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. - -### Will receipt handlers trigger for accounts and their sub-accounts? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? - -This is not supported. We are evaluating whether this functionality is required for indexing. - -### Can I use data source templates in my NEAR subgraph? - -This is not currently supported. We are evaluating whether this functionality is required for indexing. - -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? - -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. - -### My question hasn't been answered, where can I get more help building NEAR subgraphs? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## Riferimenti - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/it/subgraphs/cookbook/polymarket.mdx b/website/src/pages/it/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/it/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/it/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/it/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index fba106e6eaf6..000000000000 --- a/website/src/pages/it/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## Panoramica - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/it/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/it/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 4c435d24f56c..000000000000 --- a/website/src/pages/it/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Esempio - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Additional Resources - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/it/subgraphs/guides/_meta.js b/website/src/pages/it/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/it/subgraphs/guides/arweave.mdx b/website/src/pages/it/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/it/subgraphs/guides/enums.mdx b/website/src/pages/it/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/it/subgraphs/guides/grafting.mdx b/website/src/pages/it/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/it/subgraphs/guides/near.mdx b/website/src/pages/it/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/it/subgraphs/guides/polymarket.mdx b/website/src/pages/it/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/it/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/it/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/it/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/it/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/it/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/it/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/it/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/it/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/it/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ja/subgraphs/_meta-titles.json b/website/src/pages/ja/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/ja/subgraphs/_meta-titles.json +++ b/website/src/pages/ja/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/ja/subgraphs/_meta.js b/website/src/pages/ja/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/ja/subgraphs/_meta.js +++ b/website/src/pages/ja/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/ja/subgraphs/cookbook/_meta.js b/website/src/pages/ja/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/ja/subgraphs/cookbook/arweave.mdx b/website/src/pages/ja/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index b834f96b5cb9..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Arweaveでのサブグラフ構築 ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -このガイドでは、Arweaveブロックチェーンのインデックスを作成するためのサブグラフの構築とデプロイ方法について学びます。 - -## Arweaveとは? - -Arweave プロトコルは、開発者がデータを永久に保存することを可能にし、それが Arweave と IPFS の主な違いです。IPFSは永続性に欠ける一方、Arweaveに保存されたファイルは変更も削除もできません。 - -Arweaveは既に、さまざまなプログラミング言語でプロトコルを統合するための多数のライブラリを構築しています。詳細については、次を確認できます。 - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## Arweaveサブグラフとは? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Arweave サブグラフの作成 - -Arweaveのサブグラフを構築し展開できるようにするためには、2つのパッケージが必要です。 - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## サブグラフのコンポーネント - -サブグラフには3つの構成要素があります: - -### 1. Manifest - `subgraph.yaml` - -対象のデータ ソースとその処理方法を定義します。 Arweave は新しい種類のデータ ソースです。 - -### 2. Schema - `schema.graphql` - -ここでは、GraphQL を使用してサブグラフにインデックスを付けた後にクエリできるようにするデータを定義します。これは実際には API のモデルに似ており、モデルはリクエスト本文の構造を定義します。 - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -これは、リスニングしているデータソースと誰かがやりとりするときに、データをどのように取得し、保存するかを決定するロジックです。データは変換され、あなたがリストアップしたスキーマに基づいて保存されます。 - -サブグラフの開発には 2 つの重要なコマンドがあります: - -``` -$ graph codegen # マニフェストで識別されたようにファイルから型を生成します -$ グラフ ビルド # AssemblyScript ファイルから Web アセンブリを生成し、/build フォルダにすべてのサブグラフ ファイルを準備します -``` - -## サブグラフマニフェストの定義 - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave データ ソースには、オプションの source.owner フィールドが導入されています。これは、Arweave ウォレットの公開鍵です。 - -Arweaveデータソースは 2 種類のハンドラーをサポートしています: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> Source.owner は、所有者のアドレスまたは公開鍵にすることができます。 -> -> トランザクションはArweave permawebの構成要素であり、エンドユーザーによって作成されるオブジェクトです。 -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## スキーマ定義 - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript マッピング - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Arweaveサブグラフのクエリ - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## サブグラフの例 - -参考までにサブグラフの例を紹介します: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### サブグラフは Arweave やその他のチェーンにインデックスを付けることができますか? - -いいえ、サブグラフは 1 つのチェーン/ネットワークのデータソースのみをサポートします。 - -### 保存されたファイルをArweaveでインデックス化することはできますか? - -現在、The Graph は Arweave をブロックチェーン (ブロックとトランザクション) としてのみインデックス化しています。 - -### 自分のサブグラフにあるBundlrバンドルは特定できるのか? - -現在はサポートされていません。 - -### トランザクションを特定のアカウントにフィルターするにはどうすればよいですか? - -Source.ownerには、ユーザの公開鍵またはアカウントアドレスを指定することができます。 - -### 現在の暗号化フォーマットは? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/ja/subgraphs/cookbook/enums.mdx b/website/src/pages/ja/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 8df21d2960f9..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## その他のリソース - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ja/subgraphs/cookbook/grafting.mdx b/website/src/pages/ja/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 0be8b13c8dbd..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: グラフティングでコントラクトを取り替え、履歴を残す ---- - -このガイドでは、既存のサブグラフをグラフティングして新しいサブグラフを構築し、配備する方法を学びます。 - -## グラフティングとは? - -グラフティングは、既存のサブグラフからデータを再利用し、後のブロックからインデックスを作成します。これは、開発中にマッピングの単純なエラーを素早く乗り越えるため、または、既存のサブグラフが失敗した後に一時的に再び動作させるために有用です。また、ゼロからインデックスを作成するのに時間がかかる機能をサブグラフに追加する場合にも使用できます。 - -グラフト化されたサブグラフは、ベースとなるサブグラフのスキーマと同一ではなく、単に互換性のある GraphQL スキーマを使用することができます。また、それ自体は有効なサブグラフのスキーマでなければなりませんが、以下の方法でベースサブグラフのスキーマから逸脱することができます。 - -- エンティティタイプを追加または削除する -- エンティティタイプから属性を削除する -- 属性を追エンティティタイプに nullable加する -- null 化できない属性を null 化できる属性に変更する -- enums に値を追加する -- インターフェースの追加または削除 -- インターフェースがどのエンティティタイプに実装されるかを変更する - -詳しくは、こちらでご確認ください。 - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## ネットワークにアップグレードする際の移植に関する重要な注意事項 - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### 何でこれが大切ですか? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### ベストプラクティス - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -これらのガイドラインに従うことで、リスクを最小限に抑え、よりスムーズな移行プロセスを確保できます。 - -## 既存のサブグラフの構築 - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## サブグラフマニフェストの定義 - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## グラフティングマニフェストの定義 - -グラフティングは、元のサブグラフ・マニフェストに新しい2つの項目を追加する必要があります。 - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## ベースサブグラフの起動 - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. 終了後、サブグラフが正しくインデックスされていることを確認します。The Graph Playgroundで以下のコマンドを実行すると、サブグラフが正常にインデックスされます。 - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -このようなものが返ってきます: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -サブグラフが正しくインデックスされていることを確認したら、グラフティングで素早くサブグラフを更新することができます。 - -## グラフティングサブグラフの展開 - -グラフト置換されたsubgraph.yamlは、新しいコントラクトのアドレスを持つことになります。これは、ダンプを更新したり、コントラクトを再デプロイしたりしたときに起こりうることです。 - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. 終了後、サブグラフが正しくインデックスされていることを確認します。The Graph Playgroundで以下のコマンドを実行すると、サブグラフが正常にインデックスされます。 - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -以下のように返ってくるはずです: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## その他のリソース - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ja/subgraphs/cookbook/near.mdx b/website/src/pages/ja/subgraphs/cookbook/near.mdx deleted file mode 100644 index 6f4069566be2..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: NEAR でサブグラフを作成する ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## NEAR とは? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## NEAR サブグラフとは? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- ブロックハンドラ:新しいブロックごとに実行されます -- レシートハンドラ:指定されたアカウントでメッセージが実行されるたびに実行されます - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> レシートは、システム内で唯一実行可能なオブジェクトです。NEAR プラットフォームで「トランザクションの処理」といえば、最終的にはどこかの時点で「レシートの適用」を意味します。 - -## NEAR サブグラフの構築 - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> NEAR サブグラフの構築は、Ethereum のインデックスを作成するサブグラフの構築と非常によく似ています。 - -サブグラフの定義には 3 つの側面があります: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -サブグラフの開発には 2 つの重要なコマンドがあります: - -```bash -$ graph codegen # マニフェストで識別されたようにファイルから型を生成します -$ グラフ ビルド # AssemblyScript ファイルから Web アセンブリを生成し、/build フォルダにすべてのサブグラフ ファイルを準備します -``` - -### サブグラフマニフェストの定義 - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR データソースは 2 種類のハンドラーをサポートしています: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### スキーマ定義 - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript マッピング - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## NEAR サブグラフの展開 - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -ノードの構成は、サブグラフがどこにディプロイされるかによって異なります。 - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### ローカル グラフ ノード (デフォルト構成に基づく) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -デプロイされたサブグラフは、Graph Node によってインデックス化され、その進捗状況は、サブグラフ自体にクエリして確認できます: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### ローカル グラフ ノードを使用した NEAR のインデックス作成 - -NEAR のインデックスを作成するグラフノードの運用には、以下のような運用要件があります: - -- NEAR Indexer Framework と Firehose instrumentation -- NEAR Firehose コンポーネント -- Firehose エンドポイントが設定されたグラフノード - -上記のコンポーネントの運用については、近日中に詳しくご紹介します。 - -## NEAR サブグラフへのクエリ - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## サブグラフの例 - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### ベータ版はどのように機能しますか? - -NEAR サポートはベータ版です。統合の改善を続ける中で、API に変更が加えられる可能性があります。NEAR サブグラフの構築をサポートし、最新の開発状況をお知らせしますので、near@thegraph.comまでメールをお送りください。 - -### サブグラフは NEAR チェーンと EVM チェーンの両方にインデックスを付けることができますか? - -いいえ、サブグラフは 1 つのチェーン/ネットワークのデータソースのみをサポートします。 - -### サブグラフはより具体的なトリガーに反応できますか? - -現在、ブロックとレシートのトリガーのみがサポートされています。指定されたアカウントへのファンクションコールのトリガーを検討しています。また、NEAR がネイティブイベントをサポートするようになれば、イベントトリガーのサポートも検討しています。 - -### 領収書ハンドラーは、アカウントとそのサブアカウントに対してトリガーされますか? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### NEAR サブグラフは、マッピング中に NEAR アカウントへのビュー呼び出しを行うことができますか? - -これはサポートされていません。この機能がインデックス作成に必要かどうかを評価しています。 - -### NEAR サブグラフでデータ ソース テンプレートを使用できますか? - -これは現在サポートされていません。この機能がインデックス作成に必要かどうかを評価しています。 - -### Ethereum サブグラフは「保留中」バージョンと「現在」バージョンをサポートしていますが、NEAR サブグラフの「保留中」バージョンをデプロイするにはどうすればよいですか? - -「pending」は、NEAR サブグラフではまだサポートされていません。暫定的に、新しいバージョンを別の「named」サブグラフにデプロイし、それがチェーンヘッドと同期したときに、メインの「named」サブグラフに再デプロイすることができます。 - -### 私の質問に対する回答がありません。NEAR サブグラフの作成に関するヘルプはどこで入手できますか? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## 参考文献 - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ja/subgraphs/cookbook/polymarket.mdx b/website/src/pages/ja/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ja/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/ja/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index bac42648b0fc..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## 概要 - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ja/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/ja/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 7d4e4d6a6e6f..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: フォークを用いた迅速かつ容易なサブグラフのデバッグ ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## さて、それは何でしょうか? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## その方法は? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## コードを見てみましょう - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -通常の試すであろう修正方法: - -1. マッピングソースを変更して問題の解決を試す(解決されないことは分かっていても) -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. 同期を待つ -4. 再び問題が発生した場合は、1に戻る - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. マッピングのソースを変更し、問題を解決する -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. もし再度、壊れる場合1に戻る - -さて、ここで2つの疑問が生じます: - -1. フォークベースとは? -2. フォーキングは誰ですか? - -回答: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. フォーキングは簡単であり煩雑な手間はありません - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -そこで、以下の通りです: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ja/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/ja/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 74d66b27fcaa..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: 安全なサブグラフのコード生成 ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Subgraph Uncrashable と統合する理由 - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- また、このフレームワークには、エンティティ変数のグループに対して、カスタムだが安全なセッター関数を作成する方法が(設定ファイルを通じて)含まれています。この方法では、ユーザーが古いグラフ・エンティティをロード/使用することは不可能であり、また、関数が必要とする変数の保存や設定を忘れることも不可能です。 - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashableは、Graph CLI codegenコマンドでオプションのフラグとして実行することができます。 - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/ja/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/ja/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 6ef52284a5f5..000000000000 --- a/website/src/pages/ja/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### 例 - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### その他のリソース - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ja/subgraphs/guides/_meta.js b/website/src/pages/ja/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/ja/subgraphs/guides/arweave.mdx b/website/src/pages/ja/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/ja/subgraphs/guides/enums.mdx b/website/src/pages/ja/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ja/subgraphs/guides/grafting.mdx b/website/src/pages/ja/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ja/subgraphs/guides/near.mdx b/website/src/pages/ja/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ja/subgraphs/guides/polymarket.mdx b/website/src/pages/ja/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ja/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/ja/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ja/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/ja/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ja/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/ja/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ja/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/ja/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/ja/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ko/subgraphs/_meta-titles.json b/website/src/pages/ko/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/ko/subgraphs/_meta-titles.json +++ b/website/src/pages/ko/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/ko/subgraphs/_meta.js b/website/src/pages/ko/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/ko/subgraphs/_meta.js +++ b/website/src/pages/ko/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/ko/subgraphs/cookbook/_meta.js b/website/src/pages/ko/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/ko/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/ko/subgraphs/cookbook/polymarket.mdx b/website/src/pages/ko/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/ko/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ko/subgraphs/guides/_meta.js b/website/src/pages/ko/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/ko/subgraphs/guides/arweave.mdx b/website/src/pages/ko/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/ko/subgraphs/guides/enums.mdx b/website/src/pages/ko/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ko/subgraphs/guides/grafting.mdx b/website/src/pages/ko/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ko/subgraphs/guides/near.mdx b/website/src/pages/ko/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ko/subgraphs/guides/polymarket.mdx b/website/src/pages/ko/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ko/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/ko/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ko/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/ko/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ko/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/ko/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ko/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/ko/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/ko/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/mr/subgraphs/_meta-titles.json b/website/src/pages/mr/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/mr/subgraphs/_meta-titles.json +++ b/website/src/pages/mr/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/mr/subgraphs/_meta.js b/website/src/pages/mr/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/mr/subgraphs/_meta.js +++ b/website/src/pages/mr/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/mr/subgraphs/cookbook/_meta.js b/website/src/pages/mr/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/mr/subgraphs/cookbook/arweave.mdx b/website/src/pages/mr/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 2b43324539b9..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Arweave वर सबग्राफ तयार करणे ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -या मार्गदर्शकामध्ये, तुम्ही Arweave ब्लॉकचेन इंडेक्स करण्यासाठी सबग्राफ कसे तयार करावे आणि कसे तैनात करावे ते शिकाल. - -## Arweave काय आहे? - -Arweave प्रोटोकॉल विकसकांना कायमस्वरूपी डेटा संचयित करण्याची परवानगी देतो आणि Arweave आणि IPFS मधील मुख्य फरक आहे, जेथे IPFS मध्ये वैशिष्ट्याचा अभाव आहे; कायमस्वरूपी, आणि Arweave वर संचयित केलेल्या फायली बदलल्या किंवा हटवल्या जाऊ शकत नाहीत. - -अनेक वेगवेगळ्या प्रोग्रामिंग भाषांमध्ये प्रोटोकॉल समाकलित करण्यासाठी Arweave ने आधीच असंख्य लायब्ररी तयार केल्या आहेत. अधिक माहितीसाठी तुम्ही तपासू शकता: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## Arweave Subgraphs काय आहेत? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Arweave Subgraph तयार करणे - -Arweave Subgraphs तयार आणि तैनात करण्यात सक्षम होण्यासाठी, तुम्हाला दोन पॅकेजेसची आवश्यकता आहे: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## सबग्राफचे घटक - -सबग्राफचे तीन घटक आहेत: - -### 1. Manifest - `subgraph.yaml` - -स्वारस्य असलेल्या डेटा स्रोतांची व्याख्या करते आणि त्यांची प्रक्रिया कशी करावी. Arweave हा एक नवीन प्रकारचा डेटा स्रोत आहे. - -### 2. Schema - `schema.graphql` - -GraphQL वापरून तुमचा सबग्राफ इंडेक्स केल्यानंतर तुम्ही कोणता डेटा क्वेरी करू इच्छिता ते येथे तुम्ही परिभाषित करता. हे प्रत्यक्षात API च्या मॉडेलसारखेच आहे, जेथे मॉडेल विनंती मुख्य भागाची रचना परिभाषित करते. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -जेव्हा तुम्ही ऐकत असलेल्या डेटा स्रोतांशी कोणीतरी संवाद साधते तेव्हा डेटा कसा पुनर्प्राप्त आणि संग्रहित केला जावा हे हे तर्कशास्त्र आहे. डेटा अनुवादित केला जातो आणि तुम्ही सूचीबद्ध केलेल्या स्कीमावर आधारित संग्रहित केला जातो. - -सबग्राफ विकासादरम्यान दोन प्रमुख आज्ञा आहेत: - -``` -$ graph codegen # मॅनिफेस्टमध्ये ओळखल्या गेलेल्या स्कीमा फाइलमधून प्रकार व्युत्पन्न करते -$ graph build # असेंबलीस्क्रिप्ट फायलींमधून वेब असेंब्ली तयार करते आणि /बिल्ड फोल्डरमध्ये सर्व सबग्राफ फाइल्स तयार करते -``` - -## सबग्राफ मॅनिफेस्ट व्याख्या - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave डेटा स्रोत पर्यायी source.owner फील्ड सादर करतात, जी Arweave वॉलेटची सार्वजनिक की आहे - -Arweave डेटा स्रोत दोन प्रकारच्या हँडलरला समर्थन देतात: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> source.owner हा मालकाचा पत्ता किंवा त्यांची सार्वजनिक की असू शकतो. -> -> व्यवहार हे Arweave permaweb चे बिल्डिंग ब्लॉक्स आहेत आणि ते अंतिम वापरकर्त्यांनी तयार केलेल्या वस्तू आहेत. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## स्कीमा व्याख्या - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## असेंबलीस्क्रिप्ट मॅपिंग - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## प्रश्न करत आहे Arweave सबग्राफ - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## उदाहरणे सबग्राफ - -संदर्भासाठी येथे एक उदाहरण उपग्राफ आहे: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### सबग्राफ इंडेक्स Arweave आणि इतर साखळी करू शकता? - -नाही, सबग्राफ केवळ एका साखळी/नेटवर्कमधील डेटा स्रोतांना समर्थन देऊ शकतो. - -### मी Arweave वर संग्रहित फाइल्स अनुक्रमित करू शकतो? - -सध्या, ग्राफ फक्त ब्लॉकचेन (त्याचे ब्लॉक्स आणि व्यवहार) म्हणून Arweave अनुक्रमित करत आहे. - -### Currently, The Graph फक्त blockchain (त्याचे blocks आणि transactions) म्हणून Arweave अनुक्रमित करत आहे? - -हे सध्या समर्थित नाही. - -### मी विशिष्ट खात्यातील व्यवहार कसे फिल्टर करू शकतो? - -source.owner वापरकर्त्याची सार्वजनिक की किंवा खाते पत्ता असू शकतो. - -### सध्याचे एन्क्रिप्शन स्वरूप काय आहे? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/mr/subgraphs/cookbook/enums.mdx b/website/src/pages/mr/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 081add904f9a..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## अतिरिक्त संसाधने - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/mr/subgraphs/cookbook/grafting.mdx b/website/src/pages/mr/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 3ceb7d2c7901..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: करार बदला आणि त्याचा इतिहास ग्राफ्टिंगसह ठेवा ---- - -या मार्गदर्शकामध्ये, तुम्ही विद्यमान सबग्राफ्सचे ग्राफ्टिंग करून नवीन सबग्राफ कसे तयार करावे आणि कसे तैनात करावे ते शिकाल. - -## ग्राफ्टिंग म्हणजे काय? - -ग्राफ्टिंग विद्यमान सबग्राफमधील डेटा पुन्हा वापरते आणि नंतरच्या ब्लॉकमध्ये अनुक्रमित करणे सुरू करते. मॅपिंगमध्ये भूतकाळातील साध्या चुका लवकर मिळवण्यासाठी किंवा विद्यमान सबग्राफ अयशस्वी झाल्यानंतर तात्पुरते काम करण्यासाठी हे विकासादरम्यान उपयुक्त आहे. तसेच, स्क्रॅचपासून इंडेक्स होण्यास बराच वेळ घेणार्‍या सबग्राफमध्ये वैशिष्ट्य जोडताना ते वापरले जाऊ शकते. - -ग्राफ्टेड सबग्राफ GraphQL स्कीमा वापरू शकतो जो बेस सबग्राफपैकी एकाशी एकसारखा नसतो, परंतु त्याच्याशी फक्त सुसंगत असतो. ती स्वतःच्या अधिकारात वैध सबग्राफ स्कीमा असणे आवश्यक आहे, परंतु खालील प्रकारे बेस सबग्राफच्या स्कीमापासून विचलित होऊ शकते: - -- हे घटक प्रकार जोडते किंवा काढून टाकते -- हे घटक प्रकारातील गुणधर्म काढून टाकते -- हे अस्तित्व प्रकारांमध्ये रद्द करण्यायोग्य विशेषता जोडते -- हे नॉन-नलेबल अॅट्रिब्यूट्सना न्युलेबल अॅट्रिब्यूट्समध्ये बदलते -- हे enums मध्ये मूल्ये जोडते -- हे इंटरफेस जोडते किंवा काढून टाकते -- कोणत्या घटकासाठी इंटरफेस लागू केला जातो ते बदलते - -अधिक माहितीसाठी, तुम्ही तपासू शकता: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## विद्यमान सबग्राफ तयार करणे - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## सबग्राफ मॅनिफेस्ट व्याख्या - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Grafting मॅनिफेस्ट व्याख्या - -ग्राफ्टिंगसाठी मूळ सबग्राफ मॅनिफेस्टमध्ये दोन नवीन आयटम जोडणे आवश्यक आहे: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## बेस सबग्राफ तैनात करणे - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. एकदा पूर्ण झाल्यावर, सबग्राफ योग्यरित्या अनुक्रमित होत असल्याचे सत्यापित करा. जर तुम्ही ग्राफ प्लेग्राउंडमध्ये खालील आदेश चालवलात - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -हे असे काहीतरी परत करते: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -एकदा तुम्ही सबग्राफ व्यवस्थित इंडेक्स करत असल्याची पडताळणी केल्यानंतर, तुम्ही ग्राफ्टिंगसह सबग्राफ त्वरीत अपडेट करू शकता. - -## ग्राफ्टिंग सबग्राफ तैनात करणे - -कलम बदली subgraph.yaml मध्ये नवीन करार पत्ता असेल. जेव्हा तुम्ही तुमचा dapp अपडेट करता, करार पुन्हा लागू करता तेव्हा असे होऊ शकते. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. एकदा पूर्ण झाल्यावर, सबग्राफ योग्यरित्या अनुक्रमित होत असल्याचे सत्यापित करा. जर तुम्ही ग्राफ प्लेग्राउंडमध्ये खालील आदेश चालवलात - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It should return the following: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## अतिरिक्त संसाधने - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/mr/subgraphs/cookbook/near.mdx b/website/src/pages/mr/subgraphs/cookbook/near.mdx deleted file mode 100644 index 6e790fdcb0cf..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: NEAR वर सबग्राफ तयार करणे ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## जवळ म्हणजे काय? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## NEAR subgraphs म्हणजे काय? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- ब्लॉक हँडलर: हे प्रत्येक नवीन ब्लॉकवर चालवले जातात -- पावती हँडलर्स: निर्दिष्ट खात्यावर संदेश कार्यान्वित झाल्यावर प्रत्येक वेळी चालवा - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> प्रणालीमध्ये पावती ही एकमेव क्रिया करण्यायोग्य वस्तू आहे. जेव्हा आम्ही जवळच्या प्लॅटफॉर्मवर "व्यवहारावर प्रक्रिया करणे" बद्दल बोलतो, तेव्हा याचा अर्थ शेवटी "पावत्या लागू करणे" असा होतो. - -## एक NEAR सबग्राफतयार करणे - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> NEAR सबग्राफ तयार करणे, याची प्रक्रिया इथेरियमवरील सबग्राफ तयार करण्याशी खूप सामान्यतेने सादर करते. - -सबग्राफ व्याख्येचे तीन पैलू आहेत: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -सबग्राफ विकासादरम्यान दोन प्रमुख आज्ञा आहेत: - -```bash -$ graph codegen # मॅनिफेस्टमध्ये ओळखल्या गेलेल्या स्कीमा फाइलमधून प्रकार व्युत्पन्न करते -$ graph build # असेंबलीस्क्रिप्ट फायलींमधून वेब असेंब्ली तयार करते आणि /बिल्ड फोल्डरमध्ये सर्व सबग्राफ फाइल्स तयार करते -``` - -### सबग्राफ मॅनिफेस्ट व्याख्या - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -जवळील डेटा स्रोत दोन प्रकारच्या हँडलरला समर्थन देतात: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### स्कीमा व्याख्या - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### असेंबलीस्क्रिप्ट मॅपिंग - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## NEAR सबग्राफ डिप्लॉय करण्यासाठी - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -नोड कॉन्फिगरेशन सबग्राफ कोठे तैनात केले जात आहे यावर अवलंबून असेल. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### स्थानिक आलेख नोड (डीफॉल्ट कॉन्फिगरेशनवर आधारित) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -एकदा तुमचा सबग्राफ तैनात केला गेला की, तो ग्राफ नोडद्वारे अनुक्रमित केला जाईल. तुम्ही सबग्राफवरच क्वेरी करून त्याची प्रगती तपासू शकता: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### स्थानिक ग्राफ नोडशी NEAR चे सूचीकरण करणे - -NEAR ची अनुक्रमणिका देणारा आलेख नोड चालवण्यासाठी खालील ऑपरेशनल आवश्यकता आहेत: - -- फायरहोस इंस्ट्रुमेंटेशनसह इंडेक्सर फ्रेमवर्क जवळ -- NEAR फायरहोज घटकाज(वळ) -- फायरहोस एंडपॉइंटसह आलेख नोड कॉन्फिगर केले आहे - -वरील घटक चालवण्याबाबत आम्ही लवकरच अधिक माहिती देऊ. - -## NEAR सबग्राफची क्वेरी करणे - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## उदाहरणे सबग्राफ - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### बीटा कसे कार्य करते? - -NEAR सपोर्ट बीटामध्ये आहे, याचा अर्थ असा की API मध्ये बदल होऊ शकतात कारण आम्ही एकत्रीकरण सुधारण्यासाठी काम करत आहोत. कृपया near@thegraph.com वर ईमेल करा जेणेकरुन आम्‍ही तुम्‍हाला जवळचे सबग्राफ तयार करण्‍यात मदत करू शकू आणि तुम्‍हाला नवीनतम घडामोडींबद्दल अद्ययावत ठेवू शकू! - -### सबग्राफ इंडेक्स NEAR आणि EVM दोन्ही चेन करू शकतो का? - -नाही, सबग्राफ केवळ एका साखळी/नेटवर्कमधील डेटा स्रोतांना समर्थन देऊ शकतो. - -### सबग्राफ अधिक विशिष्ट ट्रिगरवर प्रतिक्रिया देऊ शकतात? - -सध्या, फक्त ब्लॉक आणि पावती ट्रिगर समर्थित आहेत. आम्ही एका निर्दिष्ट खात्यावर फंक्शन कॉलसाठी ट्रिगर तपासत आहोत. आम्‍हाला इव्‍हेंट ट्रिगरला सपोर्ट करण्‍यात देखील रस आहे, एकदा NEAR ला नेटिव्ह इव्‍हेंट सपोर्ट असेल. - -### पावती हँडलर खाती आणि त्यांच्या उप-खात्यांसाठी ट्रिगर करतील का? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### मॅपिंग दरम्यान NEAR subgraphs NEAR खात्यांना व्ह्यू कॉल करू शकतात? - -हे समर्थित नाही. अनुक्रमणिकेसाठी ही कार्यक्षमता आवश्यक आहे का याचे आम्ही मूल्यमापन करत आहोत. - -### NEARのサブグラフでデータソーステンプレートを使用できますか? - -हे सध्या समर्थित नाही. अनुक्रमणिकेसाठी ही कार्यक्षमता आवश्यक आहे का याचे आम्ही मूल्यमापन करत आहोत. - -### イーサリアムのサブグラフでは、「pending」および「current」のバージョンがサポートされていますが、NEARのサブグラフの「pending」バージョンをどのようにデプロイできるでしょうか? - -NEARサブグラフの「保留中」機能はまだサポートされていません。その間、異なる「名前付き」サブグラフに新しいバージョンをデプロイし、それがチェーンヘッドと同期された後、主要な「名前付き」サブグラフに再デプロイすることができます。この場合、同じ基礎となるデプロイメントIDを使用するため、メインのサブグラフは即座に同期されます. - -### माझा प्रश्न उत्तर दिला नाही, NEAR सबग्राफ तयार करण्यासाठी अधिक मदत कुठे मिळेल? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## संदर्भ - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/mr/subgraphs/cookbook/polymarket.mdx b/website/src/pages/mr/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/mr/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/mr/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index d5ff1b146dfd..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## सविश्लेषण - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/mr/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/mr/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 3c7f2ec051e3..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: फॉर्क्स वापरून जलद आणि सुलभ सबग्राफ डीबगिंग ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## ठीक आहे, ते काय आहे? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## काय?! कसे? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## कृपया, मला काही कोड दाखवा! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -निराकरण करण्याचा प्रयत्न करण्याचा नेहमीचा मार्ग आहे: - -1. मॅपिंग स्त्रोतामध्ये बदल करा, जो तुम्हाला विश्वास आहे की समस्या सोडवेल (जेव्हा मला माहित आहे की ते होणार नाही). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. ते समक्रमित होण्याची प्रतीक्षा करा. -4. तो पुन्हा खंडित झाल्यास 1 वर परत जा, अन्यथा: हुर्रे! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. मॅपिंग स्त्रोतामध्ये बदल करा, जो तुम्हाला विश्वास आहे की समस्या सोडवेल. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. तो पुन्हा खंडित झाल्यास, 1 वर परत जा, अन्यथा: हुर्रे! - -आता, तुमच्याकडे 2 प्रश्न असू शकतात: - -1. fork-base काय??? -2. फोर्किंग होईल कोणासोबत?! - -आणि मी उत्तर देतो: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. काटा काढणे सोपे आहे, घाम गाळण्याची गरज नाही: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -तर, मी काय करतो ते येथे आहे: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/mr/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/mr/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 9a7e3d9f008e..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: सुरक्षित सबग्राफ कोड जनरेटर ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Subgraph Uncrashable सह समाकलित का? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- फ्रेमवर्कमध्ये एंटिटी व्हेरिएबल्सच्या गटांसाठी सानुकूल, परंतु सुरक्षित, सेटर फंक्शन्स तयार करण्याचा मार्ग (कॉन्फिग फाइलद्वारे) देखील समाविष्ट आहे. अशा प्रकारे वापरकर्त्याला जुना आलेख घटक लोड करणे/वापरणे अशक्य आहे आणि फंक्शनसाठी आवश्यक असलेले व्हेरिएबल सेव्ह करणे किंवा सेट करणे विसरणे देखील अशक्य आहे. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -ग्राफ CLI codegen कमांड वापरून Subgraph Uncrashable हा पर्यायी ध्वज म्हणून चालवला जाऊ शकतो. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/mr/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/mr/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index d31f9d8864b5..000000000000 --- a/website/src/pages/mr/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### उदाहरण - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### अतिरिक्त संसाधने - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/mr/subgraphs/guides/_meta.js b/website/src/pages/mr/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/mr/subgraphs/guides/arweave.mdx b/website/src/pages/mr/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/mr/subgraphs/guides/enums.mdx b/website/src/pages/mr/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/mr/subgraphs/guides/grafting.mdx b/website/src/pages/mr/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/mr/subgraphs/guides/near.mdx b/website/src/pages/mr/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/mr/subgraphs/guides/polymarket.mdx b/website/src/pages/mr/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/mr/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/mr/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/mr/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/mr/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/mr/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/mr/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/mr/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/mr/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/mr/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/nl/subgraphs/_meta-titles.json b/website/src/pages/nl/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/nl/subgraphs/_meta-titles.json +++ b/website/src/pages/nl/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/nl/subgraphs/_meta.js b/website/src/pages/nl/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/nl/subgraphs/_meta.js +++ b/website/src/pages/nl/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/nl/subgraphs/cookbook/_meta.js b/website/src/pages/nl/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/nl/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/nl/subgraphs/cookbook/arweave.mdx b/website/src/pages/nl/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 1ff7fdd460fc..000000000000 --- a/website/src/pages/nl/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Bouwen van Subgraphs op Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -In deze gids, zul je leren hoe je Subgraphs bouwt en implementeer om de Arweave blockchain te indexeren. - -## Wat is Arweave? - -Het Arweave protocol stelt ontwikkelaars in staat om gegevens permanent op te slaan, dat is het voornaamste verschil tussen Arweave en IPFS, waar IPFS deze functie mist, en bestanden die op Arweave zijn opgeslagen, kunnen niet worden gewijzigd of verwijderd. - -Arweave heeft al talloze bibliotheken gebouwd voor het integreren van het protocol in verschillende programmeertalen. Voor meer informatie kun je kijken op: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## Wat zijn Arweave Subgraphs? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Bouwen van een Arweave Subgraph - -Voor het kunnen bouwen en implementeren van Arweave Subgraphs, heb je twee paketten nodig: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Subgraph's componenten - -Er zijn drie componenten van een subgraph: - -### 1. Manifest - `subgraph.yaml` - -Definieert gegevensbronnen die van belang zijn en hoe deze verwerkt moeten worden. Arweave is een nieuw type gegevensbron. - -### 2. Schema - `schema.graphql` - -Hier definieer je welke gegevens je wilt kunnen opvragen na het indexeren van je subgraph door het gebruik van GraphQL. Dit lijkt eigenlijk op een model voor een API, waarbij het model de structuur van een verzoek definieert. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -Dit is de logica die definieert hoe data zou moeten worden opgevraagd en opgeslagen wanneer iemand met de gegevens communiceert waarnaar jij aan het luisteren bent. De gegevens worden vertaald en is opgeslagen gebaseerd op het schema die je genoteerd hebt. - -Tijdens subgraph ontwikkeling zijn er twee belangrijke commando's: - -``` -$ graph codegen # genereert types van het schema bestand die geïdentificeerd is in het manifest -$ graph build # genereert Web Assembly vanuit de AssemblyScript-bestanden, en bereidt alle Subgraph-bestanden voor in een /build map -``` - -## Subgraph Manifest Definition - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersie: 0.0.5 -omschrijving: Arweave Blocks Indexing -schema: - bestand: ./schema.graphql # link to the schema file -dataSources: - - type: arweave - naam: arweave-blocks - netwerk: arweave-mainnet # The Graph only supports Arweave Mainnet - bron: - eigenaar: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - toewijzing: - apiVersie: 0.0.5 - taal: wasm/assemblyscript - bestand: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entiteit: - - Block - - Transaction - blockAfhandelaar: - - afhandelaar: handleBlock # the function name in the mapping file - transactieAfhandelaar: - - afhandelaar: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave data bronnen introduceert een optionele bron.eigenaar veld, dat de openbare sleutel is van een Arweave wallet - -Arweave data bronnen ondersteunt twee typen verwerkers: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> The source.owner can be the owner's address, or their Public Key. -> -> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Schema Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Querying an Arweave Subgraph - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Example Subgraphs - -Here is an example subgraph for reference: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Can a subgraph index Arweave and other chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can I index the stored files on Arweave? - -Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). - -### Can I identify Bundlr bundles in my subgraph? - -This is not currently supported. - -### How can I filter transactions to a specific account? - -The source.owner can be the user's public key or account address. - -### What is the current encryption format? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/nl/subgraphs/cookbook/near.mdx b/website/src/pages/nl/subgraphs/cookbook/near.mdx deleted file mode 100644 index 75f966e7a597..000000000000 --- a/website/src/pages/nl/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Building Subgraphs on NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## What is NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## What are NEAR subgraphs? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Block handlers: these are run on every new block -- Receipt handlers: run every time a message is executed at a specified account - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. - -## Building a NEAR Subgraph - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. - -There are three aspects of subgraph definition: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -Tijdens subgraph ontwikkeling zijn er twee belangrijke commando's: - -```bash -$ graph codegen # genereert types van het schema bestand die geïdentificeerd is in het manifest -$ graph build # genereert Web Assembly vanuit de AssemblyScript-bestanden, en bereidt alle Subgraph-bestanden voor in een /build map -``` - -### Subgraph Manifest Definition - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR data sources support two types of handlers: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Schema Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Deploying a NEAR Subgraph - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -The node configuration will depend on where the subgraph is being deployed. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Local Graph Node (based on default configuration) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexing NEAR with a Local Graph Node - -Running a Graph Node that indexes NEAR has the following operational requirements: - -- NEAR Indexer Framework with Firehose instrumentation -- NEAR Firehose Component(s) -- Graph Node with Firehose endpoint configured - -We will provide more information on running the above components soon. - -## Querying a NEAR Subgraph - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Example Subgraphs - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### How does the beta work? - -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! - -### Can a subgraph index both NEAR and EVM chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can subgraphs react to more specific triggers? - -Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. - -### Will receipt handlers trigger for accounts and their sub-accounts? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? - -This is not supported. We are evaluating whether this functionality is required for indexing. - -### Can I use data source templates in my NEAR subgraph? - -This is not currently supported. We are evaluating whether this functionality is required for indexing. - -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? - -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. - -### My question hasn't been answered, where can I get more help building NEAR subgraphs? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## References - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/nl/subgraphs/cookbook/polymarket.mdx b/website/src/pages/nl/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/nl/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/nl/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/nl/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 0cc91a0fa2c3..000000000000 --- a/website/src/pages/nl/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Safe Subgraph Code Generator ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Why integrate with Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/nl/subgraphs/guides/_meta.js b/website/src/pages/nl/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/nl/subgraphs/guides/arweave.mdx b/website/src/pages/nl/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/nl/subgraphs/guides/enums.mdx b/website/src/pages/nl/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/nl/subgraphs/guides/grafting.mdx b/website/src/pages/nl/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/nl/subgraphs/guides/near.mdx b/website/src/pages/nl/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/nl/subgraphs/guides/polymarket.mdx b/website/src/pages/nl/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/nl/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/nl/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/nl/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/nl/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/nl/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/nl/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/nl/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/nl/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/nl/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pl/subgraphs/_meta-titles.json b/website/src/pages/pl/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/pl/subgraphs/_meta-titles.json +++ b/website/src/pages/pl/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/pl/subgraphs/_meta.js b/website/src/pages/pl/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/pl/subgraphs/_meta.js +++ b/website/src/pages/pl/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/pl/subgraphs/cookbook/_meta.js b/website/src/pages/pl/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/pl/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/pl/subgraphs/cookbook/polymarket.mdx b/website/src/pages/pl/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/pl/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pl/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/pl/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 6610f19da66d..000000000000 --- a/website/src/pages/pl/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Quick and Easy Subgraph Debugging Using Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## Ok, what is it? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## What?! How? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## Please, show me some code! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -The usual way to attempt a fix is: - -1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Wait for it to sync-up. -4. If it breaks again go back to 1, otherwise: Hooray! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. If it breaks again, go back to 1, otherwise: Hooray! - -Now, you may have 2 questions: - -1. fork-base what??? -2. Forking who?! - -And I answer: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Forking is easy, no need to sweat: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -So, here is what I do: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/pl/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/pl/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 0cc91a0fa2c3..000000000000 --- a/website/src/pages/pl/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Safe Subgraph Code Generator ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Why integrate with Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/pl/subgraphs/guides/_meta.js b/website/src/pages/pl/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/pl/subgraphs/guides/arweave.mdx b/website/src/pages/pl/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/pl/subgraphs/guides/enums.mdx b/website/src/pages/pl/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/pl/subgraphs/guides/grafting.mdx b/website/src/pages/pl/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/pl/subgraphs/guides/near.mdx b/website/src/pages/pl/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/pl/subgraphs/guides/polymarket.mdx b/website/src/pages/pl/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pl/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/pl/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/pl/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/pl/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/pl/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/pl/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/pl/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/pl/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/pl/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pt/subgraphs/_meta-titles.json b/website/src/pages/pt/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/pt/subgraphs/_meta-titles.json +++ b/website/src/pages/pt/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/pt/subgraphs/_meta.js b/website/src/pages/pt/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/pt/subgraphs/_meta.js +++ b/website/src/pages/pt/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/pt/subgraphs/cookbook/_meta.js b/website/src/pages/pt/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/pt/subgraphs/cookbook/arweave.mdx b/website/src/pages/pt/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index a84800d73d48..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Construindo Subgraphs no Arweave ---- - -> O apoio ao Arweave no Graph Node, e no Subgraph Studio, está em beta: por favor nos contacte no [Discord](https://discord.gg/graphprotocol) se tiver dúvidas sobre como construir subgraphs no Arweave! - -Neste guia, você aprenderá como construir e lançar Subgraphs para indexar a blockchain Arweave. - -## O que é o Arweave? - -O protocolo Arweave permite que programadores armazenem dados permanentemente. Esta é a grande diferença entre o Arweave e o IPFS, considerando que o IPFS não tem esta característica; a permanência, e os arquivos armazenados no Arweave, não podem ser mudados ou apagados. - -O Arweave já construiu várias bibliotecas para integrar o protocolo num número de línguas de programação diferentes. Para mais informações, pode-se conferir: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Recursos do Arweave](https://www.arweave.org/build) - -## O que são Subgraphs no Arweave? - -The Graph permite a construção de APIs abertas e personalizadas chamadas "Subgraphs", que servem para contar aos indexadores (operadores de servidor) quais dados devem ser indexados em uma blockchain e guardados nos seus servidores para serem consultados a qualquer hora em queries pelo [GraphQL](https://graphql.org/). - -O [Graph Node](https://github.com/graphprotocol/graph-node) é atualmente capaz de indexar dados no protocolo Arweave. A integração atual indexa apenas o Arweave como uma blockchain (blocos e transações), mas no momento, não indexa os arquivos armazenados. - -## Construindo um Subgraph no Arweave - -Para construir e lançar Subgraphs no Arweave, são necessários dois pacotes: - -1. `@graphprotocol/graph-cli` acima da versão 0.30.2 — Esta é uma ferramenta de linha de comandos para a construção e implantação de subgraphs. [Clique aqui](https://www.npmjs.com/package/@graphprotocol/graph-cli) para baixá-la usando o `npm`. -2. `@graphprotocol/graph-ts` acima da versão 0.27.0 — Esta é uma ferramenta de linha de comandos para a construção e implantação de subgraphs. [Clique aqui](https://www.npmjs.com/package/@graphprotocol/graph-ts) para baixá-la usando o `npm`. - -## Os componentes de um subgraph - -Um subgraph tem três componentes: - -### 1. Manifest - `subgraph.yaml` - -Define as fontes de dados de interesse, e como elas devem ser processadas. O Arweave é uma nova categoria de fontes de dados. - -### 2. Schema - `schema.graphql` - -Aqui é possível definir quais dados queres consultar após indexar o seu subgraph utilizando o GraphQL. Isto é como um modelo para uma API, onde o modelo define a estrutura de um órgão de requisito. - -Os requisitos para subgraphs do Arweave estão cobertos pela [documentação](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. Mapeamentos de AssemblyScript - `mapping.ts` - -Esta é a lógica que determina como os dados devem ser retirados e armazenados quando alguém interage com as fontes de dados que estás a escutar. Os dados são traduzidos e armazenados baseados no schema que listaste. - -Durante o desenvolvimento de um subgraph, existem dois comandos importantes: - -``` -$ graph codegen # gera tipos do arquivo de schema identificado no manifest -$ graph build # gera Web Assembly dos arquivos AssemblyScript, e prepara todos os arquivos do subgraph em uma pasta /build -``` - -## Definição de Manifest de Subgraph - -O manifest do subgraph `subgraph.yaml` identifica as fontes de dados para o subgraph, os gatilhos de interesse, e as funções que devem ser executadas em resposta a tais gatilhos. Veja abaixo um exemplo de um manifest de subgraph, para um subgraph no Arweave: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link ao arquivo schema -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph apoia apenas a Mainnet do Arweave - source: - owner: 'ID-OF-AN-OWNER' # A chave pública de uma carteira no Arweave - startBlock: 0 # coloque isto como 0 para começar a indexar da gênese da chain - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link ao arquivo com os mapeamentos no Assemblyscript - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # o nome da função no arquivo de mapeamento - transactionHandlers: - - handler: handleTx # o nome da função no arquivo de mapeamento -``` - -- Subgraphs no Arweave introduzem uma nova categoria de fonte de dados (`arweave`) -- A rede deve corresponder a uma rede no Graph Node que a hospeda. No Subgraph Studio, a mainnet do Arweave é `arweave-mainnet` -- Fontes de dados no Arweave introduzem um campo source.owner opcional, a chave pública de uma carteira no Arweave - -Fontes de dados no Arweave apoiam duas categorias de handlers: - -- `blockHandlers` — Executar em cada bloco novo no Arweave. Nenhum `source.owner` necessário. -- `transactionHandlers` — Executar em todas as transações cujo dono é o source.owner da fonte de dados. Atualmente, é necessário ter um dono para o transactionHandlers; caso um utilizador queira processar todas as transações, ele deve providenciar "" como o `source.owner` - -> O source.owner pode ser o endereço do dono, ou sua Chave Pública. -> -> Transações são os blocos de construção da permaweb do Arweave, além de serem objetos criados para utilizadores finais. -> -> Nota: No momento, não há apoio para transações no [Irys (antigo Bundlr)](https://irys.xyz/). - -## Definição de Schema - -A definição de Schema descreve a estrutura do banco de dados resultado do subgraph, e os relacionamentos entre entidades. Isto é agnóstico da fonte de dados original. Para mais detalhes na definição de schema de subgraph, [clique aqui](/developing/creating-a-subgraph/#the-graphql-schema). - -## Mapeamentos em AssemblyScript - -Os handlers para processamento de eventos estão escritos em [AssemblyScript](https://www.assemblyscript.org/). - -A indexação do Arweave introduz tipos de dados específicos para esse ecossistema à [API do AssemblyScript](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Handlers de bloco recebem um `Block`, enquanto transações recebem um `Transaction`. - -Escrever os mapeamentos de um Subgraph no Arweave é parecido com a escrita dos mapeamentos de um Subgraph no Ethereum. Para mais informações, clique [aqui](/developing/creating-a-subgraph/#writing-mappings). - -## Como lançar um Subgraph no Arweave ao Subgraph Studio - -Após criar o seu Subgraph no painel de controlo do Subgraph Studio, este pode ser implantado com o comando `graph deploy`. - -```bash -graph deploy --access-token -``` - -## Consultando um Subgraph no Arweave - -O ponto final do GraphQL para subgraphs no Arweave é determinado pela definição do schema, com a interface existente da API. Visite a [documentação da API da GraphQL](/subgraphs/querying/graphql-api/) para mais informações. - -## Exemplos de Subgraphs - -Aqui está um exemplo de subgraph para referência: - -- [Exemplo de subgraph para o Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Um subgraph pode indexar o Arweave e outras chains? - -Não, um subgraph só pode apoiar fontes de dados de apenas uma chain/rede. - -### Posso indexar os arquivos armazenados no Arweave? - -Atualmente, The Graph apenas indexa o Arweave como uma blockchain (seus blocos e transações). - -### Posso identificar pacotes do Bundlr em meu subgraph? - -Isto não é apoiado no momento. - -### Como posso filtrar transações para uma conta específica? - -O source.owner pode ser a chave pública ou o endereço da conta do utilizador. - -### Qual é o formato atual de encriptação? - -Os dados são geralmente passados aos mapeamentos como Bytes, que se armazenados diretamente, são retornados ao subgraph em um formato `hex` (por ex. hashes de transações e blocos). Você pode querer convertê-lo a um formato seguro para `base64` ou `base64 URL` em seus mapeamentos, para combinar com o que é exibido em exploradores de blocos, como o [Arweave Explorer](https://viewblock.io/arweave/). - -A seguinte função de helper `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` pode ser usada, e será adicionada ao `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/pt/subgraphs/cookbook/enums.mdx b/website/src/pages/pt/subgraphs/cookbook/enums.mdx deleted file mode 100644 index d76ea4c23c4b..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize Marketplaces de NFT com Enums ---- - -Use Enums para deixar o seu código mais limpo e menos vulnerável a erros. Veja um exemplo do uso deste em marketplaces de NFT. - -## O que são Enums? - -Enums, ou tipos de enumeração, são um tipo de dados específico que permite definir um conjunto de valores específicos permitidos. - -### Exemplo de Enums no seu Schema - -Se estiver a construir um subgraph para rastrear o histórico de posse de tokens em um marketplace, cada token pode passar por posses diferentes, como `OriginalOwner`, `SecondOwner`, e `ThirdOwner`. Ao usar enums, é possível definir essas posses específicas, assim garantindo que só são nomeados valores predefinidos. - -É possível definir enums no seu schema; assim definidos, a representação de string dos valores de enum podem ser usados para configurar um campo de enum numa entidade. - -Com base no exemplo acima, uma definição de enum no seu schema pode ficar assim: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -Ou seja, quando usar o tipo `TokenStatus` no seu schema, a expectativa é de que seja exatamente um dos valores predefinidos: `OriginalOwner`, `SecondOwner`, ou `ThirdOwner`, assim garantindo a consistência e validez. - -Para saber mais sobre enums, veja [Como Criar um Subgraph](/developing/creating-a-subgraph/#enums) e a [documentação da GraphQL](https://graphql.org/learn/schema/#enumeration-types). - -## Vantagens de Usar Enums - -- **Clareza**: Enums dão nomes significativos a valores, facilitando a navegação de dados. -- **Validação**: Enums aplicam definições rígidas de valor, assim evitando entradas inválidas de dados. -- **Manutenibilidade:** Enums permitem mudar ou adicionar novas categorias de maneira concentrada. - -### Sem Enums - -Se escolher definir o tipo como um string em vez de usar um Enum, seu código poderá ficar assim: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Proprietário do token - tokenStatus: String! # Campo de string para rastrear o estado do token - timestamp: BigInt! -} -``` - -Neste schema, `TokenStatus` é um string simples sem valores permitidos específicos. - -#### Por que isto é um problema? - -- Não há restrições sobre valores `TokenStatus`, então qualquer string pode ser nomeado por acidente. Assim, fica difícil garantir que só estados válidos — como `OriginalOwner`, `SecondOwner`, ou `ThirdOwner` — serão configurados. -- É fácil fazer erros de digitação, como `Orgnalowner` em vez de `OriginalOwner`, o que faria os dados, e queries em potencial, não confiáveis. - -### Com Enums - -Em vez de nomear strings livres, é possível definir um enum para `TokenStatus` com valores específicos: `OriginalOwner`, `SecondOwner`, ou `ThirdOwner`. Usar um enum garante o uso de valores permitidos, e mais nenhum. - -Enums provém segurança de dados, minimizam os riscos de erros de digitação, e garantem resultados consistentes e confiáveis. - -## Como Definir Enums para Marketplaces de NFT - -> Nota: o guia a seguir usa o contrato inteligente de NFTs CryptoCoven. - -Para definir enums para os vários marketplaces com apoio a troca de NFTs, use o seguinte no seu schema de subgraph: - -```gql -# Enum para Marketplaces com que o contrato CryptoCoven interagiu(provavelmente Troca/Mint) -enum Marketplace { - OpenSeaV1 # Representa o comércio de um NFT CryptoCoven no marketplace - OpenSeaV2 # Representa o comércio de um NFT CryptoCoven no marketplace OpenSeaV2 - SeaPort # Representa o comércio de um NFT CryptoCoven no marketplace SeaPort - LooksRare # Representa o comércio de um NFT CryptoCoven no marketplace LookRare - # ...e outros marketplaces -} -``` - -## Como Usar Enums para Marketplaces de NFT - -Quando definidos, enums podem ser usados no seu subgraph para categorizar transações ou eventos. - -Por exemplo: ao registrar vendas de NFT, é possível usar o enum para especificar o marketplace envolvido na ação. - -### Como Implementar uma Função para Marketplaces de NFT - -Veja como implementar uma função para resgatar o nome de um marketplace do enum, como string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Usando comandos if-else para mapear o valor do enum para um string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // Se o marketplace for OpenSea, retornar sua representação de string - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // Se o marketplace for SeaPort, retornar sua representação de string - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // Se o marketplace for LooksRare, retornar sua representação de string - // ... e outros marketplaces - } -} -``` - -## Melhores Práticas para o Uso de Enums - -- **Nomes Consistentes**: Deixe o seu código mais legível; use nomes mais claros e descritivos para valores de enum. -- **Gestão Centralizada:** Mantenha enums num único arquivo para ficar mais consistente. Assim, os enums ficam mais fáceis de atualizar, garantindo uma fonte única e verdadeira de dados. -- **Documentação:** Adicione comentários a enums para esclarecer o seu propósito e uso. - -## Como Usar Enums em Queries - -Enums em queries ajudam a melhorar a qualidade de dados e deixam os seus resultados mais fáceis de interpretar. Eles funcionam como filtros e elementos de resposta, assim garantindo a consistência e reduzindo erros em valores de marketplace. - -**Detalhes** - -- **Filtros com Enums:** Enums fornecem filtros claros, permitindo a inclusão ou exclusão clara de marketplaces específicos. -- **Enums em Respostas:** Enums garantem que só marketplaces reconhecidos sejam retornados, trazendo resultados consistentes e precisos. - -### Exemplos de Query - -#### Query 1: Conta com Mais Interações de Marketplace em NFT - -Este query faz o seguinte: - -- Encontra a conta com mais interações únicas com marketplaces de NFT, ótimo para analisar atividade entre marketplaces. -- O campo de marketplaces usa o enum de marketplace, garantindo valores consistentes e validados na resposta. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # Este campo retorna o valor de enum representando o marketplace - } - } -} -``` - -#### Respostas - -Esta resposta fornece detalhes de conta e uma lista de interações singulares de marketplace com valores de enum, para mais clareza: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Marketplace mais ativo para transações do CryptoCoven - -Este query faz o seguinte: - -- Identifica o marketplace com maior volume de transações do CryptoCoven. -- Usa o enum de marketplace para garantir que só tipos válidos de marketplace apareçam na resposta, deixando os seus dados mais confiáveis e consistentes. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Resultado 2 - -A resposta esperada inclui o marketplace e a contagem correspondente de transações, usando o enum para indicar o tipo de marketplace: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Interações de Marketplace com Altos Números de Transação - -Este query faz o seguinte: - -- Resgata os quatro marketplaces com maior número de transações acima de 100, excluindo marketplaces "desconhecidos". -- Usa enums como filtros para garantir que só tipos válidos de marketplace sejam incluídos, deixando a resposta mais precisa. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Resultado 3 - -O retorno esperado inclui os marketplaces que cumprem os critérios, cada um representado por um valor enum: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Outros Recursos - -Para mais informações, veja o [repositório](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums) deste guia. diff --git a/website/src/pages/pt/subgraphs/cookbook/grafting.mdx b/website/src/pages/pt/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index cbfc42ddc895..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Como Substituir um Contrato e Manter a sua História com Enxertos ---- - -Neste guia, aprenda como construir e lançar novos subgraphs com o enxerto de subgraphs existentes. - -## O que é Enxerto? - -O processo de enxerto reutiliza os dados de um subgraph existente e o indexa em um bloco seguinte. Isto é útil durante o desenvolvimento para rapidamente superar erros simples nos mapeamentos, ou fazer um subgraph existente funcionar temporariamente após ele ter falhado. Ele também pode ser usado ao adicionar uma característica a um subgraph que demora para ser indexado do zero. - -O subgraph enxertado pode usar um schema GraphQL que não é idêntico ao schema do subgraph base, mas é apenas compatível com ele. Ele deve ser um schema válido no seu próprio mérito, mas pode desviar do schema do subgraph base nas seguintes maneiras: - -- Ele adiciona ou remove tipos de entidade -- Ele retira atributos de tipos de entidade -- Ele adiciona atributos anuláveis a tipos de entidade -- Ele transforma atributos não anuláveis em atributos anuláveis -- Ele adiciona valores a enums -- Ele adiciona ou remove interfaces -- Ele muda os tipos de entidades para qual implementar uma interface - -Para mais informações, confira: - -- [Enxertos](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -Neste tutorial, cobriremos um caso de uso básico. Substituiremos um contrato existente com um contrato idêntico (com um novo endereço, mas o mesmo código). Depois, enxertaremos o subgraph existente ao subgraph "base" que rastreará o novo contrato. - -## Notas Importantes sobre Enxertos ao Migrar Para a Graph Network - -> **Cuidado**: Não é recomendado usar enxertos para subgraphs editados na The Graph Network - -### Qual a Importância Disto? - -Isto é um recurso poderoso que permite que os programadores "enxertem" um subgraph em outro, o que, efetivamente, transfere dados históricos do subgraph existente até uma versão nova. Não é possível enxertar um subgraph da Graph Network de volta ao Subgraph Studio. - -### Boas práticas - -**Migração Inicial**: Ao implantar o seu subgraph pela primeira vez na rede descentralizada, faça-o sem enxertos. Verifique se o subgraph está estável e funciona como esperado. - -**Atualizações Subsequentes**: quando o seu subgraph estiver ativo e estável na rede descentralizada, será possível usar enxertos para versões futuras, para tornar a transição mais suave e preservar dados históricos. - -Ao aderir a estas diretrizes, dá para minimizar riscos e garantir um processo de migração mais suave. - -## Como Construir um Subgraph Existente - -Construir subgraphs é uma parte essencial do The Graph, descrita mais profundamente [aqui](/subgraphs/quick-start/). Para poder construir e implementar o subgraph existente usado neste tutorial, veja o seguinte repositório: - -- [Exemplo de repositório de subgraph](https://github.com/Shiyasmohd/grafting-tutorial) - -> Nota: O contrato usado no subgraph foi tirado do seguinte [Kit para Iniciantes de Hackathon](https://github.com/schmidsi/hackathon-starterkit). - -## Definição de Manifest de Subgraph - -O manifest do subgraph `subgraph.yaml` identifica as fontes de dados para o subgraph, os gatilhos de interesse, e as funções que devem ser executadas em resposta a esses gatilhos. Veja abaixo um exemplo de manifesto de subgraph para usar: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- A fonte de dados `Lock` consiste na ABI (Interface binária de aplicação), e o endereço de contrato que receberemos ao compilar e implantar o contrato -- A rede deve corresponder a uma rede indexada a ser consultada em query. Como estamos a operar na testnet da Sepolia, a rede é `sepolia` -- A seção `mapping` define os gatilhos de interesse e as funções a executar em resposta a esses. Neste caso, estamos à espera do evento `Withdrawal`; quando emitido, chamaremos a função `handleWithdrawal`. - -## Definição de Manifest de Enxertos - -Enxertos exigem a adição de dois novos itens ao manifest do subgraph original: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` é uma lista de todos os [nomes de função](/developing/creating-a-subgraph/#experimental-features) usados. -- `graft:` é um mapa do subgraph `base` e ​​do bloco para enxertar. `block` é o número do bloco para começar a indexação. The Graph copiará os dados do subgraph base até, e incluindo, o bloco fornecido, e então continuará a indexar o novo subgraph a partir desse bloco em diante. - -Os valores `base` e ​​`block` podem ser encontrados com a implantação de dois subgraphs: um para indexação de base e outro com enxerto - -## Como Lançar o Subgraph Base - -1. Vá para o [Subgraph Studio](https://thegraph.com/studio/) e crie um subgraph na testnet da Sepolia chamado `graft-example` -2. Siga as direções na seção `AUTH & DEPLOY` na sua página de subgraph, na pasta `graft-example` do repositório -3. Ao terminar, verifique que o subgraph está a indexar corretamente. Se executar o seguinte comando no The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Ele deve retornar algo assim: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Após verificar que o subgraph está a indexar corretamente, será possível atualizar rapidamente o subgraph com o enxerto. - -## Como Lançar o Subgraph de Enxerto - -O subgraph.yaml do substituto terá um novo endereço de contrato. Isto pode acontecer quando atualizar o seu dapp, relançar um contrato, etc. - -1. Vá para o [Subgraph Studio](https://thegraph.com/studio/) e crie um subgraph na testnet da Sepolia chamado `graft-replacement` -2. Crie um novo manifesto. O `subgraph.yaml` para `graph-replacement` contém um endereço de contrato diferente e novas informações sobre como ele deve enxertar. Estes são o `block` do [último evento importante emitido](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) pelo contrato antigo, e o `base` do subgraph antigo. A ID de subgraph `base` é a `Deployment ID` do seu subgraph `graph-example` original. Você pode encontrá-la no Subgraph Studio. -3. Siga as instruções na seção `AUTH & DEPLOY` da sua página de subgraph, na pasta `graft-replacement` do repositório -4. Ao terminar, verifique que o subgraph está a indexar corretamente. Se executar o seguinte comando no The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Ele deve retornar algo como: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -Repare que o subgraph `graft-replacement` está a indexar a partir de dados `graph-example` mais antigos e dados mais novos do novo endereço de contrato. O contrato original emitiu dois eventos `Withdrawal`: [Evento 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) e [Evento 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). O novo contrato emitiu um `Withdrawal` após, [Evento 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). As duas transações indexadas anteriormente (Evento 1 e 2) e a nova transação (Evento 3) foram combinadas no subgraph `graft-replacement`. - -Parabéns! Enxertaste um subgraph em outro subgraph. - -## Outros Recursos - -Caso queira mais experiência com enxertos, veja alguns exemplos de contratos populares: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -Para se tornar especialista no The Graph, aprenda sobre outras maneiras de cuidar de mudanças em fontes de dados subjacentes. Alternativas como [Modelos de Fontes de Dados](/developing/creating-a-subgraph/#data-source-templates) podem dar resultados parecidos - -> Nota: Grande parte do material deste artigo foi tirado do [artigo anteriormente editado sobre o Arweave](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/pt/subgraphs/cookbook/near.mdx b/website/src/pages/pt/subgraphs/cookbook/near.mdx deleted file mode 100644 index 58143e87a809..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Construção de Subgraphs na NEAR ---- - -Este guia é uma introdução à construção de subgraphs para indexar contratos inteligentes na blockchain [NEAR](https://docs.near.org/). - -## O que é NEAR? - -[NEAR](https://near.org/) é uma plataforma de contrato inteligente para construir aplicativos descentralizados. Visite a [documentação oficial](https://docs.near.org/concepts/basics/protocol) para mais informações. - -## O que são subgraphs na NEAR? - -The Graph fornece aos programadores ferramentas para processar eventos de blockchain e tornar os dados resultantes facilmente disponíveis por meio de uma API GraphQL, conhecida individualmente como subgraph. O [Graph Node](https://github.com/graphprotocol/graph-node) agora é capaz de processar eventos NEAR, o que significa que programadores da NEAR agora podem criar subgraphs para indexar seus contratos inteligentes. - -Subgraphs são baseados em eventos; ou seja, eles esperam e então processam eventos on-chain. Atualmente há dois tipos de handlers que funcionam para subgraphs na NEAR: - -- Handlers de blocos: executados em todos os blocos novos -- Handlers de recibos: Executados sempre que uma mensagem é executada numa conta especificada - -[Da documentação da NEAR](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Um Recibo é o único objeto acionável no sistema. Quando falamos de "processar uma transação" na plataforma NEAR, em algum ponto isto eventualmente significa "aplicar recibos". - -## Construindo um Subgraph no NEAR - -`@graphprotocol/graph-cli` é uma ferramenta de linha de comando para a construção e implantação de subgraphs. - -`@graphprotocol/graph-ts` é uma biblioteca de tipos específicos a subgraphs. - -A programação de subgraphs no NEAR exige o `graph-cli` acima da versão `0.23.0`, e o `graph-ts` acima da versão `0.23.0`. - -> Construir um subgraph NEAR é um processo muito parecido com a construção de um subgraph que indexa o Ethereum. - -Há três aspectos de definição de subgraph: - -**subgraph.yaml:** o manifest do subgraph, que define as fontes de dados de interesse e como elas devem ser processadas. A NEAR é uma nova espécie (`kind`) de fonte de dados. - -**schema.graphql:** um arquivo de schema que define quais dados são armazenados para o seu subgraph e como consultá-los via GraphQL. Os requisitos para subgraphs NEAR são cobertos pela [documentação existente](/developing/creating-a-subgraph/#the-graphql-schema). - -**Mapeamentos de AssemblyScript:** [Código AssemblyScript](/subgraphs/developing/creating/graph-ts/api/) que traduz dos dados do evento para as entidades definidas no seu esquema. O apoio à NEAR introduz tipos de dados específicos da NEAR e novas funções de análise JSON. - -Durante o desenvolvimento de um subgraph, existem dois comandos importantes: - -```bash -$ graph codegen # gera tipos do arquivo de schema identificado no manifest -$ graph build # gera Web Assembly dos arquivos AssemblyScript, e prepara todos os arquivos do subgraph em uma pasta /build -``` - -### Definição de Manifest de Subgraph - -O manifest do subgraph (`subgraph.yaml`) identifica as fontes de dados para o subgraph, os gatilhos de interesse, e as funções que devem ser executadas em resposta a tais gatilhos. Veja abaixo um exemplo de manifest para um subgraph na NEAR: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link para o arquivo de schema -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # Esta fonte de dados monitorará esta conta - startBlock: 10662188 # Necessário para a NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # nome da função no arq. de mapeamento - receiptHandlers: - - handler: handleReceipt # nome da função no arq. de mapeamento - file: ./src/mapping.ts # link ao arq. com os mapeamentos de Assemblyscript -``` - -- Subgraphs na NEAR introduzem um novo tipo (`kind`) de fonte de dados (`near`) -- O `network` deve corresponder a uma rede no Graph Node hóspede. No Subgraph Studio, a mainnet da NEAR é `near-mainnet`, e a testnet da NEAR é `near-testnet` -- Fontes de dados na NEAR introduzem um campo `source.account` opcional: uma ID legível a humanos que corresponde a uma [conta na NEAR](https://docs.near.org/concepts/protocol/account-model). Isto pode ser uma conta ou subconta. -- As fontes de dados da NEAR introduzem um campo alternativo `source.accounts` opcional, que contém sufixos e prefixos opcionais. Pelo menos prefix ou sufixo deve ser especificado, eles corresponderão a qualquer conta que comece ou termine com a lista de valores, respectivamente. O exemplo abaixo corresponderia a: `[app|good].*[morning.near|morning.testnet]`. Se apenas uma lista de prefixos ou sufixos for necessária, o outro campo pode ser omitido. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -As fontes de dados na NEAR apoiam duas categorias de handlers: - -- `blockHandlers`: executado em cada novo bloco na NEAR. Não é necessário nenhum `source.account`. -- `receiptHandlers`: executados em todo recibo onde o `source.account` da fonte de dados é o recipiente. Note que só são processadas combinações exatas ([subcontas](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) devem ser adicionadas como fontes de dados independentes). - -### Definição de Schema - -A definição de Schema descreve a estrutura do banco de dados resultado do subgraph, e os relacionamentos entre entidades. Isto é agnóstico da fonte de dados original. Para mais detalhes na definição de schema de subgraph, [clique aqui](/developing/creating-a-subgraph/#the-graphql-schema). - -### Mapeamentos em AssemblyScript - -Os handlers para processamento de eventos estão escritos em [AssemblyScript](https://www.assemblyscript.org/). - -A indexação da NEAR introduz tipos de dados específicos desse ecossistema à [API do AssemblyScript](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -Estes tipos são repassados para handlers de blocos e recibos: - -- Handlers de blocos receberão um `Block` -- Handlers de recibos receberão um `ReceiptWithOutcome` - -Caso contrário, o resto da [API do AssemblyScript](/subgraphs/developing/creating/graph-ts/api/) está à disposição dos programadores de subgraph na NEAR, durante a execução dos mapeamentos. - -Isto inclui uma nova função de análise em JSON: logs na NEAR são frequentemente emitidos como JSONs em string. A nova função json.fromString(...) está disponível como parte da [API JSON](/subgraphs/developing/creating/graph-ts/api/#json-api) para que programadores processem estes logs com mais facilidade. - -## Lançando um Subgraph na NEAR - -Quando tiver um subgraph pronto, chegará a hora de implantá-lo no Graph Node para indexar. Subgraphs na NEAR podem ser implantados em qualquer Graph Node `>=v0.26.x` (esta versão ainda não foi marcada ou liberada). - -O Subgraph Studio e o Indexador de atualização na Graph Network apoiam atualmente a indexação da mainnet e da testnet do NEAR em beta, com os seguintes nomes de rede: - -- `near-mainnet` -- `near-testnet` - -Para mais informações sobre criar e implantar subgraphs no Subgraph Studio, clique [aqui](/deploying/deploying-a-subgraph-to-studio/). - -Para começo de conversa, o primeiro passo consiste em "criar" o seu subgraph - isto só precisa ser feito uma vez. No Subgraph Studio, isto pode ser feito do [seu Painel](https://thegraph.com/studio/): "Criar um subgraph". - -Quando o seu subgraph estiver pronto, implante o seu subgraph com o comando de CLI `graph deploy`: - -```sh -$ graph create --node # cria um subgraph num Graph Node local (no Subgraph Studio, isto é feito via a interface) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # sobe os arquivos do build a um ponto final IPFS especificado, e implanta o subgraph num Graph Node com base no hash IPFS do manifest -``` - -A configuração do nódulo dependerá de onde o subgraph será lançado. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Graph Node local (baseado na configuração padrão) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Quando o seu subgraph for lançado, ele será indexado pelo Graph Node. O seu progresso pode ser conferido com um query no próprio subgraph: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Como indexar a NEAR com um Graph Node local - -Executar um Graph Node que indexa a NEAR exige estes requisitos opcionais: - -- NEAR Indexer Framework (Estrutura de Indexer) com instrumentação Firehose -- Componente(s) de Firehose no NEAR -- Graph Node com endpoint Firehose configurado - -Em breve, falaremos mais sobre como executar os componentes acima. - -## Como Consultar um Subgraph na NEAR - -O ponto final do GraphQL para subgraphs na NEAR é determinado pela definição do schema, com a interface existente da API. Visite a [documentação da API da GraphQL](/subgraphs/querying/graphql-api/) para mais informações. - -## Exemplos de Subgraphs - -Aqui estão alguns exemplos de subgraphs para referência: - -[Blocos da NEAR](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[Recibos da NEAR](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### Como o beta funciona? - -O apoio à NEAR está em beta; podem ocorrer mais mudanças na API enquanto continuamos a melhorar a integração. Por favor, contacte-nos em near@thegraph.com para podermos apoiar-te na construção de subgraphs no NEAR e avisar-te sobre os acontecimentos mais recentes! - -### Um subgraph pode indexar chains da NEAR e da EVM? - -Não, um subgraph só pode apoiar fontes de dados de apenas uma chain/rede. - -### Os subgraphs podem reagir a gatilhos mais específicos? - -Atualmente, só há apoio a gatilhos de Blocos e Recibos. Estamos a investigar gatilhos para chamadas de função a uma conta específica. Também temos interesse em apoiar gatilhos de eventos, quando a NEAR receber apoio nativo a eventos. - -### Handlers de recibos ativarão para contas e subcontas? - -Se uma conta (`account`) for especificada, ela só combinará com o nome exacto da conta. É possível corresponder subcontas ao especificar um campo `accounts`, com sufixos (`suffixes`) e prefixos (`prefixes`) particularizados para encontrar contas e subcontas. Por exemplo, todas as subcontas `mintbase1.near` seriam encontradas com o seguinte: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Subgraphs na NEAR podem fazer chamadas de vistoria para contas NEAR durante os mapeamentos? - -Não há apoio a isto. Estamos a avaliar se esta funcionalidade é necessária para indexação. - -### Posso usar modelos de fontes de dados no meu subgraph na NEAR? - -Não há apoio a isto no momento. Estamos a avaliar se esta funcionalidade é necessária para indexação. - -### Subgraphs no Ethereum apoiam versões "pendentes" e "atuais". Como posso lançar uma versão "pendente" de um subgraph no NEAR? - -No momento, não há apoio à funcionalidade de pendências para subgraphs na NEAR. Entretanto, podes lançar uma nova versão para um subgraph de "nome" diferente, e quando este for sincronizado com a cabeça da chain, podes relançá-la para seu subgraph de "nome" primário, que usará o mesmo ID de lançamento subjacente — e aí, o subgraph principal sincronizará instantaneamente. - -### A minha pergunta não foi respondida. Onde posso conseguir mais ajuda sobre construir subgraphs na NEAR? - -Se esta for uma pergunta geral sobre programação de subgraphs, há mais informações no resto da [documentação para programadores](/subgraphs/quick-start/). Caso contrário, entre no [Discord do Graph Protocol](https://discord.gg/graphprotocol) e pergunte no canal #near, ou mande a sua pergunta para near@thegraph.com. - -## Referências - -- [Documentação para programadores na NEAR](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/pt/subgraphs/cookbook/polymarket.mdx b/website/src/pages/pt/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index add043fc2af3..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Como Consultar Dados de Blockchain do Polymarket com Subgraphs no The Graph -sidebarTitle: Query Polymarket Data ---- - -Consulte os dados na chain do Polymarket usando a GraphQL via subgraphs na The Graph Network. Subgraphs são APIs descentralizadas energizadas pelo The Graph, um protocolo para indexação e consulta de dados de blockchains. - -## Subgraph do Polymarket no Graph Explorer - -Dá para ver um playground interativo de queries na [página do subgraph do Polymarket no The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), onde você pode testar qualquer query. - -![Playground da Polymarket](/img/Polymarket-playground.png) - -## Como Usar o Editor Visual de Queries - -O editor visual de queries permite-te testar exemplos de query do seu subgraph. - -Você pode usar o GraphiQL Explorer para compor os seus queries da GraphQL clicando nos campos desejados. - -### Exemplo de Query: 5 maiores pagamentos do Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Exemplo de retorno - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Schema da GraphQL do Polymarket - -O esquema deste subgraph é definido [aqui no GitHub do Polymarket](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Ponto Final do Subgraph do Polymarket - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -O ponto final do subgraph do Polymarket está disponível no [Graph Explorer](https://thegraph.com/explorer). - -![Ponto Final do Polymarket](/img/Polymarket-endpoint.png) - -## Como Adquirir sua Própria Chave de API - -1. Entre em [https://thegraph.com/studio](http://thegraph.com/studio) e conecte a sua carteira de criptomoedas -2. Crie uma chave de API em https://thegraph.com/studio/apikeys/ - -Esta chave de API vale para qualquer subgraph no [Graph Explorer](https://thegraph.com/explorer), não apenas no Polymarket. - -Cem mil queries por mês de graça, perfeito para um projeto paralelo! - -## Subgraphs Adicionais do Polymarket - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket — Atividade na Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket — Lucro e Prejuízo](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket — Contratos em Aberto](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## Como fazer Queries com a API - -Qualquer query da GraphQL pode ser passada para o ponto final do Polymarket; os dados serão recebidos no formato json. - -O exemplo de código a seguir retornará exatamente o mesmo resultado que acima. - -### Exemplo de Código do node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Mandar o query da GraphQL -axios(graphQLRequest) - .then((response) => { - // Controlar a resposta aqui - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Controlar quaisquer erros - console.error(error); - }); -``` - -### Outros Recursos - -Para mais informações sobre queries de dados do seu subgraph, leia mais [aqui](/subgraphs/querying/introduction/). - -Para explorar todas as maneiras de otimizar e personalizar o seu subgraph para melhor desempenho, leia mais sobre [como criar um subgraph aqui](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pt/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/pt/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 768ee1418880..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Como Proteger Chaves de API com Componentes do Servidor Next.js ---- - -## Visão geral - -Podemos proteger a nossa chave API no frontend do nosso dApp com [componentes do servidor Next.js](https://nextjs.org/docs/app/building-your-application/rendering/server-components). Para ainda mais segurança, também podemos [restringir a nossa chave API a certos domínios ou subgraphs no Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -Neste manual, veremos como criar um componente de servidor Next.js que faz queries em um subgraph enquanto esconde a chave API do frontend. - -### Porém... - -- Componentes de servidor Next.js não protegem chaves API de extrações durante ataques DDoS (negação distribuída de serviço). -- Os gateways da Graph Network têm estratégias prontas de mitigação e deteção de negação de serviço, mas o uso de componentes de servidor pode enfraquecer estas proteções. -- Componentes de servidor Next.js introduzem riscos de centralização, possibilitando uma derruba do servidor. - -### Por Que é Necessário - -Num aplicativo de React normal, chaves API incluídas no código do frontend podem ser expostas ao lado do cliente, o que apresenta um risco de segurança. É normal o uso de arquivos `.env`, mas estes não protegem as chaves por completo, já que o código do React é executado no lado do cliente (client-side), o que expõe a chave API nos headers. Os componentes do servidor Next.js abordam este problema via a execução de operações sensíveis server-side. - -### Como usar renderização client-side para fazer queries em um subgraph - -![Renderização client-side](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- Uma chave API do [Subgraph Studio](https://thegraph.com/studio) -- Conhecimentos básicos de Next.js e React. -- Um projeto Next.js existente que use o [App Router](https://nextjs.org/docs/app). - -## Manual Passo a Passo - -### Passo 1: Prepare Variáveis de Ambiente - -1. Na raiz do nosso projeto Next.js, crie um arquivo `env.local`. -2. Adicione a nossa chave API: `API_KEY=`. - -### Passo 2: Crie um Componente de Servidor - -1. No nosso diretório `components`, crie um arquivo novo, `ServerComponent.js`. -2. Use o exemplo de código acima para preparar o componente do servidor. - -### Passo 3: Implemente o Pedido da API Server-Side - -No `ServerComponent.js`, adicione o seguinte código: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Passo 4: Utilize o Componente do Servidor - -1. No nosso arquivo de página (por ex., `pages/index.js`), importe `Server Component`. -2. Renderize o componente: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Passo 5: Execute e Teste o Nosso dApp - -Inicie o nosso aplicativo Next.js com `npm run dev`. Verifique se o componente do servidor retira dados sem expor a chave API. - -![Renderização server-side](/img/api-key-server-side-rendering.png) - -### Conclusão - -Ao utilizar os Componentes de Servidor Next.js, nós praticamente escondemos a chave API do client-side, o que aumenta a segurança do nosso aplicativo. Com este método, operações sensíveis podem ser executadas server-side, longe de vulnerabilidades em potencial no client-side. E finalmente, orientamos que explore [outras medidas de segurança de chave API](/subgraphs/querying/managing-api-keys/) para aumentar ainda mais a sua segurança de chaves API. diff --git a/website/src/pages/pt/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/pt/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 8d1a1bc6444a..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Debugging de Subgraphs Rápido e Fácil Com Forks ---- - -Assim como vários sistemas que processam uma abundância de dados, os Indexadores do Graph (Graph Nodes) podem demorar um pouco para sincronizar o seu subgraph com a blockchain de destino. A discrepância entre mudanças rápidas para fins de debugging e os longos tempos de espera necessários para o indexing é extremamente contraprodutiva, e nós sabemos muito bem disso. É por isso que introduzimos o **forking de subgraphs**, programado pela [LimeChain](https://limechain.tech/); neste artigo. Veja como dá para acelerar bastante o debugging de subgraphs! - -## Ok, o que é isso? - -**Forking de subgraphs** é o processo de retirar entidades tranquilamente do armazenamento de _outro_ subgraph (normalmente, remoto). - -No contexto do debugging, o **forking de subgraphs** permite debugar o seu subgraph falho no bloco _X_ sem precisar esperar que ele sincronize até o bloco _X_. - -## O quê?! Como?! - -Quando um subgraph é implementado a um Graph Node remoto para indexação, e ele falha no bloco _X_, a boa notícia é que o Graph Node ainda servirá queries GraphQL com seu armazenamento, que é sincronizado até o bloco _X_. Ótimo! Podemos aproveitar este armazenamento "atualizado" para consertar os bugs que surgem ao indexar o bloco _X_. - -Resumindo, faremos um fork do subgraph falho de um Graph Node remoto para garantir que o subgraph seja indexado até o bloco _X_, para fornecer ao subgraph implantado localmente uma visão atualizada do estado da indexação; sendo este debugado no bloco _X_. - -## Por favor, quero ver códigos! - -Para manter a concentração no debugging de subgraphs, vamos começar com coisas simples: siga o [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) a indexar o contrato inteligente Ethereum Gravity. - -Aqui estão os handlers definidos para a indexação dos `Gravatars`, sem qualquer bug: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Que pena! Quando eu implanto o meu lindo subgraph no Subgraph Studio, ele falha com o erro "Gravatar not found" (Gravatar não encontrado). - -A maneira mais comum de tentar consertar este erro é: - -1. Fazer uma mudança na fonte dos mapeamentos, que talvez possa resolver o problema (mas é claro que não vai). -2. Implante o subgraph novamente no [Subgraph Studio](https://thegraph.com/studio/) (ou outro Graph Node remoto). -3. Esperar que ele se sincronize. -4. Se quebrar novamente, volte ao passo 1. Se não: Eba! - -É um típico processo ordinário de debug, mas há um passo que atrasa muito o processo: _3. Esperar que ele se sincronize._ - -Com o **forking de subgraphs**, essencialmente, podemos eliminar este passo. É mais ou menos assim: - -0. Crie um Graph Node local com o conjunto de **_fork-base apropriado_**. -1. Faça uma mudança na fonte dos mapeamentos, que talvez possa resolver o problema. -2. Implante-o no Graph Node local, **faça um fork do subgraph falho**, e **comece do bloco problemático\_**. -3. Se quebrar novamente, volte ao passo 1. Se não: Eba! - -Agora, você deve ter duas perguntas: - -1. Que fork-base??? -2. Forkar quem?! - -E eu respondo: - -1. `fork-base` é o URL "base", tal que quando a _id de subgraph_ é atrelada, o URL resultante (`/`) se torna um ponto final GraphQL válido para o armazenamento do subgraph. -2. Forking é fácil, não precisa se preocupar: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Aliás, não esqueça de preencher o campo `dataSources.source.startBlock` no manifest do subgraph com o número do bloco problemático, para pular a indexação de blocos desnecessários e tomar vantagem do fork! - -Aqui está o que eu faço: - -1. Eu crio um Graph Node local ([veja como](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) com a opção `fork-base` de `https://api.thegraph.com/subgraphs/id/`, já que eu vou forkar um subgraph, o bugado que eu lancei anteriormente, do [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. Após vistoriar com cuidado, percebo uma discrepância nas representações de `id` usadas ao indexar `Gravatar`s nos meus dois handlers. Enquanto `handleNewGravatar` o converte a um hex (`event.params.id.toHex()`), o `handleUpdatedGravatar` usa um int32 (`event.params.id.toI32()`). Assim, o `handleUpdatedGravatar` entra em pânico com o "Gravatar não encontrado!". Eu faço os dois converterem o `id` em um hex. -3. Após ter feito as mudanças, implanto o meu subgraph no Graph Node local, **_fazendo um fork do subgraph falho_** e programando o `dataSources.source.startBlock` em `6190343` no `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. Eu verifico os logs produzidos pelo Graph Node local e... eba! Parece que deu tudo certo. -5. Lanço o meu subgraph, agora livre de bugs, a um Graph Node remoto e vivo feliz para sempre! (mas sem batatas) diff --git a/website/src/pages/pt/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/pt/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 522740ee8246..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Gerador de Código Seguro para Subgraphs ---- - -O [Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) é uma ferramenta geradora de código, que gera um conjunto de funções de helper a partir do schema GraphQL de um projeto. Ela garante total segurança e consistência em todas as interações com entidades no seu subgraph. - -## Por que integrar com a Subgraph Uncrashable? - -- **Atividade Contínua**. Entidades mal-cuidadas podem causar panes em subgraphs, o que pode ser perturbador para projetos dependentes no The Graph. Prepare funções de helper para deixar os seus subgraphs "impossíveis de travar" e garantir a continuidade dos negócios. - -- **Totalmente Seguro**. Alguns dos problemas comuns vistos na programação de subgraphs são problemas de carregamento de entidades não definidas; o não-preparo ou inicialização de todos os valores de entidades; e condições de corrida sobre carregamento e salvamento de entidades. Garanta que todas as interações com entidades sejam completamente atômicas. - -- **Configurável pelo Utilizador**. Determine valores padrão e configure o nível necessário de verificações de segurança para o seu projeto. São gravados registros de aviso que indicam onde há uma brecha de lógica no subgraph, auxiliando o processo de solução de problemas e garantir a precisão dos dados. - -**Características Importantes** - -- A ferramenta de geração de código acomoda **todos** os tipos de subgraph e pode ser configurada para que os utilizadores coloquem padrões razoáveis nos valores. A geração de código usará esta configuração para gerar funções de helper que combinem com a especificação do utilizador. - -- A estrutura também inclui uma maneira (através do arquivo de configuração) de criar funções personalizadas, mas seguras, para configurar grupos de variáveis de entidade. Desta maneira, é impossível que o utilizador carregue/use uma entidade de graph obsoleta, e também é impossível esquecer de salvar ou determinar uma variável exigida pela função. - -- Logs de aviso são registrados como logs que indicam onde há uma quebra de lógica no subgraph, para ajudar a consertar o problema e garantir a segurança dos dados. - -A Subgraph Uncrashable pode ser executada como flag opcional usando o comando codegen no Graph CLI. - -```sh -graph codegen -u [options] [] -``` - -Visite a [documentação do Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/docs/) ou veja este [tutorial em vídeo](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) para aprender como programar subgraphs mais seguros. diff --git a/website/src/pages/pt/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/pt/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index e5ad802a2941..000000000000 --- a/website/src/pages/pt/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Transfira-se para The Graph ---- - -Migre rapidamente os seus subgraphs, de qualquer plataforma para a [rede descentralizada do The Graph](https://thegraph.com/networks/). - -## Vantagens de Trocar para The Graph - -- Use o mesmo subgraph que os seus aplicativos já usam, com migração sem tempo de ócio. -- Aumenta a confiabilidade de uma rede global mantida por mais de 100 Indexadores. -- Receba suporte rápido para subgraphs, com uma equipa de engenharia de plantão disponível a todas as horas. - -## Atualize o Seu Subgraph para The Graph em 3 Etapas Fáceis - -1. [Construa o Seu Ambiente do Studio](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Implante o Seu Subgraph no Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Edite na The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## Construa o Seu Ambiente do Studio - -### Como Criar um Subgraph no Subgraph Studio - -- Entre no [Subgraph Studio](https://thegraph.com/studio/) e conecte a sua carteira de criptomoedas. -- Clique em "Create a Subgraph" ("Criar um Subgraph"). É recomendado nomear o subgraph em caixa de título: por exemplo, "Nome De Subgraph Nome da Chain". - -> Observação: após a edição, o nome do subgraph poderá ser editado, mas isto sempre exigirá uma ação on-chain sempre, então pense bem no nome que irá dar. - -### Instale a Graph CLI - -É necessário ter [Node.js](https://nodejs.org/) e um gerenciador de pacotes da sua escolha (`npm` ou `pnpm`) instalados, para usar a Graph CLI. Verifique a versão [mais recente](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) da CLI. - -Na sua máquina local, execute o seguinte comando: - -Uso de [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use o comando a seguir para criar um subgraph no Studio com a CLI: - -```sh -graph init --product subgraph-studio -``` - -### Autentique o Seu Subgraph - -Na Graph CLI, use o comando `auth` visto no Subgraph Studio: - -```sh -graph auth -``` - -## 2. Implante o Seu Subgraph no Studio - -Se tiver o seu código-fonte, pode facilmente implantá-lo no Studio. Se não o tiver, aqui está uma maneira rápida de implantar o seu subgraph. - -Na The Graph CLI, execute o seguinte comando: - -```sh -graph deploy --ipfs-hash - -``` - -> **Observação:** Cada subgraph tem um hash IPFS (ID de Implantação), que se parece com isto: "Qmasdfad...". Para implantar, basta usar este **hash IPFS**. Aparecerá uma solicitação de versão (por exemplo, v0.0.1). - -## 3. Edite o Seu Subgraph na The Graph Network - -![Botão de edição](/img/publish-sub-transfer.png) - -### Faça um Query - -> Para atrair cerca de 3 indexadores para fazer queries no seu subgraph, recomendamos curar pelo menos 3.000 GRT. Para saber mais sobre a curadoria, leia sobre [Curadoria](/resources/roles/curating/) no The Graph. - -Dá para começar a [fazer queries](/subgraphs/querying/introduction/) em qualquer subgraph enviando um query GraphQL para o ponto final da URL de query do subgraph, localizado na parte superior da página do Explorer no Subgraph Studio. - -#### Exemplo - -[Subgraph: CryptoPunks Ethereum](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) por Messari: - -![URL de Query](/img/cryptopunks-screenshot-transfer.png) - -A URL de queries para este subgraph é: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**sua-chave-de-api**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Agora, você só precisa preencher **sua própria chave de API** para começar a enviar queries GraphQL para este ponto final. - -### Como adquirir sua própria Chave de API - -É possível riar chaves de API no Subgraph Studio na aba “Chaves de API” na parte superior da página: - -![Chaves de API](/img/Api-keys-screenshot.png) - -### Como Monitorar o Estado do Seu Subgraph - -Após a atualização, poderá acessar e gerir os seus subgraphs no [Subgraph Studio](https://thegraph.com/studio/) e explorar todos os subgraphs no [The Graph Explorer](https://thegraph.com/networks/). - -### Outros Recursos - -- Para criar e editar um novo subgraph, veja o [Guia de Início Rápido](/subgraphs/quick-start/). -- Para explorar todas as maneiras de otimizar e personalizar o seu subgraph para melhor desempenho, leia mais sobre [como criar um subgraph aqui](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pt/subgraphs/guides/_meta.js b/website/src/pages/pt/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/pt/subgraphs/guides/arweave.mdx b/website/src/pages/pt/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/pt/subgraphs/guides/enums.mdx b/website/src/pages/pt/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/pt/subgraphs/guides/grafting.mdx b/website/src/pages/pt/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/pt/subgraphs/guides/near.mdx b/website/src/pages/pt/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/pt/subgraphs/guides/polymarket.mdx b/website/src/pages/pt/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/pt/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/pt/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/pt/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/pt/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/pt/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/pt/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/pt/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/pt/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/pt/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ro/subgraphs/_meta-titles.json b/website/src/pages/ro/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/ro/subgraphs/_meta-titles.json +++ b/website/src/pages/ro/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/ro/subgraphs/_meta.js b/website/src/pages/ro/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/ro/subgraphs/_meta.js +++ b/website/src/pages/ro/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/ro/subgraphs/cookbook/_meta.js b/website/src/pages/ro/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/ro/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/ro/subgraphs/cookbook/enums.mdx b/website/src/pages/ro/subgraphs/cookbook/enums.mdx deleted file mode 100644 index a10970c1539f..000000000000 --- a/website/src/pages/ro/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Additional Resources - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ro/subgraphs/cookbook/grafting.mdx b/website/src/pages/ro/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 57d5169830a7..000000000000 --- a/website/src/pages/ro/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Replace a Contract and Keep its History With Grafting ---- - -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. - -## What is Grafting? - -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. - -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: - -- It adds or removes entity types -- It removes attributes from entity types -- It adds nullable attributes to entity types -- It turns non-nullable attributes into nullable attributes -- It adds values to enums -- It adds or removes interfaces -- It changes for which entity types an interface is implemented - -For more information, you can check: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## Building an Existing Subgraph - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Subgraph Manifest Definition - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Grafting Manifest Definition - -Grafting requires adding two new items to the original subgraph manifest: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Deploying the Base Subgraph - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It returns something like this: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. - -## Deploying the Grafting Subgraph - -The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It should return the following: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Additional Resources - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ro/subgraphs/cookbook/polymarket.mdx b/website/src/pages/ro/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/ro/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ro/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/ro/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 6610f19da66d..000000000000 --- a/website/src/pages/ro/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Quick and Easy Subgraph Debugging Using Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## Ok, what is it? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## What?! How? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## Please, show me some code! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -The usual way to attempt a fix is: - -1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Wait for it to sync-up. -4. If it breaks again go back to 1, otherwise: Hooray! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. If it breaks again, go back to 1, otherwise: Hooray! - -Now, you may have 2 questions: - -1. fork-base what??? -2. Forking who?! - -And I answer: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Forking is easy, no need to sweat: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -So, here is what I do: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ro/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/ro/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 0cc91a0fa2c3..000000000000 --- a/website/src/pages/ro/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Safe Subgraph Code Generator ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Why integrate with Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/ro/subgraphs/guides/_meta.js b/website/src/pages/ro/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/ro/subgraphs/guides/arweave.mdx b/website/src/pages/ro/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/ro/subgraphs/guides/enums.mdx b/website/src/pages/ro/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ro/subgraphs/guides/grafting.mdx b/website/src/pages/ro/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ro/subgraphs/guides/near.mdx b/website/src/pages/ro/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ro/subgraphs/guides/polymarket.mdx b/website/src/pages/ro/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ro/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/ro/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ro/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/ro/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ro/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/ro/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ro/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/ro/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/ro/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ru/subgraphs/_meta-titles.json b/website/src/pages/ru/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/ru/subgraphs/_meta-titles.json +++ b/website/src/pages/ru/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/ru/subgraphs/_meta.js b/website/src/pages/ru/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/ru/subgraphs/_meta.js +++ b/website/src/pages/ru/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/ru/subgraphs/cookbook/_meta.js b/website/src/pages/ru/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/ru/subgraphs/cookbook/arweave.mdx b/website/src/pages/ru/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index a7f24e1bf79e..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Создание Субграфов на Arweave ---- - -> Поддержка Arweave в Graph Node и Subgraph Studio находится на стадии бета-тестирования. Если у Вас есть вопросы о создании субграфов Arweave, свяжитесь с нами в [Discord](https://discord.gg/graphprotocol)! - -Из этого руководства Вы узнаете, как создавать и развертывать субграфы для индексации блокчейна Arweave. - -## Что такое Arweave? - -Протокол Arweave позволяет разработчикам хранить данные на постоянной основе, и в этом основное различие между Arweave и IPFS, поскольку в IPFS отсутствует функция постоянства, а файлы, хранящиеся в Arweave, не могут быть изменены или удалены. - -Arweave уже создала множество библиотек для интеграции протокола на нескольких различных языках программирования. С дополнительной информацией Вы можете ознакомиться: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Ресурсы Arweave](https://www.arweave.org/build) - -## Что такое субграфы Arweave? - -The Graph позволяет создавать собственные открытые API, называемые "Субграфами". Субграфы используются для указания индексаторам (операторам серверов), какие данные индексировать на блокчейне и сохранять на их серверах, чтобы Вы могли запрашивать эти данные в любое время используя [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) теперь может индексировать данные на протоколе Arweave. Текущая интеграция индексирует только Arweave как блокчейн (блоки и транзакции), она еще не индексирует сохраненные файлы. - -## Построение Субграфа на Arweave - -Чтобы иметь возможность создавать и развертывать Субграфы на Arweave, Вам понадобятся два пакета: - -1. `@graphprotocol/graph-cli` версии выше 0.30.2 — это инструмент командной строки для создания и развертывания субграфов. [Нажмите здесь](https://www.npmjs.com/package/@graphprotocol/graph-cli), чтобы скачать с помощью `npm`. -2. `@graphprotocol/graph-ts` версии выше 0.27.0 — это библиотека типов, специфичных для субграфов. [Нажмите здесь](https://www.npmjs.com/package/@graphprotocol/graph-ts), чтобы скачать с помощью `npm`. - -## Составляющие Субграфов - -Существует 3 компонента субграфа: - -### 1. Манифест - `subgraph.yaml` - -Определяет источники данных, представляющие интерес, и то, как они должны обрабатываться. Arweave - это новый вид источника данных. - -### 2. Схема - `schema.graphql` - -Здесь Вы определяете, какие данные хотите иметь возможность запрашивать после индексации своего субграфа с помощью GraphQL. На самом деле это похоже на модель для API, где модель определяет структуру тела запроса. - -Требования для субграфов Arweave описаны в [имеющейся документации](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. Мэппинги на AssemblyScript - `mapping.ts` - -Это логика, которая определяет, как данные должны извлекаться и храниться, когда кто-то взаимодействует с источниками данных, которые Вы отслеживаете. Данные переводятся и сохраняются в соответствии с указанной Вами схемой. - -Во время разработки субграфа есть две ключевые команды: - -``` -$ graph codegen # генерирует типы из файла схемы, указанного в манифесте -$ graph build # генерирует Web Assembly из файлов AssemblyScript и подготавливает все файлы субграфа в папке /build -``` - -## Определение манифеста субграфа - -Манифест субграфа `subgraph.yaml` определяет источники данных для субграфа, триггеры, представляющие интерес, и функции, которые должны выполняться в ответ на эти триггеры. Ниже приведён пример манифеста субграфа для Arweave: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # ссылка на файл схемы -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph поддерживает только Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # Открытый ключ кошелька Arweave - startBlock: 0 # установите это значение на 0, чтобы начать индексацию с генезиса чейна - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # ссылка на файл с мэппингами Assemblyscript - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # имя функции в файле мэппинга - transactionHandlers: - - handler: handleTx # имя функции в файле мэппинга -``` - -- Субграфы Arweave вводят новый тип источника данных (`arweave`) -- Сеть должна соответствовать сети на размещенной Graph Node. В Subgraph Studio мейннет Arweave обозначается как `arweave-mainnet` -- Источники данных Arweave содержат необязательное поле source.owner, которое является открытым ключом кошелька Arweave - -Источники данных Arweave поддерживают два типа обработчиков: - -- `blockHandlers` — выполняется при каждом новом блоке Arweave. source.owner не требуется. -- `transactionHandlers` — выполняется при каждой транзакции, где `source.owner` является владельцем источника данных. На данный момент для `transactionHandlers` требуется указать владельца. Если пользователи хотят обрабатывать все транзакции, они должны указать `""` в качестве `source.owner` - -> Source.owner может быть адресом владельца или его Публичным ключом. -> -> Транзакции являются строительными блоками Arweave permaweb, и они представляют собой объекты, созданные конечными пользователями. -> -> Примечание: транзакции [Irys (ранее Bundlr)](https://irys.xyz/) пока не поддерживаются. - -## Определение схемы - -Определение схемы описывает структуру базы данных итогового субграфа и взаимосвязи между объектами. Это не зависит от исходного источника данных. Более подробную информацию об определении схемы субграфа можно найти [здесь](/developing/creating-a-subgraph/#the-graphql-schema). - -## Мэппинги AssemblyScript - -Обработчики для обработки событий написаны на [AssemblyScript](https://www.assemblyscript.org/). - -Индексирование Arweave вводит специфичные для Arweave типы данных в [API AssemblyScript](https://thegraph. com/docs/using-graph-ts). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Обработчики блоков получают `Block`, в то время как обработчики транзакций получают `Transaction`. - -Написание мэппингов для субграфа Arweave очень похоже на написание мэппингов для субграфа Ethereum. Для получения дополнительной информации нажмите [сюда](/developing/creating-a-subgraph/#writing-mappings). - -## Развертывание субграфа Arweave в Subgraph Studio - -Как только Ваш субграф будет создан на панели управления Subgraph Studio, Вы можете развернуть его с помощью команды CLI `graph deploy`. - -```bash -graph deploy --access-token -``` - -## Запрос субграфа Arweave - -Конечная точка GraphQL для субграфов Arweave определяется схемой и существующим интерфейсом API. Для получения дополнительной информации ознакомьтесь с [документацией по API GraphQL](/subgraphs/querying/graphql-api/). - -## Примеры субграфов - -Ниже приведен пример субграфа для справки: - -- [Пример субграфа для Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Может ли субграф индексировать Arweave и другие чейны? - -Нет, субграф может поддерживать источники данных только из одного чейна/сети. - -### Могу ли я проиндексировать сохраненные файлы в Arweave? - -В настоящее время The Graph индексирует Arweave только как блокчейн (его блоки и транзакции). - -### Могу ли я идентифицировать связки Bundle в своем субграфе? - -В настоящее время это не поддерживается. - -### Как я могу отфильтровать транзакции по определенному аккаунту? - -Source.owner может быть открытым ключом пользователя или адресом учетной записи. - -### Каков текущий формат шифрования? - -Данные обычно передаются в мэппингах в виде байтов (Bytes), которые, если хранятся напрямую, возвращаются в субграф в формате `hex` (например, хэши блоков и транзакций). Вы можете захотеть преобразовать их в формат `base64` или `base64 URL`-безопасный в Ваших мэппингах, чтобы они соответствовали тому, что отображается в блок-обозревателях, таких как [Arweave Explorer](https://viewblock.io/arweave/). - -Следующая вспомогательная функция `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` может быть использована и будет добавлена в `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/ru/subgraphs/cookbook/enums.mdx b/website/src/pages/ru/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 204b35851fc3..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Категоризация маркетплейсов NFT с использованием Enums (перечислений) ---- - -Используйте Enums (перечисления), чтобы сделать Ваш код чище и уменьшить вероятность ошибок. Вот полный пример использования перечислений для маркетплейсов NFT. - -## Что такое Enums (перечисления)? - -Перечисления (или типы перечислений) — это особый тип данных, который позволяет определить набор конкретных допустимых значений. - -### Пример использования Enums (перечислений) в Вашей схеме - -Если вы создаете субграф для отслеживания истории владения токенами на рынке, каждый токен может переходить через разные стадии владения, такие как `OriginalOwner` (Первоначальный Владелец), `SecondOwner` (Второй Владелец) и `ThirdOwner` (Третий Владелец). Используя перечисления (enums), Вы можете определить эти конкретные стадии владения, обеспечивая присвоение только заранее определенных значений. - -Вы можете определить перечисления (enums) в своей схеме, и после их определения Вы можете использовать строковое представление значений перечислений для установки значения поля перечисления в объекты. - -Вот как может выглядеть определение перечисления (enum) в Вашей схеме, исходя из приведенного выше примера: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -Это означает, что когда Вы используете тип `TokenStatus` в своей схеме, Вы ожидаете, что он будет иметь одно из заранее определенных значений: `OriginalOwner` (Первоначальный Владелец), `SecondOwner` (Второй Владелец) или `ThirdOwner` (Третий Владелец), что обеспечивает согласованность и корректность данных. - -Чтобы узнать больше о перечислениях (Enums), ознакомьтесь с разделом [Создание субграфа](/developing/creating-a-subgraph/#enums) и с [документацией GraphQL](https://graphql.org/learn/schema/#enumeration-types). - -## Преимущества использования перечислений (Enums) - -- **Ясность:** Перечисления предоставляют значимые имена для значений, что делает данные более понятными. -- **Валидация:** Перечисления обеспечивают строгие определения значений, предотвращая ввод недопустимых данных. -- **Поддерживаемость:** Когда Вам нужно изменить или добавить новые категории, перечисления позволяют сделать это целенаправленно и удобно. - -### Без перечислений (Enums) - -Если Вы решите определить тип как строку вместо использования перечисления (Enum), Ваш код может выглядеть следующим образом: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -В этой схеме `TokenStatus` является простой строкой без конкретных и допустимых значений. - -#### Почему это является проблемой? - -- Нет никаких ограничений на значения `TokenStatus`, поэтому любое строковое значение может быть назначено случайно. Это усложняет обеспечение того, что устанавливаются только допустимые статусы, такие как `OriginalOwner` (Первоначальный Владелец), `SecondOwner` (Второй Владелец) или `ThirdOwner` (Третий Владелец). -- Легко допустить опечатку, например, `Orgnalowner` вместо `OriginalOwner`, что делает данные и потенциальные запросы ненадежными. - -### С перечислениями (Enums) - -Вместо присвоения строк произвольной формы Вы можете определить перечисление (Enum) для `TokenStatus` с конкретными значениями: `OriginalOwner`, `SecondOwner` или `ThirdOwner`. Использование перечисления гарантирует, что используются только допустимые значения. - -Перечисления обеспечивают безопасность типов, минимизируют риск опечаток и гарантируют согласованные и надежные результаты. - -## Определение перечислений (Enums) для Маркетплейсов NFT - -> Примечание: Следующее руководство использует смарт-контракт NFT CryptoCoven. - -Чтобы определить перечисления для различных маркетплейсов, на которых торгуются NFT, используйте следующее в своей схеме субграфа: - -```gql -# Перечисление для маркетплейсов, с которыми взаимодействовал смарт-контракт CryptoCoven (вероятно, торговля или минт) -enum Marketplace { - OpenSeaV1 # Представляет случай, когда NFT CryptoCoven торгуется на маркетплейсе OpenSeaV1 - OpenSeaV2 # Представляет случай, когда NFT CryptoCoven торгуется на маркетплейсе OpenSeaV2 - SeaPort # Представляет случай, когда NFT CryptoCoven торгуется на маркетплейсе SeaPort - LooksRare # Представляет случай, когда NFT CryptoCoven торгуется на маркетплейсе LooksRare - # ...и другие рынки -} -``` - -## Использование перечислений (Enums) для Маркетплейсов NFT - -После определения перечисления (enums) могут использоваться в Вашем субграфе для категоризации транзакций или событий. - -Например, при регистрации продаж NFT можно указать маркетплейс, на котором произошла сделка, используя перечисление. - -### Реализация функции для маркетплейсов NFT - -Вот как можно реализовать функцию для получения названия маркетплейса из перечисления (enum) в виде строки: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Используем операторы if-else для сопоставления значения перечисления со строкой - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // Если маркетплейс OpenSea, возвращаем его строковое представление - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // Если маркетплейс SeaPort, возвращаем его строковое представление - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // Если маркетплейс LooksRare, возвращаем его строковое представление - // ... и другие маркетплейсы - } -} -``` - -## Лучшие практики использования перечислений (Enums) - -- **Согласованность в наименованиях:** Используйте четкие, описательные названия для значений перечислений, чтобы улучшить читаемость кода. -- **Централизованное управление:** Храните перечисления в одном файле для обеспечения согласованности. Это облегчает обновление перечислений и гарантирует, что они являются единственным источником достоверной информации. -- **Документация:** Добавляйте комментарии к перечислениям, чтобы прояснить их назначение и использование. - -## Использование перечислений (Enums) в запросах - -Перечисления в запросах помогают улучшить качество данных и делают результаты более понятными. Они функционируют как фильтры и элементы ответа, обеспечивая согласованность и уменьшая ошибки в значениях маркетплейса. - -**Особенности** - -- **Фильтрация с помощью перечислений:** Перечисления предоставляют четкие фильтры, позволяя уверенно включать или исключать конкретные маркетплейсы. -- **Перечисления в ответах:** Перечисления гарантируют, что возвращаются только признанные названия маркетплейсов, делая результаты стандартизированными и точными. - -### Пример запросов - -#### Запрос 1: Аккаунт с наибольшим количеством взаимодействий на маркетплейсе NFT - -Этот запрос выполняет следующие действия: - -- Он находит аккаунт с наибольшим количеством уникальных взаимодействий с маркетплейсами NFT, что полезно для анализа активности на разных маркетплейсах. -- Поле маркетплейсов использует перечисление marketplace, что обеспечивает согласованность и валидацию значений маркетплейсов в ответе. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # Это поле возвращает значение перечисления, представляющее маркетплейс - } - } -} -``` - -#### Результаты - -Данный ответ включает информацию об аккаунте и перечень уникальных взаимодействий с маркетплейсом, где используются значения перечислений (enum) для обеспечения единообразной ясности: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Запрос 2: Наиболее активный маркетплейс для транзакций CryptoCoven - -Этот запрос выполняет следующие действия: - -- Он определяет маркетплейс с наибольшим объемом транзакций CryptoCoven. -- Он использует перечисление marketplace, чтобы гарантировать, что в ответе будут только допустимые типы маркетплейсов, что повышает надежность и согласованность ваших данных. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Результат 2 - -Ожидаемый ответ включает маркетплейс и соответствующее количество транзакций, используя перечисление для указания типа маркетплейса: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Запрос 3: Взаимодействия на маркетплейсе с высоким количеством транзакций - -Этот запрос выполняет следующие действия: - -- Он извлекает четыре самых активных маркетплейса с более чем 100 транзакциями, исключая маркетплейсы с типом "Unknown". -- Он использует перечисления в качестве фильтров, чтобы гарантировать, что включены только допустимые типы маркетплейсов, что повышает точность выполнения запроса. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Результат 3 - -Ожидаемый вывод включает маркетплейсы, которые соответствуют критериям, каждый из которых представлен значением перечисления: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Дополнительные ресурсы - -Дополнительную информацию можно найти в [репозитории] этого руководства (https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ru/subgraphs/cookbook/grafting.mdx b/website/src/pages/ru/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 8605468ff4e7..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Замените контракт и сохраните его историю с помощью Grafting ---- - -Из этого руководства Вы узнаете, как создавать и развертывать новые субграфы путем графтинга (переноса) существующих субграфов. - -## Что такое Grafting? - -При графтинге (переносе) повторно используются данные из существующего субрафа и начинается их индексация в более позднем блоке. Это может быть полезно в период разработки, чтобы быстро устранить простые ошибки в мэппинге или временно восстановить работу существующего субграфа после его сбоя. Кроме того, его можно использовать при добавлении в субграф функции, индексация которой с нуля занимает много времени. - -Перенесённый субграф может использовать схему GraphQL, которая не идентична схеме базового субграфа, а просто совместима с ней. Это должна быть автономно действующая схема субграфа, но она может отличаться от схемы базового субграфа следующим образом: - -- Она добавляет или удаляет типы объектов -- Она удаляет атрибуты из типов объектов -- Она добавляет обнуляемые атрибуты к типам объектов -- Она превращает необнуляемые атрибуты в обнуляемые -- Она добавляет значения в перечисления -- Она добавляет или удаляет интерфейсы -- Она изменяется в зависимости от того, под какой тип объектов реализован интерфейс - -Для получения дополнительной информации Вы можете перейти: - -- [Графтинг](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -В этом руководстве мы рассмотрим базовый случай использования. Мы заменим существующий контракт идентичным (с новым адресом, но с тем же кодом). Затем подключим существующий субграф к "базовому" субграфу, который отслеживает новый контракт. - -## Важное примечание о Grafting при обновлении до сети - -> **Предупреждение**: Рекомендуется не использовать графтинг для субграфов, опубликованных в сети The Graph - -### Почему это важно? - -Grafting — это мощная функция, которая позволяет «переносить» один субграф в другой, фактически перенося исторические данные из существующего субграфа в новую версию. Однако перенос субграфа из The Graph Network обратно в Subgraph Studio невозможен. - -### Лучшие практики - -**Первоначальная миграция**: при первом развертывании субграфа в децентрализованной сети рекомендуется не использовать графтинг. Убедитесь, что субграф стабилен и работает должным образом. - -**Последующие обновления**: когда Ваш субграф будет развернут и стабилен в децентрализованной сети, Вы можете использовать графтинг для будущих версий, чтобы облегчить переход и сохранить исторические данные. - -Соблюдая эти рекомендации, Вы минимизируете риски и обеспечите более плавный процесс миграции. - -## Создание существующего субграфа - -Создание субграфов — это важная часть работы с The Graph, более подробно описанная [здесь](/subgraphs/quick-start/). Для того чтобы иметь возможность создать и развернуть существующий субграф, используемый в этом руководстве, предоставлен следующий репозиторий: - -- [Пример репозитория субграфа](https://github.com/Shiyasmohd/grafting-tutorial) - -> Примечание: Контракт, используемый в субграфе, был взят из следующего [стартового набора Hackathon](https://github.com/schmidsi/hackathon-starterkit). - -## Определение манифеста субграфа - -Манифест субграфа `subgraph.yaml` определяет источники данных для субграфа, триггеры, которые представляют интерес, и функции, которые должны быть выполнены в ответ на эти триггеры. Ниже приведен пример манифеста субграфа, который Вы будете использовать: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- Источник данных `Lock` — это ABI и адрес контракта, которые мы получим при компиляции и развертывании контракта -- Сеть должна соответствовать индексируемой сети, к которой выполняется запрос. Поскольку мы работаем в тестнете Sepolia, сеть будет `sepolia`. -- Раздел `mapping` определяет триггеры, которые представляют интерес, и функции, которые должны быть выполнены в ответ на эти триггеры. В данном случае мы слушаем событие `Withdrawal` и вызываем функцию `handleWithdrawal`, когда оно срабатывает. - -## Определение Манифеста Grafting - -Grafting требует добавления двух новых элементов в исходный манифест субграфа: - -```yaml ---- -features: - - grafting # наименование функции -graft: - base: Qm... # идентификатор субграфа базового субграфа - block: 5956000 # номер блока -``` - -- `features:` — это список всех используемых [имен функций](/developing/creating-a-subgraph/#experimental-features). -- `graft:` — это отображение базового субграфа и блока, к которому применяется графтинг (перенос). `block` — это номер блока, с которого нужно начать индексирование. The Graph скопирует данные из базового субграфа до указанного блока включительно, а затем продолжит индексирование нового субграфа с этого блока. - -Значения `base` и `block` можно найти, развернув два субграфа: один для базового индексирования и один с графтингом - -## Развертывание базового субграфа - -1. Перейдите в [Subgraph Studio](https://thegraph.com/studio/) и создайте субграф в тестнете Sepolia с названием `graft-example` -2. Следуйте инструкциям в разделе `AUTH & DEPLOY` на странице своего субграфа в папке `graft-example` репозитория -3. После завершения убедитесь, что субграф правильно индексируется. Если Вы запустите следующую команду в The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Отклик будет подобным этому: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Убедившись, что субграф индексируется правильно, Вы можете быстро обновить его с помощью графтинга. - -## Развертывание grafting субграфа - -Замененный subgraph.yaml будет иметь новый адрес контракта. Это может произойти, когда Вы обновите свое децентрализованное приложение, повторно развернете контракт и т. д. - -1. Перейдите в [Subgraph Studio](https://thegraph.com/studio/) и создайте субграф в тестнете Sepolia с названием `graft-replacement` -2. Создайте новый манифест. `subgraph.yaml` для `graph-replacement` содержит другой адрес контракта и новую информацию о том, как он должен быть присоединен. Это `block` [последнего сгенерированного события], которое Вас интересует, вызванного старым контрактом, и `base` старого субграфа. Идентификатор субграфа `base` — это `Deployment ID` Вашего исходного субграфа `graph-example`. Вы можете найти его в Subgraph Studio. -3. Следуйте инструкциям в разделе `AUTH & DEPLOY` на странице своего субграфа в папке `graft-replacement` репозитория -4. После завершения убедитесь, что субграф правильно индексируется. Если Вы запустите следующую команду в The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Это должно привести к следующему результату: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -Вы можете увидеть, что субграф `graft-replacement` индексирует данные как из старого субграфа `graph-example`, так и из новых данных из нового адреса контракта. Исходный контракт сгенерировал два события `Withdrawal`, [Событие 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) и [Событие 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). Новый контракт сгенерировал одно событие `Withdrawal` после этого, [Событие 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). Две ранее индексируемые транзакции (События 1 и 2) и новая транзакция (Событие 3) были объединены в субграфе `graft-replacement`. - -Поздравляем! Вы успешно перенесли один субграф в другой. - -## Дополнительные ресурсы - -Если Вы хотите получить больше опыта в графтинге (переносе), вот несколько примеров популярных контрактов: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -Чтобы стать еще большим экспертом в области Graph, рассмотрите возможность изучения других способов обработки изменений в исходных данных. Альтернативы, такие как [Шаблоны источников данных](/developing/creating-a-subgraph/#data-source-templates), могут привести к аналогичным результатам - -> Примечание: Многие материалы из этой статьи были взяты из ранее опубликованной статьи об [Arweave](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ru/subgraphs/cookbook/near.mdx b/website/src/pages/ru/subgraphs/cookbook/near.mdx deleted file mode 100644 index ac22a9f8c015..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Создание субграфов на NEAR ---- - -Это руководство является введением в создание субграфов для индексирования смарт-контрактов на [блокчейне NEAR](https://docs.near.org/). - -## Что такое NEAR? - -[NEAR](https://near.org/) — это платформа для смарт-контрактов, предназначенная для создания децентрализованных приложений. Для получения дополнительной информации ознакомьтесь с [официальной документацией](https://docs.near.org/concepts/basics/protocol). - -## Что такое NEAR субграфы? - -The Graph предоставляет разработчикам инструменты для обработки событий блокчейна и упрощает доступ к полученным данным через API GraphQL, известный также как субграф. [Graph Node](https://github.com/graphprotocol/graph-node) теперь способен обрабатывать события NEAR, что позволяет разработчикам NEAR создавать субграфы для индексирования своих смарт-контрактов. - -Субграфы основаны на событиях, что означает, что они отслеживают и обрабатывают события в блокчейне. В настоящее время для субграфов NEAR поддерживаются два типа обработчиков: - -- Обработчики блоков: они запускаются для каждого нового блока -- Обработчики поступлений: запускаются каждый раз, когда сообщение выполняется в указанной учетной записи - -[Из документации NEAR](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Поступление - это единственный объект, к которому можно применить действие в системе. Когда мы говорим об "обработке транзакции" на платформе NEAR, это в конечном итоге означает "применение поступлений" в какой-то момент. - -## Создание NEAR субграфа - -`@graphprotocol/graph-cli` — это инструмент командной строки для создания и развертывания субграфов. - -`@graphprotocol/graph-ts` — это библиотека типов, специфичных для субграфов. - -Для разработки субграфов на платформе NEAR требуется `graph-cli` версии выше `0.23.0` и `graph-ts` версии выше `0.23.0`. - -> Построение NEAR субграфа очень похоже на построение субграфа, индексирующего Ethereum. - -Существует три аспекта определения субграфа: - -**subgraph.yaml:** манифест субграфа, определяющий источники данных и способы их обработки. NEAR является новым `kind` (типом) источника данных. - -**schema.graphql:** файл схемы, который определяет, какие данные хранятся в Вашем субграфе и как к ним можно обращаться через GraphQL. Требования для субграфов NEAR описаны в [существующей документации](/developing/creating-a-subgraph/#the-graphql-schema). - -**Мэппинги на AssemblyScript:** [код на AssemblyScript](/subgraphs/developing/creating/graph-ts/api/), который преобразует данные событий в элементы, определенные в Вашей схеме. Поддержка NEAR вводит специфичные для NEAR типы данных и новую функциональность для парсинга JSON. - -Во время разработки субграфа есть две ключевые команды: - -```bash -$ graph codegen # генерирует типы из файла схемы, указанного в манифесте -$ graph build # генерирует Web Assembly из файлов AssemblyScript и подготавливает все файлы субграфа в папке /build -``` - -### Определение манифеста субграфа - -Манифест субграфа (`subgraph.yaml`) определяет источники данных для субграфа, интересующие триггеры и функции, которые должны быть выполнены в ответ на эти триггеры. Пример манифеста субграфа для NEAR представлен ниже: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- Субграфы NEAR вводят новый тип источника данных (`near`) -- `network` должен соответствовать сети на хостинговой Graph Node. В Subgraph Studio майннет NEAR называется `near-mainnet`, а теснет NEAR — `near-testnet` -- Источники данных NEAR содержат необязательное поле `source.account`, которое представляет собой удобочитаемый идентификатор, соответствующий [учетной записи NEAR] (https://docs.near.org/concepts/protocol/account-model). Это может быть как основной аккаунт, так и суб-аккаунт. -- Источники данных NEAR вводят альтернативное необязательное поле `source.accounts`, которое содержит необязательные префиксы и суффиксы. Необходимо указать хотя бы один префикс или суффикс, они будут соответствовать любому аккаунту, начинающемуся или заканчивающемуся на значения из списка соответственно. Приведенный ниже пример будет совпадать с: `[app|good].*[morning.near|morning.testnet]`. Если необходим только список префиксов или суффиксов, другое поле можно опустить. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -Источники данных NEAR поддерживают два типа обработчиков: - -- `blockHandlers`: выполняется для каждого нового блока NEAR. `source.account` не требуется. -- `receiptHandlers`: выполняется при каждом получении, где `source.account` источника данных является получателем. Обратите внимание, что обрабатываются только точные совпадения ([субаккаунты](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) должны быть добавлены как независимые источники данных). - -### Определение схемы - -Определение схемы описывает структуру итоговой базы данных субграфа и отношения между объектами. Это не зависит от исходного источника данных. Более подробную информацию об определении схемы субграфа можно найти [здесь](/developing/creating-a-subgraph/#the-graphql-schema). - -### Мэппинги AssemblyScript - -Обработчики для обработки событий написаны на [AssemblyScript](https://www.assemblyscript.org/). - -Индексирование NEAR вводит специфичные для NEAR типы данных в [API AssemblyScript](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Всегда 0 для версии < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -Эти типы передаются в обработчики блоков и поступлений: - -- Обработчики блоков получат `Block` -- Обработчики поступлений получат `ReceiptWithOutcome` - -В остальном, весь [API для AssemblyScript](/subgraphs/developing/creating/graph-ts/api/) доступен разработчикам субграфов для NEAR во время выполнения мэппинга. - -Это включает в себя новую функцию для парсинга JSON — логи в NEAR часто выводятся как строковые JSON. Новая функция `json.fromString(...)` доступна в рамках [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api), что позволяет разработчикам легко обрабатывать эти логи. - -## Развертывание NEAR субграфа - -Как только Ваш субграф будет создан, наступает время развернуть его на Graph Node для индексирования. Субграфы NEAR можно развернуть на любом Graph Node версии `>=v0.26.x` (эта версия еще не отмечена и не выпущена). - -Subgraph Studio и Индексатор обновлений в The Graph Network в настоящее время поддерживают индексирование основной и тестовой сети NEAR в бета-версии со следующими именами сетей: - -- `near-mainnet` -- `near-testnet` - -Дополнительную информацию о создании и развертывании субграфов в Subgraph Studio можно найти [здесь](/deploying/deploying-a-subgraph-to-studio/). - -В качестве краткого примера — первый шаг заключается в "создании" Вашего субграфа — это нужно сделать только один раз. В Subgraph Studio это можно сделать на Вашей [панели управления](https://thegraph.com/studio/), выбрав опцию "Создать субграф". - -После того как субграф создан, его можно развернуть с помощью команды `graph deploy` в CLI: - -```sh -$ graph create --node # создает субграф на локальной Graph Node (в Subgraph Studio это делается через UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # загружает файлы сборки на указанную конечную точку IPFS, а затем разворачивает субграф на указанной Graph Node на основе хеша манифеста IPFS -``` - -Конфигурация ноды будет зависеть от того, где развертывается субграф. - -### Subgraph Studio - -```sh -graph auth -graph deploy -``` - -### Локальная Graph Node (на основе конфигурации по умолчанию) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Как только Ваш субграф будет развернут, он будет проиндексирован Graph Node. Вы можете проверить его прогресс, сделав запрос к самому субграфу: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Индексирование NEAR с помощью локальной Graph Node - -Запуск Graph Node, который индексирует NEAR, имеет следующие эксплуатационные требования: - -- Фреймворк NEAR Indexer с инструментарием Firehose -- Компонент(ы) NEAR Firehose -- Graph Node с настроенным эндпоинтом Firehose - -В ближайшее время мы предоставим более подробную информацию о запуске вышеуказанных компонентов. - -## Запрос NEAR субграфа - -Конечная точка GraphQL для субграфов NEAR определяется в соответствии с определением схемы и существующим интерфейсом API. Для получения дополнительной информации изучите [документацию по GraphQL API](/subgraphs/querying/graphql-api/). - -## Примеры субграфов - -Вот несколько примеров субграфов для справки: - -[Блоки NEAR](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[Подтверждения NEAR](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### Как работает бета-версия? - -Поддержка NEAR находится в стадии бета-тестирования, что означает, что в API могут быть внесены изменения, поскольку мы продолжаем работать над улучшением интеграции. Пожалуйста, напишите на электронную почту near@thegraph.com чтобы мы могли поддержать Вас в создании NEAR субграфов и держать в курсе последних разработок! - -### Может ли субграф индексировать чейны NEAR и EVM? - -Нет, субграф может поддерживать источники данных только из одного чейна/сети. - -### Могут ли субграфы реагировать на более конкретные триггеры? - -В настоящее время поддерживаются только триггеры Block и Receipt. Мы исследуем триггеры для вызовов функций к указанной учетной записи. Мы также заинтересованы в поддержке триггеров событий, когда NEAR обладает собственной поддержкой событий. - -### Будут ли срабатывать обработчики поступлений для учетных записей и их дочерних учетных записей? - -Если указано `account`, это будет соответствовать только точному имени аккаунта. Для того чтобы соответствовать субаккаунтам, можно указать поле `accounts`, с `suffixes` и `prefixes`, которые будут соответствовать аккаунтам и субаккаунтам. Например, следующее выражение будет соответствовать всем субаккаунтам `mintbase1.near`: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Могут ли субграфы NEAR выполнять вызовы просмотра аккаунтов NEAR во время мэппингов? - -Это не поддерживается. Мы оцениваем, требуется ли этот функционал для индексирования. - -### Могу ли я использовать шаблоны источников данных в своем субграфе NEAR? - -В настоящее время это не поддерживается. Мы оцениваем, требуется ли этот функционал для индексирования. - -### Субграфы Ethereum поддерживают «ожидающие» и «текущие» версии, как я могу развернуть «ожидающую» версию субграфа NEAR? - -Функционал ожидания еще не поддерживается для NEAR субграфов. Тем временем Вы можете развернуть новую версию на другом "именованном" субграфе, а затем, когда она будет синхронизирована с головным чейном, Вы можете повторно развернуть ее на свой основной "именованный" субграф, который будет использовать тот же базовый идентификатор развертывания, поэтому основной субграф будет мгновенно синхронизирован. - -### На мой вопрос нет ответа, где я могу получить дополнительную помощь в создании субграфов NEAR? - -Если это общий вопрос о разработке субграфов, дополнительную информацию можно найти в остальной части [документации для разработчиков](/subgraphs/quick-start/). В других случаях присоединяйтесь к [Discord-каналу The Graph Protocol](https://discord.gg/graphprotocol) и задавайте вопросы в канале #near или отправьте email на адрес near@thegraph.com. - -## Ссылки - -- [Документация для разработчиков NEAR](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ru/subgraphs/cookbook/polymarket.mdx b/website/src/pages/ru/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ru/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/ru/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 963188b67823..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Как обезопасить API-ключи с использованием серверных компонентов Next.js ---- - -## Обзор - -Мы можем использовать [серверные компоненты Next.js](https://nextjs.org/docs/app/building-your-application/rendering/server-components), чтобы должным образом защитить наш API-ключ от взлома во внешнем интерфейсе нашего децентрализованного приложения (dapp). Чтобы дополнительно повысить безопасность API-ключа, мы также можем [ограничить доступ к нашему API-ключу для определённых субграфов или доменов в Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -В этом руководстве мы рассмотрим, как создать серверный компонент Next.js, который запрашивает субграф, одновременно скрывая API-ключ от фронтенда. - -### Предостережения - -- Серверные компоненты Next.js не защищают API-ключи от утечки при атаках типа "отказ в обслуживании". -- Шлюзы The Graph Network имеют стратегии обнаружения и смягчения атак типа "отказ в обслуживании", однако использование серверных компонентов может ослабить эти защиты. -- Серверные компоненты Next.js вносят риски централизации, так как сервер может выйти из строя. - -### Почему это необходимо - -В стандартном React-приложении API-ключи, включённые в код внешнего интерфейса, могут быть раскрыты на стороне клиента, что созает угрозу безопасности. Хотя обычно используются файлы `.env`, они не обеспечивают полной защиты ключей, так как код React выполняется на стороне клиента, раскрывая API-ключ в заголовках. Серверные компоненты Next.js решают эту проблему, обрабатывая конфиденциальные операции на сервере. - -### Использование рендеринга на клиентской стороне для запроса к субграфу - -![Рендеринг на клиентской стороне](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- API-ключ от [Subgraph Studio](https://thegraph.com/studio) -- Базовые знания о Next.js и React. -- Существующий проект Next.js, который использует [App Router](https://nextjs.org/docs/app). - -## Пошаговое руководство - -### Шаг 1: Настройка переменных среды - -1. В корневой папке нашего проекта Next.js создайте файл `.env.local`. -2. Добавьте наш API-ключ: `API_KEY=`. - -### Шаг 2: Создание серверного компонента - -1. В директории `components` создайте новый файл `ServerComponent.js`. -2. Используйте приведённый пример кода для настройки серверного компонента. - -### Шаг 3: Реализация API-запроса на стороне сервера - -В файл `ServerComponent.js` добавьте следующий код: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Шаг 4: Использование серверного компонента - -1. В файл страницы (например, `pages/index.js`) импортируйте `ServerComponent`. -2. Отрендерите компонент: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Шаг 5: Запуск и тестирование нашего децентрализованного приложения (Dapp) - -Запустите наше приложение Next.js с помощью команды `npm run dev`. Убедитесь, что серверный компонент запрашивает данные, не раскрывая API-ключ. - -![Рендеринг на стороне сервера](/img/api-key-server-side-rendering.png) - -### Заключение - -Используя серверные компоненты Next.js, мы эффективно скрыли ключ API от клиентской стороны, улучшив безопасность нашего приложения. Этот метод гарантирует, что чувствительные операции обрабатываются на сервере, вдали от потенциальных уязвимостей на стороне клиента. В заключение, не забудьте ознакомиться с [другими мерами безопасности для ключей API](/subgraphs/querying/managing-api-keys/), чтобы повысить уровень безопасности своего ключа API. diff --git a/website/src/pages/ru/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/ru/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 8f2e67289d77..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Быстрая и простая отладка субграфа с использованием форков ---- - -Как и многие системы, обрабатывающие большие объемы данных, Индексаторы The Graph (Graph Nodes) могут занять достаточно много времени для синхронизации Вашего субграфа с целевым блокчейном. Несоответствие между быстрыми изменениями, направленными на отладку, и долгим временем ожидания, необходимым для индексирования, является крайне непродуктивным, и мы прекрасно осознаем эту проблему. Поэтому мы представляем **форкинг субграфа**, разработанный [LimeChain](https://limechain.tech/), и в этой статье я покажу, как эту функцию можно использовать для значительного ускорения отладки субграфов! - -## И так, что это? - -**Форкинг субграфа** — это процесс ленивой загрузки объектов из _другого_ хранилища субграфа (обычно удалённого). - -В контексте отладки **форкинг субграфа** позволяет Вам отлаживать Ваш неудавшийся субграф на блоке _X_, не дожидаясь синхронизации с блоком _X_. - -## Что? Как? - -Когда Вы развертываете субграф на удалённой Graph Node для индексирования, и он терпит неудачу на блоке _X_, хорошая новость заключается в том, что Graph Node всё равно будет обслуживать запросы GraphQL, используя своё хранилище, которое синхронизировано с блоком _X_. Это здорово! Таким образом, мы можем воспользоваться этим "актуальным" хранилищем, чтобы исправить ошибки, возникающие при индексировании блока _X_. - -Короче говоря, мы собираемся _форкать неработающий субграф_ с удалённой Graph Node, которая гарантированно имеет индексированный субграф до блока _X_, чтобы предоставить локально развернутому субграфу, который отлаживается на блоке _X_, актуальное состояние индексирования. - -## Пожалуйста, покажите мне какой-нибудь код! - -Чтобы сосредоточиться на отладке субграфа, давайте упростим задачу и продолжим с [примером субграфа](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar), который индексирует смарт-контракт Ethereum Gravity. - -Вот обработчики, определённые для индексирования `Gravatar`, без каких-либо ошибок: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Ой, как неприятно! Когда я развертываю свой идеально выглядящий субграф в [Subgraph Studio](https://thegraph.com/studio/), он выдаёт ошибку _"Gravatar not found!"_. - -Обычный способ попытаться исправить это: - -1. Внести изменения в источник мэппингов, которые, по Вашему мнению, решат проблему (в то время как я знаю, что это не так). -2. Перезапустить развертывание своего субграфа в [Subgraph Studio](https://thegraph.com/studio/) (или на другую удалённую Graph Node). -3. Подождать, пока он синхронизируется. -4. Если он снова сломается, вернуться к пункту 1, в противном случае: Ура! - -Действительно, это похоже на обычный процесс отладки, но есть один шаг, который ужасно замедляет процесс: _3. Ждите, пока завершится синхронизация._ - -Используя **форк субграфа**, мы можем фактически устранить этот шаг. Вот как это выглядит: - -0. Запустите локальную Graph Node с помощью **_соответстсвующего набора fork-base_**. -1. Внесите изменения в источник мэппингов, которые, по Вашему мнению, решат проблему. -2. Произведите развертывание на локальной Graph Node, **_форкнув неудачно развернутый субграф_** и **_начав с проблемного блока_**. -3. Если он снова сломается, вернитесь к пункту 1, в противном случае: Ура! - -Сейчас у Вас может появиться 2 вопроса: - -1. fork-base - что это??? -2. Форкнуть кого?! - -И я вам отвечаю: - -1. `fork-base` - это «базовый» URL, при добавлении которого к _subgraph id_ результирующий URL (`/`) является действительной конечной точкой GraphQL для хранилища субграфа. -2. Форкнуть легко, не нужно напрягаться: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Также не забудьте установить поле `dataSources.source.startBlock` в манифесте субграфа на номер проблемного блока, чтобы пропустить индексирование ненужных блоков и воспользоваться преимуществами форка! - -Итак, вот что я делаю: - -1. Я запускаю локальную Graph Node ([вот как это сделать](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) с опцией `fork-base`, установленной в: `https://api.thegraph.com/subgraphs/id/`, поскольку я буду форкать субграф, тот самый, который я ранее развертывал, с [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. После тщательной проверки я замечаю, что существует несоответствие в представлениях `id`, используемых при индексировании `Gravatar` в двух моих обработчиках. В то время как `handleNewGravatar` конвертирует его в hex (`event.params.id.toHex()`), `handleUpdatedGravatar` использует int32 (`event.params.id.toI32()`), что приводит к тому, что `handleUpdatedGravatar` завершается ошибкой и появляется сообщение "Gravatar not found!". Я заставляю оба обработчика конвертировать `id` в hex. -3. После внесения изменений я развертываю свой субграф на локальной Graph Node, **выполняя форк неудавшегося субграфа** и устанавливаю значение `dataSources.source.startBlock` равным `6190343` в файле `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. Я проверяю логи, созданные локальной Graph Node, и, ура!, кажется, все работает. -5. Я развертываю свой теперь свободный от ошибок субграф на удаленной Graph Node и живу долго и счастливо! (но без картошки) diff --git a/website/src/pages/ru/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/ru/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index f81fe52608e8..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Генератор кода безопасного субграфа ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) — это инструмент для генерации кода, который создает набор вспомогательных функций из схемы GraphQL проекта. Он гарантирует, что все взаимодействия с объектами в Вашем субграфе будут полностью безопасными и последовательными. - -## Зачем интегрироваться с Subgraph Uncrashable? - -- **Непрерывная работа**. Ошибки в обработке объектов могут привести к сбоям субграфов, что нарушит работу проектов, зависящих от The Graph. Настройте вспомогательные функции, чтобы Ваши субграфы оставались «непотопляемыми» и обеспечивали стабильную работу. - -- **Полная безопасность**. Обычные проблемы при разработке субграфов — это ошибки загрузки неопределенных элементов, неинициализированные или неустановленные значения элементов, а также гонки при загрузке и сохранении элементов. Убедитесь, что все взаимодействия с объектами полностью атомарны. - -- **Настройка пользователем**. Установите значения по умолчанию и настройте уровень проверок безопасности, который соответствует потребностям Вашего индивидуального проекта. Записываются предупреждающие логи, указывающие на то, где произходит нарушение логики субграфа, что помогает исправить проблему и обеспечить точность данных. - -**Ключевые особенности** - -- Инструмент генерации кода поддерживает **все** типы субграфов и настраивается таким образом, чтобы пользователи могли задать разумные значения по умолчанию. Генерация кода будет использовать эту настройку для создания вспомогательных функций в соответствии с требованиями пользователей. - -- Фреймворк также включает в себя способ создания пользовательских, но безопасных функций установки для групп переменных объектов (через config-файл). Таким образом, пользователь не сможет загрузить/использовать устаревшую graph entity, и также не сможет забыть о сохранении или установке переменной, которая требуется функцией. - -- Предупреждающие логи записываются как логи, указывающие на нарушение логики субграфа, чтобы помочь устранить проблему и обеспечить точность данных. - -Subgraph Uncrashable можно запустить как необязательный флаг с помощью команды Graph CLI codegen. - -```sh -graph codegen -u [options] [] -``` - -Ознакомьтесь с [документацией по subgraph uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/docs/) или посмотрите этот [видеоруководство](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial), чтобы узнать больше и начать разрабатывать более безопасные субграфы. diff --git a/website/src/pages/ru/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/ru/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 570aab81debc..000000000000 --- a/website/src/pages/ru/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Перенос в The Graph ---- - -Быстро обновите свои субграфы с любой платформы до [децентрализованной сети The Graph](https://thegraph.com/networks/). - -## Преимущества перехода на The Graph - -- Используйте тот же субграф, который уже используют ваши приложения, с миграцией без времени простоя. -- Повышайте надежность благодаря глобальной сети, поддерживаемой более чем 100 индексаторами. -- Получайте молниеносную поддержку для субграфов 24/7 от дежурной команды инженеров. - -## Обновите свой субграф до The Graph за 3 простых шага - -1. [Настройте свою среду Studio](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Разверните свой субграф в Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Опубликуйте в сети The Graph](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Настройте свою среду в Studio - -### Создайте субграф в Subgraph Studio - -- Перейдите в [Subgraph Studio](https://thegraph.com/studio/) и подключите свой кошелек. -- Нажмите "Создать субграф". Рекомендуется называть субграф с использованием Заглавного регистра: "Subgraph Name Chain Name". - -> Примечание: после публикации имя субграфа будет доступно для редактирования, но для этого каждый раз потребуется действие на он-чейне, поэтому выберите подходящее имя сразу. - -### Установите Graph CLI - -Для использования Graph CLI у Вас должны быть установлены [Node.js](https://nodejs.org/) и выбранный Вами менеджер пакетов (`npm` или `pnpm`). Проверьте [самую последнюю](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) версию CLI. - -Выполните следующую команду на своем локальном компьютере: - -Использование [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Используйте следующую команду для создания субграфа в Studio с помощью CLI: - -```sh -graph init --product subgraph-studio -``` - -### Аутентификация Вашего субграфа - -В Graph CLI используйте команду `auth`, как показано в Subgraph Studio: - -```sh -graph auth -``` - -## 2. Разверните свой субграф в Studio - -Если у Вас есть исходный код, Вы можете с легкостью развернуть его в Studio. Если его нет, вот быстрый способ развернуть Ваш субграф. - -В Graph CLI выполните следующую команду: - -```sh -graph deploy --ipfs-hash - -``` - -> **Примечание:** Каждый субграф имеет хэш IPFS (идентификатор развертывания), который выглядит так: "Qmasdfad...". Для развертывания просто используйте этот **IPFS хэш**. Вам будет предложено ввести версию (например, v0.0.1). - -## 3. Опубликуйте свой субграф в The Graph Network - -![кнопка публикации](/img/publish-sub-transfer.png) - -### Запросите Ваш Субграф - -> Для того чтобы привлечь около 3 индексаторов для запроса Вашего субграфа, рекомендуется зафиксировать как минимум 3000 GRT. Чтобы узнать больше о кураторстве, ознакомьтесь с разделом [Кураторство](/resources/roles/curating/) на платформе The Graph. - -Вы можете начать [запрашивать](/subgraphs/querying/introduction/) любой субграф, отправив запрос GraphQL на конечную точку URL-адреса его запроса, которая расположена в верхней части страницы его эксплорера в Subgraph Studio. - -#### Пример - -[Субграф CryptoPunks на Ethereum](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) от Messari: - -![URL запроса](/img/cryptopunks-screenshot-transfer.png) - -URL запроса для этого субграфа: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**Ваш-api-ключ**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Теперь Вам нужно просто вставить **Ваш собственный API-ключ**, чтобы начать отправлять GraphQL-запросы на эту конечную точку. - -### Получение собственного API-ключа - -Вы можете создать API-ключи в Subgraph Studio в меню «API Keys» в верхней части страницы: - -![API ключи](/img/Api-keys-screenshot.png) - -### Мониторинг статуса субграфа - -После обновления Вы сможете получить доступ к своим субграфам и управлять ими в [Subgraph Studio](https://thegraph.com/studio/) и исследовать все субграфы в [The Graph Explorer](https://thegraph.com/networks/). - -### Дополнительные ресурсы - -- Чтобы быстро создать и опубликовать новый субграф, ознакомьтесь с [Руководством по быстрому старту](/subgraphs/quick-start/). -- Чтобы исследовать все способы оптимизации и настройки своего субграфа для улучшения производительности, читайте больше о [создании субграфа здесь](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ru/subgraphs/guides/_meta.js b/website/src/pages/ru/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/ru/subgraphs/guides/arweave.mdx b/website/src/pages/ru/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/ru/subgraphs/guides/enums.mdx b/website/src/pages/ru/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ru/subgraphs/guides/grafting.mdx b/website/src/pages/ru/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ru/subgraphs/guides/near.mdx b/website/src/pages/ru/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ru/subgraphs/guides/polymarket.mdx b/website/src/pages/ru/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ru/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/ru/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ru/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/ru/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ru/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/ru/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ru/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/ru/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/ru/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/sv/subgraphs/_meta-titles.json b/website/src/pages/sv/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/sv/subgraphs/_meta-titles.json +++ b/website/src/pages/sv/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/sv/subgraphs/_meta.js b/website/src/pages/sv/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/sv/subgraphs/_meta.js +++ b/website/src/pages/sv/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/sv/subgraphs/cookbook/_meta.js b/website/src/pages/sv/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/sv/subgraphs/cookbook/arweave.mdx b/website/src/pages/sv/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 8a78a4ffa184..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Bygga subgrafer på Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -I den här guiden kommer du att lära dig hur du bygger och distribuerar subgrafer för att indexera Weaver-blockkedjan. - -## Vad är Arweave? - -Arweave-protokollet tillåter utvecklare att lagra data permanent och det är den största skillnaden mellan Arweave och IPFS, där IPFS saknar funktionen; beständighet och filer lagrade på Arweave kan inte ändras eller raderas. - -Arweave har redan byggt ett flertal bibliotek för att integrera protokollet i ett antal olika programmeringsspråk. För mer information kan du kolla: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## Vad är Arweave-subgrafer? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Bygga en Arweave-subgraf - -För att kunna bygga och distribuera Arweave Subgraphs behöver du två paket: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Subgraphs komponenter - -Det finns tre komponenter i en subgraf: - -### 1. Manifest - `subgraph.yaml` - -Definierar datakällorna av intresse och hur de ska behandlas. Arweave är en ny typ av datakälla. - -### 2. Schema - `schema.graphql` - -Här definierar du vilken data du vill kunna fråga efter att du har indexerat din subgrafer med GraphQL. Detta liknar faktiskt en modell för ett API, där modellen definierar strukturen för en begäran. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -Detta är logiken som avgör hur data ska hämtas och lagras när någon interagerar med datakällorna du lyssnar på. Data översätts och lagras utifrån det schema du har listat. - -Under subgrafutveckling finns det två nyckelkommandon: - -``` -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -## Definition av subgraf manifestet - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave datakällor introducerar ett valfritt source.owner fält, som är den publika nyckeln till en Arweave plånbok - -Arweave datakällor stöder två typer av hanterare: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> De source.owner kan vara ägarens adress eller deras publika nyckel. -> -> Transaktioner är byggstenarna i Arweave permaweb och de är objekt skapade av slutanvändare. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Schema Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript mappningar - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Fråga efter en Arweave-subgraf - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Exempel på subgrafer - -Här är ett exempel på subgraf som referens: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Kan en subgraf indexera Arweave och andra kedjor? - -Nej, en subgraf kan bara stödja datakällor från en kedja/nätverk. - -### Kan jag indexera de lagrade filerna på Arweave? - -För närvarande indexerar The Graph bara Arweave som en blockkedja (dess block och transaktioner). - -### Kan jag identifiera Bundlr buntar i min subgraf? - -Detta stöds inte för närvarande. - -### Hur kan jag filtrera transaktioner till ett specifikt konto? - -Source.owner kan vara användarens publika nyckel eller kontoadress. - -### Vad är det aktuella krypteringsformatet? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/sv/subgraphs/cookbook/enums.mdx b/website/src/pages/sv/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 2fc0efcc5831..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Ytterligare resurser - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/sv/subgraphs/cookbook/grafting.mdx b/website/src/pages/sv/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index e43fd73014c3..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Byt ut ett kontrakt och behåll dess historia med ympning ---- - -I den här guiden kommer du att lära dig hur du bygger och distribuerar nya subgrafer genom att ympa befintliga subgrafer. - -## Vad är ympning? - -Ympning återanvänder data från en befintlig subgraf och börjar indexera den vid ett senare block. Detta är användbart under utveckling för att snabbt komma förbi enkla fel i mappningarna eller för att tillfälligt få en befintlig subgraf att fungera igen efter att den har misslyckats. Det kan också användas när du lägger till en funktion till en subgraf som tar lång tid att indexera från början. - -Den ympade subgrafen kan använda ett GraphQL-schema som inte är identiskt med det i bas subgrafen, utan bara är kompatibelt med det. Det måste vara ett giltigt subgraf schema i sig, men kan avvika från bas undergrafens schema på följande sätt: - -- Den lägger till eller tar bort entitetstyper -- Det tar bort attribut från entitetstyper -- Det tar bort attribut från entitetstyper -- Det förvandlar icke-nullbara attribut till nullbara attribut -- Det lägger till värden till enums -- Den lägger till eller tar bort gränssnitt -- Det ändrar för vilka entitetstyper ett gränssnitt implementeras - -För mer information kan du kontrollera: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Viktig anmärkning om ympning vid uppgradering till nätverket - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Varför är detta viktigt? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Bästa praxis - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -Genom att följa dessa riktlinjer minimerar du riskerna och säkerställer en smidigare migreringsprocess. - -## Bygga en befintlig subgraf - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Definition av subgraf manifestet - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Ympnings manifest Definition - -Ympning kräver att två nya objekt läggs till i det ursprungliga subgraf manifestet: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Distribuera Bas Subgraf - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. När du är klar kontrollerar du att subgrafen indexerar korrekt. Om du kör följande kommando i The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Den returnerar ungefär så här: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -När du har verifierat att subgrafen indexerar korrekt kan du snabbt uppdatera subgrafen med ympning. - -## Utplacering av ympning subgraf - -Transplantatersättningen subgraph.yaml kommer att ha en ny kontraktsadress. Detta kan hända när du uppdaterar din dapp, omdisponerar ett kontrakt, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. När du är klar kontrollerar du att subgrafen indexerar korrekt. Om du kör följande kommando i The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Det bör returnera följande: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Ytterligare resurser - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/sv/subgraphs/cookbook/near.mdx b/website/src/pages/sv/subgraphs/cookbook/near.mdx deleted file mode 100644 index 833a4b7c997d..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Bygger subgrafer på NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## Vad är NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## Vad är NEAR subgrafer? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Blockhanterare: dessa körs på varje nytt block -- Kvittohanterare: körs varje gång ett meddelande körs på ett angivet konto - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Ett kvitto är det enda handlingsbara objektet i systemet. När vi pratar om att "bearbeta en transaktion" på NEAR plattformen betyder det så småningom att "tillämpa kvitton" någon gång. - -## Att bygga en NEAR Subgraf - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Att bygga en NEAR subgraf är mycket lik att bygga en subgraf som indexerar Ethereum. - -Det finns tre aspekter av subgraf definition: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -Under subgrafutveckling finns det två nyckelkommandon: - -```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -### Definition av subgraf manifestet - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR datakällor stöder två typer av hanterare: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Schema Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript mappningar - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Utplacera en NEAR Subgraf - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -Nodkonfigurationen beror på var subgrafen distribueras. - -### Subgraf Studion - -```sh -graph auth -graph deploy -``` - -### Lokal graf nod (baserat på standardkonfiguration) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -När din subgraf har distribuerats kommer den att indexeras av Graph Node. Du kan kontrollera dess framsteg genom att fråga själva subgrafen: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexering av NEAR med en lokal grafnod - -Att köra en Graph Node som indexerar NEAR har följande operativa krav: - -- NEAR Indexer Framework med Firehose-instrumentering -- NEAR Brandslangskomponent(er) -- Graf Nod med Firehose ändpunkt konfigurerad - -Vi kommer snart att ge mer information om hur du kör ovanstående komponenter. - -## Fråga efter en NEAR subgraf - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Exempel på subgrafer - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### Hur fungerar betan? - -NEAR stödet är i beta, vilket innebär att det kan bli ändringar i API:t när vi fortsätter att arbeta med att förbättra integrationen. Skicka ett e-postmeddelande till near@thegraph.com så att vi kan hjälpa dig att bygga NEAR subgrafer och hålla dig uppdaterad om den senaste utvecklingen! - -### Kan en subgraf indexera både NEAR och EVM kedjor? - -Nej, en subgraf kan bara stödja datakällor från en kedja/nätverk. - -### Kan subgrafer reagera på mer specifika triggers? - -För närvarande stöds endast blockerings- och kvittoutlösare. Vi undersöker utlösare för funktionsanrop till ett specificerat konto. Vi är också intresserade av att stödja eventutlösare, när NEAR har inbyggt eventsupport. - -### Kommer kvittohanterare att utlösa för konton och deras underkonton? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Kan NEAR subgrafer göra visningsanrop till NEAR konton under mappningar? - -Detta stöds inte. Vi utvärderar om denna funktionalitet krävs för indexering. - -### Kan jag använda data källmallar i min NEAR subgraf? - -Detta stöds inte för närvarande. Vi utvärderar om denna funktionalitet krävs för indexering. - -### Ethereum subgrafer stöder "väntande" och "nuvarande" versioner, hur kan jag distribuera en "väntande" version av en NEAR subgraf? - -Väntande funktionalitet stöds ännu inte för NEAR subgrafer. Under tiden kan du distribuera en ny version till en annan "namngiven" subgraf, och när den sedan synkroniseras med kedjehuvudet kan du distribuera om till din primära "namngivna" subgraf, som kommer att använda samma underliggande implementerings-ID, så huvudsubgrafen synkroniseras omedelbart. - -### Min fråga har inte besvarats, var kan jag få mer hjälp med att bygga NEAR subgrafer? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## Referenser - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/sv/subgraphs/cookbook/polymarket.mdx b/website/src/pages/sv/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/sv/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/sv/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index a9e82a6baa72..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## Översikt - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/sv/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/sv/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index aee8ecf8791f..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Snabb och enkel subgraf felsökning med gafflar ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## Ok, vad är det? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## Vad?! Hur? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## Snälla, visa mig lite kod! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -Det vanliga sättet att försöka fixa är: - -1. Gör en förändring i mappningskällan, som du tror kommer att lösa problemet (även om jag vet att det inte kommer att göra det). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Vänta tills det synkroniseras. -4. Om den går sönder igen gå tillbaka till 1, annars: Hurra! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Gör en ändring i mappningskällan som du tror kommer att lösa problemet. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. Om den går sönder igen, gå tillbaka till 1, annars: Hurra! - -Nu kanske du har 2 frågor: - -1. gaffelbas vad??? -2. Forking vem?! - -Och jag svarar: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Gaffling är lätt, du behöver inte svettas: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -Så här är vad jag gör: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/sv/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/sv/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index ce8e87ecfd46..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Säker subgraf kodgenerator ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Varför integrera med Subgraf Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- Ramverket innehåller också ett sätt (via konfigurationsfilen) att skapa anpassade, men säkra, sätterfunktioner för grupper av entitetsvariabler. På så sätt är det omöjligt för användaren att ladda/använda en inaktuell grafenhet och det är också omöjligt att glömma att spara eller ställa in en variabel som krävs av funktionen. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable kan köras som en valfri flagga med kommandot Graph CLI codegen. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/sv/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/sv/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index f06ed1722258..000000000000 --- a/website/src/pages/sv/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Exempel - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Ytterligare resurser - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/sv/subgraphs/guides/_meta.js b/website/src/pages/sv/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/sv/subgraphs/guides/arweave.mdx b/website/src/pages/sv/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/sv/subgraphs/guides/enums.mdx b/website/src/pages/sv/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/sv/subgraphs/guides/grafting.mdx b/website/src/pages/sv/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/sv/subgraphs/guides/near.mdx b/website/src/pages/sv/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/sv/subgraphs/guides/polymarket.mdx b/website/src/pages/sv/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/sv/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/sv/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/sv/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/sv/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/sv/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/sv/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/sv/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/sv/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/sv/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/tr/subgraphs/_meta-titles.json b/website/src/pages/tr/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/tr/subgraphs/_meta-titles.json +++ b/website/src/pages/tr/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/tr/subgraphs/_meta.js b/website/src/pages/tr/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/tr/subgraphs/_meta.js +++ b/website/src/pages/tr/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/tr/subgraphs/cookbook/_meta.js b/website/src/pages/tr/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/tr/subgraphs/cookbook/arweave.mdx b/website/src/pages/tr/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 8495fd68c39b..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Arweave Üzerinde Subgraphlar Oluşturma ---- - -> Graph Düğümü ve Subgraph Studio'daki Arweave desteği beta aşamasındadır: Arweave subgraph'ları oluşturma konusunda herhangi bir sorunuz varsa lütfen [Discord](https://discord.gg/graphprotocol) üzerinden bizimle iletişime geçin! - -Bu rehberde, Arweave blok zincirini indekslemek için nasıl Subgraphs oluşturacağınızı ve dağıtacağınızı öğreneceksiniz. - -## Arweave Nedir? - -Arweave protokolü geliştiricilere verileri kalıcı olarak depolama imkanı sağlar ve bu, Arweave ile IPFS arasındaki temel farktır. IPFS'de böyle bir özellik bulunmaz; yani IPFS'te depolanan dosyalar kalıcı değildir ve Arweave'de depolanan dosyalar değiştirilemez veya silinemez. - -Arweave, protokolü farklı programlama dillerine entegre etmek için halihazırda çok sayıda kütüphane oluşturmuştur. Daha fazla bilgi için şurayı kontrol edebilirsiniz: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Kaynakları](https://www.arweave.org/build) - -## Arweave Subgraphları Nedir? - -The Graph, "Subgraph" adı verilen özel açık API'ler oluşturmanıza olanak tanır. Subgraph'ler, endeksleyicilere (sunucu operatörleri) bir blokzincirinde hangi verilerin endeksleneceğini ve sunucularında saklanacağını belirtmek için kullanılır. Böylece [GraphQL](https://graphql.org/) kullanarak bu verilere istediğiniz zaman sorgu yapabilirsiniz. - -[Graph Düğümü](https://github.com/graphprotocol/graph-node) artık Arweave protokolündeki verileri endeksleyebiliyor. Mevcut entegrasyon yalnızca Arweave'i bir blokzinciri olarak (bloklar ve işlemler) endekslemekte olup, henüz depolanan dosyaları endekslememektedir. - -## Bir Arweave Subgraph'ı Oluşturma - -Arweave Subgraphları oluşturabilmek ve dağıtabilmek için iki pakete ihtiyacınız vardır: - -1. `@graphprotocol/graph-cli` 0.30.2 sürümünün üzerinde - Bu, subgraph'ler oluşturmak ve dağıtmak için kullanılan bir komut satırı aracıdır. [Buraya] (https://www.npmjs.com/package/@graphprotocol/graph-cli) tıklayarak npm kullanarak indirebilirsiniz. -2. `@graphprotocol/graph-ts` 0.27.0 sürümünün üzerinde - Bu, subgraph'e özgü türler içeren bir kütüphanedir. [Buraya] (https://www.npmjs.com/package/@graphprotocol/graph-ts) tıklayarak npm kullanarak indirebilirsiniz. - -## Subgraph'ın bileşenleri - -Bir subgraph'ın üç bileşeni vardır: - -### 1. Manifesto - `subgraph.yaml` - -İlgilenilen veri kaynaklarını ve bunların nasıl işlenmesi gerektiğini tanımlar. Arweave yeni bir veri kaynağı türüdür. - -### 2. Şema - `schema.graphql` - -Burada, GraphQL kullanarak Subgraph'ınızı indeksledikten sonra hangi verileri sorgulayabilmek istediğinizi tanımlarsınız. Bu aslında, modelin bir istek gövdesinin yapısını tanımladığı bir API modeline benzer. - -Arweave subgraph'leri için gereksinimler [mevcut dokümanlarda](/developing/creating-a-subgraph/#the-graphql-schema) ele alınmıştır. - -### 3. AssemblyScript Eşlemeleri - `mapping.ts` - -Bu, birisi sizin etkinliklerini gözlemlediğiniz veri kaynaklarıyla etkileşimde bulunduğunda verinin nasıl alınması ve depolanması gerektiğini belirleyen mantıktır. Veri çevrilir ve belirttiğiniz şemaya göre depolanır. - -Subgraph geliştirme sırasında iki anahtar komut vardır: - -``` -$ graph codegen # manifest'de tanımlanan şema dosyasından tipleri üretir -$ graph build # AssemblyScript dosyalarından Web Assembly oluşturur ve tüm subgraph dosyalarını bir /build klasöründe hazırlar -``` - -## Subgraph Manifest Tanımı - -Subgraph manifestosu subgraph.yaml; subgraph'in veri kaynaklarını, ilgili tetikleyicileri ve bu tetikleyicilere yanıt olarak çalıştırılması gereken fonksiyonları tanımlar. Aşağıda, bir Arweave subgraph'i için örnek bir subgraph manifestosu bulunmaktadır: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # şema dosyasına bağlantı -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # Graph yalnızca Arweave Ana Ağı'nı destekler - source: - owner: 'ID-OF-AN-OWNER' # Bir Arweave cüzdanının açık anahtarı - startBlock: 0 # indekslemeyi zincir oluşumundan başlatmak için bunu 0 olarak ayarlayın - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # Assemblyscript eşleştirmelerinin bulunduğu dosyaya bağlantı - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # eşleştirme dosyasındaki fonksiyon adı - transactionHandlers: - - handler: handleTx # eşleştirme dosyasındaki fonksiyon adı -``` - -- Arweave subgraph'leri, yeni bir veri kaynağı türü (`arweave`) sunar -- Ağ, sağlayıcı Graph Düğümü üzerindeki bir ağa karşılık gelmelidir. Subgraph Studio'da, Arweave'in ana ağı `arweave-mainnet` olarak tanımlanır -- Arweave veri kaynakları, bir Arweave cüzdanının genel anahtarı olan opsiyonel bir source.owner alanı sunar - -Arweave veri kaynakları iki tür işleyiciyi destekler: - -- `blockHandlers` - Her yeni Arweave blokunda çalıştırılır. source.owner belirtilmesi gerekmez. -- `transactionHandlers` - Veri kaynağının sahibinin source.owner olduğu her işlemde çalıştırılır. Şu anda ` transactionHandlers` için bir sahip (owner) gereklidir. Kullanıcılar tüm işlemleri gerçekleştirmek istiyorlarsa `source.owner` olarak boş dize "" sağlamalıdırlar - -> source.owner, sahibin adresi veya Genel Anahtarı olabilir. -> -> İşlemler Arweave permaweb'in yapı taşlarıdır ve son kullanıcılar tarafından oluşturulan nesnelerdir. -> -> Not: [Irys (önceden Bundlr)](https://irys.xyz/) işlemleri henüz desteklenmemektedir. - -## Şema Tanımı - -Şema tanımı, oluşan subgraph veritabanının yapısını ve varlıklar arasındaki ilişkileri tanımlar. Bu ilişki orijinal veri kaynağından bağımsızdır. Subgraph şema tanımı hakkında daha fazla detay [burada](/developing/creating-a-subgraph/#the-graphql-schema) bulunmaktadır. - -## AssemblyScript Eşlemeleri - -Olayları işlemek için kullanılan işleyiciler [AssemblyScript](https://www.assemblyscript.org/) ile yazılmıştır. - -Arweave endeksleme, [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) için Arweave'e özgü veri türlerini tanıtır. - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Blok işleyiciler bir `Block` alırken, işlemler bir `Transaction` alır. - -Arweave Subgraph'inin eşleştirmelerini yazmak, bir Ethereum Subgraph'inin eşleştirmelerini yazmaya oldukça benzerdir. Daha fazla bilgi için [buraya](/developing/creating-a-subgraph/#writing-mappings) tıklayın. - -## Subgraph Studio'da Arweave Subgraph'i Dağıtma - -Subgraph Studio panelinizde subgraph'iniz oluşturulduktan sonra onu `graph deploy` CLI komutunu kullanarak dağıtabilirsiniz. - -```bash -graph deploy --access-token -``` - -## Arweave Subgraph'ını Sorgulama - -Arweave subgraph'leri için GraphQL endpoint'i, mevcut API arayüzüyle şema tanımına göre belirlenir. Daha fazla bilgi için [GraphQL API dokümantasyonuna](/subgraphs/querying/graphql-api/) göz atın. - -## Örnek Subgraph'ler - -İşte referans olması için örnek bir subgraph: - -- [Arweave için örnek subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Bir subgraph Arweave ve diğer zincirleri indeksleyebilir mi? - -Hayır, bir subgraph yalnızca bir zincirden/ağdan veri kaynaklarını destekleyebilir. - -### Depolanmış dosyaları Arweave üzerinde indeksleyebilir miyim? - -Şu anda Graph, Arweave'yi yalnızca bir blok zinciri (blokları ve işlemleri) olarak indekslemektedir. - -### Subgraph'ımdaki Bundlr paketlerini tanımlayabilir miyim? - -Bu şu anda desteklenmemektedir. - -### İşlemleri belirli bir hesaba özel olarak nasıl filtreleyebilirim? - -source.owner kullanıcının genel anahtarı veya hesap adresi olabilir. - -### Mevcut şifreleme formatı nedir? - -Veriler genellikle Bytes olarak eşleştirmelere aktarılır ve doğrudan kaydedilirse subgraph'te hex formatında (ör. blok ve işlem hash'leri) döner. [Arweave Explorer](https://viewblock.io/arweave/) gibi blok gezginlerinde görüntülenenlerle denkleştirmek için eşlemelerinizi `base64` veya `base64 URL`-safe biçimine dönüştürmek isteyebilirsiniz. - -Aşağıdaki `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` yardımcı fonksiyonu kullanılabilir. Bu fonksiyon, `graph-ts`'e eklenecektir: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/tr/subgraphs/cookbook/enums.mdx b/website/src/pages/tr/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 1aaf953bc2e4..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: NFT Pazar Yerlerini Enums Kullanarak Kategorize Etme ---- - -Kodu daha temiz yapmak ve hata yapma riskini azaltmak için Enums kullanın. İşte NFT pazar yerlerinde Enums kullanımına bir örnek. - -## Enum'lar Nedir? - -Enum'lar veya numaralandırma türleri, bir dizi izin verilen değeri tanımlamanıza olanak tanıyan belirli bir veri türüdür. - -### Şemanızda Enum Örnekleri - -Bir pazar yerinde token sahiplik geçmişini izlemek için bir subgraph oluşturuyorsanız, her token `OriginalOwner`, `SecondOwner` ve `ThirdOwner` gibi farklı sahipliklerden geçebilir. Enum'ları kullanarak, bu belirli sahiplikleri tanımlayabilir ve yalnızca önceden tanımlanmış değerlerin atanmasını sağlayabilirsiniz. - -Şemanızda enum tanımlayabilir ve bir kez tanımlandığında, bir varlık üzerinde bir enum alanı ayarlamak için enum değerlerinin dizi (string) gösterimini kullanabilirsiniz. - -İşte yukarıdaki örneğe dayanarak, şemanızda bir enum tanımı şöyle görünebilir: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -Bu, şemanızda `TokenStatus` türünü kullandığınızda, bunun tanımlı değerlerden tam olarak biri olmasını beklediğiniz anlamına gelir: `OriginalOwner`, `SecondOwner` veya `ThirdOwner`. Böylece tutarlılık ve geçerlilik sağlanmış olur. - -Enum'lar hakkında daha fazla bilgi edinmek için [Subgraph Oluşturma](/developing/creating-a-subgraph/#enums) ve [GraphQL dokümantasyonu](https://graphql.org/learn/schema/#enumeration-types) kaynaklarına göz atın. - -## Enum Kullanmanın Faydaları - -- **Anlaşılırlık:** Enum'lar değerlere anlamlı isimler verir, veriyi daha anlaşılır hale getirir. -- **Doğrulama:** Enum'lar katı değer tanımlamaları uygulayarak geçersiz veri girişlerini önler. -- **Bakım Kolaylığı:** Yeni kategoriler eklemek veya mevcut olanları değiştirmek gerektiğinde, enum'lar bunu odaklı bir şekilde yapmanıza olanak tanır. - -### Enum'lar Olmadan - -Türü Enum kullanmak yerine bir dize olarak tanımlamayı seçerseniz, kodunuz şöyle görünebilir: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Token Sahibi - tokenStatus: String! # Token Durumunu Takip Eden Dize Alanı - timestamp: BigInt! -} -``` - -Bu şemada, `TokenStatus` belirli, alabileceği değerler sınırlandırılmış olmayan basit bir dizedir. - -#### Bu neden bir sorun? - -- `TokenStatus` değerleri için bir kısıtlama yoktur. Bu yüzden yanlışlıkla herhangi bir dize atanabilir. Bu, yalnızca `OriginalOwner`, `SecondOwner` veya `ThirdOwner` gibi geçerli durumların ayarlandığını sağlamayı zorlaştırır. -- `OriginalOwner` yerine `Orgnalowner` gibi yazım hataları yaparak verilerin ve potansiyel sorguların güvenilmez hale gelmesine sebep olmak kolaydır. - -### Enum Kullanımıyla - -Serbest formda dizeler atamak yerine, `TokenStatus` için `OriginalOwner`, `SecondOwner` veya `ThirdOwner` gibi belirli değerlerle bir enum tanımlanabilir. Bir enum kullanmak, yalnızca izin verilen değerlerin kullanılmasını sağlar. - -Enumlar; tür güvenliği sağlar, yazım hatası riskini en aza indirir ve tutarlı ve güvenilir sonuçlar sağlar. - -## NFT Pazar Yerleri için Enum Tanımlama - -> Not: Aşağıdaki kılavuz CryptoCoven NFT akıllı sözleşmesini kullanmaktadır. - -NFT'lerin ticaretinin yapıldığı çeşitli pazar yerleri için enum tanımlamak için subgraph şemanızda aşağıdakini kullanın: - -```gql -# CryptoCoven sözleşmesinin etkileşimde bulunduğu pazar yerleri için Enum (muhtemel bir Takas/Basım) -enum Marketplace { - OpenSeaV1 # CryptoCoven NFT'sinin bu pazar yerinde takas yapılmasını temsil eder - OpenSeaV2 # CryptoCoven NFT'si ninOpenSeaV2 pazar yerinde takas yapılmasını temsil eder - SeaPort # CryptoCoven NFT'sinin SeaPort pazar yerinde takas yapılmasını temsil eder - LooksRare # CryptoCoven NFT'sinin LookRare pazar yerinde takas yapılmasını temsil eder - # ...ve diğer pazar yerleri -} -``` - -## NFT Pazar Yerleri için Enum Kullanımı - -Tanımlandıktan sonra, enum'lar işlemleri veya olayları kategorize etmek için subgraph'inizde kullanılabilir. - -Örneğin, NFT satışlarını kaydederken takasta yer alan pazar yerini enum kullanarak belirleyebilirsiniz. - -### NFT Pazar Yerleri için Bir Fonksiyon İmplementasyonu - -Enum'dan pazar yeri adını bir dize olarak almak için bir fonksiyonu şöyle uygulayabilirsiniz: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Enum değerini bir dizeye eşlemek için if-else ifadelerini kullanma - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // I Eğer pazar yeri OpenSea ise, onun dize temsilini döndür - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // Eğer pazar yeri SeaPort ise, onun dize temsilini döndür - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // Eğer pazar yeri LooksRare ise, onun dize temsilini döndür - // ... ve diğer pazar yerleri - } -} -``` - -## Enum Kullanımı için En İyi Uygulamalar - -- **Tutarlı İsimlendirme:** Okunabilirliği artırmak için enum değerleri için net, açıklayıcı isimler kullanın. -- **Merkezi Yönetim:** Tutarlılık için enum'ları tek bir dosyada tutun. Böylece enum'ların güncellenmesi kolaylaşmış olur ve onların tek bir doğru bilgi kaynağı olmasını sağlar. -- **Dokümantasyon:** Amaçlarını ve kullanımını açıklamak için enum'a yorumlar ekleyin. - -## Sorgularda Enum Kullanımı - -Sorgulardaki enum'lar verilerin kalitesini artırmanıza ve sonuçları daha kolay yorumlamanıza yardımcı olur. Enumlar filtreleme ve yanıt ögeleri olarak işlev görürler, tutarlılığı sağlarlar ve pazar yerlerindeki hataları azaltırlar. - -**Ayrıntılar** - -- **Enum ile Filtreleme:** Enum'lar net filtreler sağlar, belirli pazarları güvenle dahil etmenizi veya hariç tutmanızı mümkün kılar. -- **Yanıtlarda Enum'lar:** Enum'lar yalnızca tanınan pazar adlarının döndürülmesini garanti eder, bu da sonuçları standart ve isabetli hale getirir. - -### Örnek Sorgular - -#### Sorgu 1: En Yüksek NFT Pazar Yeri Etkileşimine Sahip Hesap - -Bu sorgu şunları yapar: - -- Farklı pazar yerlerinde en yüksek benzersiz NFT etkileşimlerine sahip hesabı bulur. Bu da çapraz pazar yeri aktivitelerini analiz etmek için mükemmeldir. -- Pazar yerleri alanı, yanıt içerisindeki pazar yeri değerlerini tutarlı ve doğrulanmış hale getiren pazar yeri enum'ını kullanır. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # Bu alan, pazar yerini temsil eden enum değerini döndürür. - } - } -} -``` - -#### Dönüşler - -Bu yanıt; hesap detaylarını, ve netlik sağlamak amacıyla enum değerlerine sahip benzersiz pazar yeri etkileşimlerinin listesini sağlar: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Sorgu 2: CryptoCoven İşlemleri için En Aktif Pazar Yeri - -Bu sorgu şunları yapar: - -- CryptoCoven işlemlerinin en yüksek hacimli olduğu pazar yerini belirler. -- Yalnızca geçerli pazar yeri türlerinin yanıt olarak görünmesini sağlamak için pazar yeri enum'ını kullanarak verilerinize güvenilirlik ve tutarlılık katar. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Sonuç 2 - -Beklenen yanıt, pazar yerini ve ilgili işlem sayısını içerir; pazar yeri türünü belirtmek için enum kullanır: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Sorgu 3: Yüksek İşlem Sayısına Sahip Pazar Etkileşimleri - -Bu sorgu şunları yapar: - -- "Unknown" pazarlarını hariç tutarak, 100'den fazla işlemi olan ilk dört pazarı getirir. -- Yalnızca geçerli pazar türlerinin dahil edilmesini sağlamak için filtre olarak enum'lar kullanır. Böylece doğruluk oranı arttırılmış olur. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Sonuç 3 - -Beklenen çıktı, her biri bir enum değeri ile temsil edilen, kriterleri karşılayan pazarları içerir: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Ek Kaynaklar - -Ek bilgi için bu rehberin [deposuna](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums) göz atın. diff --git a/website/src/pages/tr/subgraphs/cookbook/grafting.mdx b/website/src/pages/tr/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 60855aa97729..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Bir Sözleşmeyi Değiştirin ve Graftlama ile Geçmişini Koruyun ---- - -Bu rehberde, mevcut subgraphları graftlayarak yeni subgraphları nasıl oluşturacağınızı ve dağıtacağınızı öğreneceksiniz. - -## Graftlama Nedir? - -Graftlama, mevcut bir subgraph'daki verileri yeniden kullanır ve daha sonraki bir blokta indekslemeye başlar. Bu, geliştirme sırasında eşleştirmelerdeki basit hataları hızlı bir şekilde geçmek veya mevcut bir subgraph'ın başarısız olduktan sonra geçici olarak tekrar çalışmasını sağlamak için kullanışlıdır. Ayrıca, sıfırdan indekslenmesi uzun süren bir subgraph'a bir özellik eklerken de kullanılabilir. - -Graftlanan subgraph, temel subgraphla tamamen aynı olmayan, ancak onunla uyumlu olan bir GraphQL şeması kullanabilir. Kendi başına geçerli bir subgraph şeması olmalıdır, ancak şu şekillerde temel subgraph şemasından sapabilir: - -- Varlık türlerini ekler veya kaldırır -- Varlık türlerinden öznitelikleri kaldırır -- Varlık türlerine null yapılabilir öznitelikler ekler -- Null yapılamayan öznitelikleri null yapılabilir özniteliklere dönüştürür -- Numaralandırmalara değerler ekler -- Arayüzleri ekler veya kaldırır -- Arayüzün hangi varlık türleri için uygulandığını değiştirir - -Daha fazla bilgi için kontrol edebilirsiniz: - -- [Aşılama](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -Bu eğitimde, temel bir kullanım senaryosunu ele alacağız. Mevcut bir sözleşmeyi özdeş bir sözleşme (aynı koda sahip ancak adresi farklı bir sözleşme) ile değiştireceğiz. Ardından, mevcut subgraph'i yeni sözleşmeyi izleyen "temel" subgraph'e aşılayacağız. - -## Ağa Yükseltme Durumunda Graftlamaya İlişkin Önemli Not - -> **Dikkat**: Aşılamanın The Graph Ağına yayımlanan subgraph'ler için kullanılmaması önerilir - -### Bu Neden Önemli? - -Aşılama, bir subgraph'i diğerine "aşılayarak" mevcut subgraph'ten yeni bir versiyona tarihi verileri etkin bir şekilde aktarmanıza olanak tanıyan güçlü bir özelliktir. Bir subgraph'i The Graph Ağından Subgraph Studio'ya geri aşılamak mümkün değildir. - -### En İyi Uygulamalar - -**İlk Geçiş**: Subgraph'inizi ilk kez merkeziyetsiz ağa dağıttığınızda aşılama yapmayın. Subgraph'in stabil ve beklendiği gibi çalıştığından emin olun. - -**Sonraki Güncellemeler**: Subgraph'iniz merkeziyetsiz ağda canlı ve stabil olduğunda, gelecekteki versiyonlar için aşılama kullanarak geçişi daha sorunsuz hale getirebilir ve tarihi verileri koruyabilirsiniz. - -Bu yönergelere uyarak riskleri en aza indirebilir ve daha sorunsuz bir taşıma süreci geçirebilirsiniz. - -## Mevcut Bir Subgraph'ı Oluşturma - -Subgraph oluşturmak, The Graph'in önemli bir parçasıdır. Bu konu daha detaylı olarak [burada](/subgraphs/quick-start/) açıklanmıştır. Bu eğitimde kullanılan mevcut subgraph'i inşa etmek ve dağıtmak için aşağıdaki depo sağlanmıştır: - -- [Subgraph örnek deposu](https://github.com/Shiyasmohd/grafting-tutorial) - -> Not: Subgraph'te kullanılan sözleşme, [Hackathon Başlangıç Kiti](https://github.com/schmidsi/hackathon-starterkit)'nden alınmıştır. - -## Subgraph Manifest Tanımı - -Subgraph manifestosu `subgraph.yaml`, subgraph için veri kaynaklarını, ilgili tetikleyicileri ve bu tetikleyicilere yanıt olarak çalıştırılması gereken fonksiyonları tanımlar. Kullanacağınız bir subgraph manifestosu örneği aşağıda verilmiştir: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- `Lock` veri kaynağı, sözleşmeyi derleyip dağıttığımızda elde edeceğimiz "abi" ve sözleşme adresidir -- Ağ, sorgulanan endekslenmiş bir ağa karşılık gelmelidir. Sepolia testnet üzerinde çalıştığımız için, ağ `sepolia`'dır -- `mapping` bölümü, ilgili tetikleyicileri ve bu tetikleyicilere yanıt olarak çalıştırılması gereken fonksiyonları tanımlar. Bu durumda, `Withdrawal` olayını dinliyoruz ve yayarken `handleWithdrawal` fonksiyonunu çağırıyoruz. - -## Graftlama Manifest Tanımı - -Graftlama, orijinal subgraph bildirimine iki yeni öğe eklemeyi gerektirir: - -```yaml ---- -features: - - grafting # özellik adı -graft: - base: Qm... # Asıl subgraph'in kimlik numarası - block: 5956000 # blok numarası -``` - -- `features:` tüm kullanılan [özellik adlarının](/developing/creating-a-subgraph/#experimental-features) bir listesidir. -- `graft:` `base` subgraph ve üzerine bağlanılacak bloktan oluşan bir eşlemedir. `block`, endekslemenin başlanacağı blok numarasıdır. The Graph, belirtilen bloka kadar olan temel subgraph'in verisini kopyalayıp bu bloka kadar olan kısmı dahil edecek ve ardından yeni subgraph'i bu bloktan itibaren endekslemeye devam edecek. - -`base` ve `block` değerleri, iki subgraph dağıtılarak bulunabilir: Biri temel endeksleme için, diğeri ise aşılama için olan subgraph - -## Temel Subgraph'ı Dağıtma - -1. [Subgraph Studio](https://thegraph.com/studio/) adresine gidip Sepolia testnet üzerinde `graft-example` adlı bir subgraph oluşturun -2. Depodan `graft-example` klasöründeki `AUTH & DEPLOY` bölümündeki yönergeleri izleyin -3. Tamamlandığında, subgraph'ın doğru bir şekilde indekslendiğinden emin olun. Eğer aşağıdaki komutu Graph Test Alanında(Playground) çalıştırırsanız - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Şuna benzer bir şey döndürür: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Subgraph'ın düzgün bir şekilde indekslendiğini doğruladıktan sonra, subgraph'ı graftlama ile hızlı bir şekilde güncelleyebilirsiniz. - -## Graftlama Subgraph'ını Dağıtma - -Graft yerine geçen subgraph.yaml yeni bir sözleşme adresine sahip olacaktır. Bu, merkeziyetsiz uygulamanızı güncellediğinizde, bir sözleşmeyi yeniden dağıttığınızda vb. gerçekleşebilir. - -1. [Subgraph Studio](https://thegraph.com/studio/) adresine gidin ve Sepolia testnet üzerinde `graft-replacement` adlı bir subgraph oluşturun -2. Yeni bir manifesto dosyası oluşturun. `graph-replacement` subgraph'ine ait `subgraph.yaml` dosyası, farklı bir sözleşme adresi ve nasıl aşılanması gerektiğiyle ilgili yeni bilgiler içermektedir. Bunlar, eski sözleşme tarafından ilgilendiğiniz [son yayılan olayın](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) `blok`u ve eski subgraph'in `base`'idir (temelidir). `base` subgraph kimliği, orijinal `graph-example` subgraph'inizin `Deployment ID`'sidir (dağıtım kimliğidir). Bunu Subgraph Studio'da bulabilirsiniz. -3. `graft-replacement` klasöründeki subgraph sayfanızda, `AUTH & DEPLOY` bölümündeki talimatları izleyin -4. Tamamlandığında, subgraph'ın doğru bir şekilde indekslendiğinden emin olun. Eğer aşağıdaki komutu Graph Test Alanında(Playground) çalıştırırsanız - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Aşağıdakileri döndürmelidir: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -`graft-replacement` subgraph'inin eski `graph-example` verilerini ve yeni sözleşme adresinden gelen yeni verileri endekslediğini görebilirsiniz. Orijinal sözleşme, iki `Withdrawal` olayı yaydı: [Olay 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) ve [Olay 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). Yeni sözleşme, sonrasında bir `Withdrawal` olayı yaydı, [Olay 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). Önceden endekslenmiş iki işlem (Olay 1 ve 2) ve yeni işlem (Olay 3), `graft-replacement` subgraph'inde birleştirildi. - -Tebrikler! Bir subgraph'i başka bir subgraph'e başarıyla aşıladınız. - -## Ek Kaynaklar - -Aşılama konusunda daha fazla deneyim kazanmak istiyorsanız, yaygın kullanılan sözleşmeler için aşağıda birkaç örnek bulunmaktadır: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -Daha da iyi bir Graph uzmanı olmak için, temel veri kaynaklarındaki değişikliklerle başa çıkmanın diğer yollarını öğrenmeyi değerlendirin. [Veri Kaynağı Şablonları](/developing/creating-a-subgraph/#data-source-templates) gibi alternatifler benzer sonuçlar elde edebilir - -> Not: Bu makaledeki materyalin büyük bir kısmı, daha önce yayımlanmış olan [Arweave makalesinden](/subgraphs/cookbook/arweave/) alınmıştır diff --git a/website/src/pages/tr/subgraphs/cookbook/near.mdx b/website/src/pages/tr/subgraphs/cookbook/near.mdx deleted file mode 100644 index 42ecff83f4f1..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: NEAR Üzerinde Subgraphlar Oluşturma ---- - -Bu rehber, [NEAR blokzinciri](https://docs.near.org/) üzerindeki akıllı sözleşmeleri endeksleyen subgraph'ler inşa etmeye giriş niteliğindedir. - -## NEAR Nedir? - -[NEAR](https://near.org/), merkezi olmayan uygulamalar geliştirmek için kullanılan bir akıllı sözleşme platformudur. Daha fazla bilgi için [resmi dokümantasyona](https://docs.near.org/concepts/basics/protocol) bakabilirsiniz. - -## NEAR subgraphları nedir? - -The Graph, geliştiricilere blokzinciri olaylarını işleyip, sonuçtaki veriyi bir GraphQL API'ı (subgraph olarak da bilinir) aracılığıyla kolayca erişilebilir kılacak araçlar sunar. [Graph Düğümü](https://github.com/graphprotocol/graph-node) artık NEAR olaylarını işleyebiliyor, bu da NEAR geliştiricilerinin akıllı sözleşmelerini endekslemek için subgraph'ler oluşturabileceği anlamına gelir. - -Subgraph'ler olay tabanlıdır., yani zincir üzerindeki olayları dinler ve sonrasında işlerler. Şu anda NEAR subgraph'leri için desteklenen iki tür işleyici bulunmaktadır: - -- Blok işleyicileri: Bunlar her yeni blokta çalışır -- Makbuz işleyicileri: Belirli bir hesapta her mesaj yürütüldüğünde çalışır - -[NEAR dokümantasyonundan](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Makbuz, sistemdeki eyleme geçirilebilir tek nesnedir. NEAR platformunda "bir işlemin işlenmesinden" bahsettiğimizde, bu nihayetinde bir noktada "makbuzların uygulanması" anlamına gelir. - -## NEAR Subgraph'ı Oluşturma - -`@graphprotocol/graph-cli`, subgraph'ler oluşturmak ve dağıtmak için kullanılan bir komut satırı aracıdır. - -`@graphprotocol/graph-ts`, subgraph'e özgü türlerden oluşan bir kütüphanedir. - -NEAR ağında subgraph geliştirmek, `graph-cli`'nin `0.23.0` üstü sürümünü ve `graph-ts`'nin `0.23.0` üstü sürümünü gerektirir. - -> Bir NEAR subgraph'ı oluşturmak, Ethereum'u indeksleyen bir subgraph oluşturmakla çok benzerdir. - -Subgraph tanımının üç yönü vardır: - -**subgraph.yaml:** subgraph manifestosudur, ilgi duyulan veri kaynaklarını tanımlar ve bunların nasıl işleneceğini açıklar. NEAR, yeni bir `kind` (tür) veri kaynağıdır. - -**schema.graphql:** subgraph'iniz için hangi verilerin depolanacağını ve bunların GraphQL kullanılarak nasıl sorgulanacağını tanımlayan şema dosyasıdır. NEAR subgraph'leri için gereksinimler [mevcut dokümantasyon](/developing/creating-a-subgraph/#the-graphql-schema) tarafından kapsanmaktadır. - -**AssemblyScript Eşlemeleri:** Olay verisini, şemanızda tanımlanan varlıklara dönüştüren [AssemblyScript kodudur](/subgraphs/developing/creating/graph-ts/api/). NEAR desteği, NEAR'a özgü veri türleri ve yeni JSON ayrıştırma işlevi sunar. - -Subgraph geliştirme sırasında iki anahtar komut vardır: - -```bash -$ graph codegen # manifest'de tanımlanan şema dosyasından tipleri üretir -$ graph build # AssemblyScript dosyalarından Web Assembly oluşturur ve tüm subgraph dosyalarını bir /build klasöründe hazırlar -``` - -### Subgraph Manifest Tanımı - -Subgraph manifestosu (`subgraph.yaml`), subgraph için veri kaynaklarını, ilgili tetikleyicileri ve bu tetikleyicilere yanıt olarak çalıştırılması gereken fonksiyonları tanımlar. Aşağıda bir NEAR subgraph'i için örnek bir subgraph manifestosu bulunmaktadır: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # şema dosyasına bağlantı -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # Bu veri kaynağı bu hesabı izleyecektir - startBlock: 10662188 # NEAR için gereklidir - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # eşleştirme dosyasındaki fonksiyon adı - receiptHandlers: - - handler: handleReceipt # eşleştirme dosyasındaki fonksiyon adı - file: ./src/mapping.ts # Assemblyscript eşleştirmelerinin bulunduğu dosyaya bağlantı -``` - -- NEAR subgraph'leri yeni bir veri kaynağı `kind`'ı (türü) sunar (`near`) -- `network`, subgraph'i sunan Graph Düğümü üzerindeki bir ağa karşılık gelmelidir. Subgraph Studio'da, NEAR'ın ana ağı `near-mainnet`, ve NEAR'ın test ağı `near-testnet`'tir -- NEAR veri kaynakları, [NEAR hesabı](https://docs.near.org/concepts/protocol/account-model) ile ilişkili, insan tarafından okunabilir bir kimlik olan isteğe bağlı `source.account` alanını sunar. Bu, bir hesap veya alt hesap olabilir. -- NEAR veri kaynakları, isteğe bağlı ek `source.accounts` alanını tanıtır. Bu alan isteğe bağlı sonekler ve önekler içerir. En azından bir önek veya sonek belirtilmelidir. Bu ekler ilgili listedeki değerlerle başlayan veya biten herhangi bir hesabı eşleştirirler. Aşağıdaki örnek şunlarla eşleşecektir: `[app|good].*[morning.near|morning.testnet]`. Sadece önekler veya sonekler listesi gerekiyorsa diğer alan atlanabilir. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR veri kaynakları iki tür işleyiciyi destekler: - -- `blockHandlers`: her yeni NEAR blokunda çalıştırılır. `source.account` gerekli değildir. -- `receiptHandlers`: veri kaynağının `source.account`'unun alıcı olduğu her makbuzda çalışır. Makbuz (receipt) teknik bir kavramdır, daha detaylı bilgi için NEAR dokümanlarını inceleyebilirsiniz. Bu noktada, yalnızca tam eşleşmelerin işlendiğine dikkat edin. ([Alt hesaplar](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) bağımsız veri kaynakları olarak eklenmelidir). - -### Şema Tanımı - -Şema tanımı, ortaya çıkan subgraph veritabanının yapısını ve varlıklar arasındaki ilişkileri açıklar. Bu, orijinal veri kaynağından bağımsızdır. Subgraph şema tanımı hakkında daha fazla detay [burada](/developing/creating-a-subgraph/#the-graphql-schema) bulunabilir. - -### AssemblyScript Eşlemeleri - -Olayları işlemek için kullanılan işleyiciler [AssemblyScript](https://www.assemblyscript.org/) ile yazılmıştır. - -NEAR endeksleme, [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) için NEAR'a özgü veri türlerini tanıtır. - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -Bu türler blok & makbuz işleyicilerine aktarılır: - -- Blok işleyiciler bir `Block` alacaktır -- Makbuz işleyiciler bir `ReceiptWithOutcome` alacaktır - -Aksi takdirde, NEAR subgraph geliştiricileri eşleme yürütme sırasında [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/)'ının geri kalanını kullanabilir. - -Bu, yeni bir JSON ayrıştırma fonksiyonunu içerir - NEAR üzerindeki günlükler sıklıkla dizeleştirilmiş JSON olarak yayılır. Geliştiricilerin bu günlükleri kolayca işlemelerine olanak tanımak için [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) kapsamında yeni bir `json.fromString(...)` fonksiyonu mevcuttur. - -## NEAR Subgraph'ını Dağıtma - -Bir subgraph'i oluşturduktan sonra sıradaki adım bu subgraph'i endeksleme için Graph Düğümü'ne dağıtmaktır. NEAR subgraph'leri, herhangi bir Graph Düğümü `>=v0.26.x` sürümüne dağıtılabilir (bu sürüm henüz etiketlenmemiş ve yayımlanmamıştır). - -The Graph Ağı'ndaki Subgraph Studio ve yükseltme Endeksleyicisi şu anda beta olarak NEAR ana ağı ve test ağını endekslemeyi, aşağıdaki ağ isimleriyle desteklemektedir: - -- `near-mainnet` -- `near-testnet` - -Subgraph Studio'da subgraph'ler oluşturma ve dağıtma hakkında daha fazla bilgi [burada](/deploying/deploying-a-subgraph-to-studio/) bulunabilir. - -Kısa bir ön bilgi olarak - ilk adım subgraph'inizi "oluşturmak"tır - bu sadece bir kez yapılması gereken bir işlemdir. Subgraph Studio'da, [Gösterge Paneliniz](https://thegraph.com/studio/)'deki "Bir subgraph oluştur" kısmında yapılabilir. - -Subgraph oluşturulduktan sonra, `graph deploy` CLI komutunu kullanarak subgraph'inizi dağıtabilirsiniz: - -```sh -$ graph create --node # yerel bir Graph Düğümünde bir subgraph oluşturur (Subgraph Studio'da, bu işlem UI üzerinden yapılır) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # manifesto IPFS hash'ine göre belirtilen bir Graph Düğümü'ne subgraph'i dağıtır ve yapım dosyalarını belirtilen IPFS uç noktasına yükler -``` - -Düğüm yapılandırması, subgraph'ın nerede dağıtıldığına bağlı olacaktır. - -### Subgraph Stüdyosu - -```sh -graph auth -graph deploy -``` - -### Yerel Graph Düğümü (varsayılan yapılandırmaya göre) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Subgraph'ınız dağıtıldıktan sonra Graph Düğüme tarafından indekslenecektir. Subgraph'ın kendisini sorgulayarak ilerlemesini kontrol edebilirsiniz: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### NEAR'ı Yerel Graph Düğümü ile İndeksleme - -NEAR'ı indeksleyen bir Graph Düğümü çalıştırmanın aşağıdaki operasyonel gereksinimleri vardır: - -- Firehose enstrümantasyonu ile NEAR İndeksleyici Çerçevesi -- NEAR Firehose Bileşen(ler)i -- Firehose uç noktası yapılandırılmış Graph Düğümü - -Yukarıdaki bileşenlerin çalıştırılması hakkında yakında daha fazla bilgi vereceğiz. - -## NEAR Subgraph'ını Sorgulama - -NEAR subgraph'leri için GraphQL uç noktası, mevcut API arayüzü ile şema tanımına göre belirlenir. Daha fazla bilgi için [GraphQL API dokümantasyonuna](/subgraphs/querying/graphql-api/) bakabilirsiniz. - -## Örnek Subgraph'ler - -Aşağıda bazı örnek subgraph'leri bulabilirsiniz: - -[NEAR Blokları](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Makbuzları](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### Beta nasıl çalışır? - -NEAR desteği beta aşamasındadır, bu da entegrasyonu geliştirmek için çalışmaya devam ederken API'de değişiklikler olabileceği anlamına gelir. NEAR subgraphları oluştururken size destek olabilmemiz ve en son gelişmelerden sizi haberdar edebilmemiz için lütfen near@thegraph.com adresine e-posta gönderin! - -### Bir subgraph hem NEAR hem de EVM zincirlerini indeksleyebilir mi? - -Hayır, bir subgraph yalnızca bir zincirden/ağdan veri kaynaklarını destekleyebilir. - -### Subgraphlar daha spesifik tetikleyicilere tepki verebilir mi? - -Şu anda yalnızca Blok ve Makbuz tetikleyicileri desteklenmektedir. Belirli bir hesaba yapılan fonksiyon çağrıları için tetikleyicileri araştırma aşamasındayız. NEAR yerel olay desteğine sahip oldu takdirde, olay tetikleyicilerini desteklemekle de ilgileneceğiz. - -### Makbuz işleyicileri hesaplar ve bunların alt hesapları için tetiklenecek mi? - -Bir `account` belirtildiyse, yalnızca tam hesap adı eşleştirilecektir. `accounts` alanı belirterek alt hesapları eşleştirmek mümkündür. `suffixes` (önekleri) ve `prefixes`'i (sonekleri) ve `accounts` alanını da belirterek, alt hesapları eşleştirmek mümkündür. Örneğin, aşağıdaki `mintbase1.near` alt hesaplarının tümünü eşleştirecektir: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### NEAR subgraphları eşleştirmeler sırasında NEAR hesaplarına görünüm çağrıları yapabilir mi? - -Bu desteklenmemektedir. Bu fonksiyonelliğin indeksleme için gerekli olup olmadığını değerlendiriyoruz. - -### NEAR subgraph'ımda veri kaynağı şablonları kullanabilir miyim? - -Bu şu anda desteklenmemektedir. Bu fonksiyonelliğin indeksleme için gerekli olup olmadığını değerlendiriyoruz. - -### Ethereum subgraphları "beklemedeki" ve "mevcut" sürümleri destekler, bir NEAR subgraph'ının "beklemedeki" sürümünü nasıl dağıtabilirim? - -Bekleme fonksiyonelliği henüz NEAR subgraphları için desteklenmemektedir. Bu arada, farklı "adlandırılmış" bir subgraph'a yeni bir sürüm dağıtabilir ve daha sonra bu zincir başı ile senkronize edildiğinde, aynı temel dağıtım ID'sini kullanacak olan birincil "adlandırılmış" subgraph'ınıza yeniden dağıtabilirsiniz. Böylece ana subgraph anında senkronize olur. - -### Sorum yanıtlanmadı, NEAR subgraphları oluşturma konusunda nereden daha fazla yardım alabilirim? - -Eğer subgraph geliştirme ile ilgili genel bir soru ise, [Geliştirici dokümantasyonunun](/subgraphs/quick-start/) geri kalanında çok daha fazla bilgi bulunmaktadır. Eğer burada aradığınızı bulamazsanız lütfen [The Graph Protocol Discord](https://discord.gg/graphprotocol) sunucusuna katılın ve #near kanalında sorunuzu sorun. Veya near@thegraph.com adresine e-posta gönderin. - -## Referanslar - -- [NEAR geliştirici dokümantasyonu](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/tr/subgraphs/cookbook/polymarket.mdx b/website/src/pages/tr/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/tr/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/tr/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 50a3741afa22..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Next.js Sunucu Bileşenlerini Kullanarak API Anahtarları Nasıl Güvenli Bir Şekilde Kullanılır ---- - -## Genel Bakış - -API anahtarımızı dapp'imizin ön yüzünde açığa çıkmasını düzgün bir şekilde engellemek için [Next.js sunucu bileşenlerini](https://nextjs.org/docs/app/building-your-application/rendering/server-components) kullanabiliriz. API anahtarımızın güvenliğini daha da artırmak için, ayrıca [API anahtarımızı belirli subgraph'lar veya Subgraph Studio'daki alanlarla sınırlandırabiliriz](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -Bu talimatlarda, bir subgraph'i sorgularken aynı zamanda API anahtarını ön yüzden gizleyen bir Next.js sunucu bileşeni oluşturmayı ele alacağız. - -### Kısıtlamalar - -- Next.js sunucu bileşenleri, servis dışı bırakma saldırıları ile API anahtarlarının boşaltılmasına karşı koruma sağlamaz. -- The Graph Ağ geçitleri, servis dışı bırakma saldırı tespiti ve saldırıyı hafifletme stratejilerine sahiptir. Ancak sunucu bileşenlerini kullanmak bu korumaları zayıflatabilir. -- Next.js sunucu bileşenleri, sunucunun çökmesi ihtimali dolayısıyla merkezileşme riskleri taşır. - -### Neden Gerekli - -Standart bir React uygulamasında, ön yüz koduna dahil edilen API anahtarları istemci tarafında açığa çıkabilir ve güvenlik riski oluşturabilir. `.env` dosyaları yaygın olarak kullanılsa da React kodu istemci tarafında çalıştığı için anahtarları tam olarak korumazlar ve API anahtarı başlıklarda açığa çıkar. Next.js Sunucu Bileşenleri bu sorunu, hassas işlemleri sunucu tarafında yürüterek çözer. - -### Bir subgraph'i sorgulamak için istemci tarafında işleme (render) - -![İstemci tarafında işleme](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- [Subgraph Studio](https://thegraph.com/studio)'dan bir API anahtarı -- Temel Next.js ve React bilgisi. -- [Uygulama Yönlendiricisi](https://nextjs.org/docs/app) kullanan mevcut bir Next.js projesi. - -## Adım Adım Talimatlar - -### Adım 1: Ortam Değişkenlerini Ayarlayın - -1. Next.js projemizin kök dizininde `.env.local` dosyası oluşturun. -2. API anahtarımızı ekleyin: `API_KEY=`. - -### Adım 2: Bir Sunucu Bileşeni Oluşturma - -1. `components` dizinimizde "ServerComponent.js" adında yeni bir dosya oluşturun. -2. Sunucu bileşenini kurmak için sağlanan örnek kodu kullanın. - -### Adım 3: Sunucu Tarafı API İsteğini Gerçekleştirin - -`ServerComponent.js`'e aşağıdaki kodu ekleyin: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Adım 4: Sunucu Bileşenini Kullanın - -1. Sayfa dosyamızda (örneğin, `pages/index.js`), `ServerComponent`'ı içe aktarın. -2. Bileşeni işleyin: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Adım 5: Dapp'imizi Çalıştırın ve Test Edin - -`npm run dev` komutunu kullanarak Next.js uygulamamızı başlatın. Sunucu bileşeninin API anahtarını açığa çıkarmadan veri çektiğini doğrulayın. - -![Sunucu-taraflı işleme](/img/api-key-server-side-rendering.png) - -### Sonuç - -Next.js Sunucu Bileşenlerini kullanarak, API anahtarını istemci tarafında gizlemeyi başardık ve bu da uygulamamızın güvenliğini artırdı. Bu yöntem, hassas işlemlerin potansiyel istemci-taraflı güvenlik açıklıklarından uzak bir şekilde sunucu tarafında ele alındığını garanti eder. Son olarak, API anahtar güvenliğinizi daha da artırmak için [diğer API anahtar güvenlik önlemlerini](/subgraphs/querying/managing-api-keys/) incelemeyi unutmayın. diff --git a/website/src/pages/tr/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/tr/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index d739d1aee6d6..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Fork Kullanarak Hızlı ve Kolay Subgraph Hata Ayıklama ---- - -Büyük miktarda veri işleyen birçok sistemde olduğu gibi, The Graph'ın Endeksleyicilerinin (Graph Düğümlerinin), subgraph'inizi hedef blokzinciri ile senkronize etmesi ciddi ölçüde uzun sürebilir. Hata ayıklama amacıyla yapılan hızlı değişiklikler ile endeksleme için gereken uzun bekleme süreleri arasındaki uyumsuzluk son derece verimsiz olmaktadır. Bunun kesinlikle farkındayız. Bu yüzden, [LimeChain](https://limechain.tech/) tarafından geliştirilen **subgraph çatallama**yı sunuyoruz. Bu makalede size bu özelliğin subgraph hata ayıklamayı önemli ölçüde hızlandırmak için nasıl kullanılabileceğini göstereceğim! - -## Peki, nedir bu Subgraph Forklama? - -**Subgraph çatallama**, _başka bir_ subgraph'in mağazasından (genellikle uzak bir mağaza) tembel bir şekilde öge çekme işlemidir. - -Hata ayıklama bağlamında, **subgraph çatallama** başarısız olmuş subgraph'i, _X_ blokuna kadar senkronize olmasını beklemeden hata ayıklamanıza olanak tanır. - -## Ne?! Nasıl? - -Bir subgraph'i uzaktaki bir Graph Düğümüne endekslemek amacıyla dağıttığınızda subgraph _X_ blokunda çalışmayı durdurabilir. İyi haber ise Graph Düğümü, _X_ blokuna kadar senkronize olmuş deposunu kullanarak GraphQL sorgularını yerine getiriyor olacaktır. Bu harika bir haber! Bu durum, endeksleme sırasında _X_ blokunda ortaya çıkan hataları düzeltmek için bu "güncel" depodan faydalanabileceğimiz anlamına gelir. - -Özetle, _çalışmayı durdurmuş bir subgraph'i_, _X_ blokuna kadar endekslenmesi garanti edilen uzak bir Graph Düğümünden _çatallayacağız_. Böylece _X_ blokunda hatası ayıklanan yerel olarak dağıtılmış subgraph'in endeksleme durumunu gösteren güncel bir görünüm sağlamış olacağız. - -## Lütfen bana biraz kod göster! - -Subgraph hata ayıklamalarına odaklanmak için işleri basitleştirelim ve Ethereum Gravatar akıllı sözleşmesini endeksleyen [örnek-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) üzerinde çalışalım. - -`Gravatar`'ları endekslemek için tanımlanan, hiçbir hata içermeyen işleyiciler şunlardır: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Eyvah, ne talihsiz bir durum, mükemmel görünen subgraph'imi [Subgraph Studio](https://thegraph.com/studio/) üzerinde dağıttığımda _"Gravatar bulunamadı!"_ hatası ile çalışmayı durduruyor. - -Genellikle düzeltmeyi denemek için yol şudur: - -1. Eşleştirme kaynağında, sorunu çözeceğine inandığınız bir değişiklik yapın (ama ben çözmeyeceğini biliyorum). -2. Subgraph'i [Subgraph Studio](https://thegraph.com/studio/) (veya başka bir uzak Graph Düğümü) üzerinde yeniden dağıtın. -3. Senkronize olması için bekleyin. -4. Tekrar sorunla karşılaşırsanız 1. aşamaya geri dönün, aksi takdirde: Yaşasın! - -Bu gerçekten sıradan bir hata ayıklama sürecine oldukça benzemektedir, ancak süreci korkunç derecede yavaşlatan bir adım vardır: _3. Senkronize olmasını bekleyin._ - -**Subgraph çatallama** kullanarak bu adımı ortadan kaldırabiliriz. Aşağıda bu işlemi görebilirsiniz: - -0. **_Uygun çatal-temeli (fork-base)_** ayarlanmış yerel bir Graph Düğümü başlatın. -1. Eşleştirme kaynağında, sorunu çözeceğine inandığınız bir değişiklik yapın. -2. Çalışmayı durduran subgraph'i **_çatallayarak_** ve **_sorunlu bloktan başlayarak_** yerel Graph Düğümüne dağıtın. -3. Tekrar sorunla karşılaşırsanız 1. aşamaya geri dönün, aksi takdirde: Yaşasın! - -Şimdi, 2 sorunuz olabilir: - -1. fork temelli ne??? -2. Kimi forkluyoruz?! - -Ve ben cevap veriyorum: - -1. `fork-base`, "temel" URL'dir, böylece devamına _subgraph id_ eklendiğinde oluşan URL (`/`) subgraph'in depolaması için geçerli bir GraphQL uç noktası olur. -2. Forklama kolay, ter dökmeye gerek yok: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Ayrıca, ihtiyaç olmayan blokları endekslemeyi atlamak ve çatallamanın avantajlarından yararlanmak için `subgraph` manifesto dosyasındaki `dataSources.source.startBlock` alanını sorunlu blokun numarası olarak ayarlamayı unutmayın! - -İşte benim ne yaptığım: - -1. Lokal bir Graph Düğümü başlatıyorum ([nasıl yapılacağını buradan öğrenebilirsiniz](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) ve `fork-base` seçeneğini şu şekilde ayarlıyorum: `https://api.thegraph.com/subgraphs/id/`, çünkü daha önce [Subgraph Studio](https://thegraph.com/studio/)dan dağıttığım hatalı `subgraph`i çatallayacağım. - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. Dikkatli bir incelemeden sonra, iki işleyicimde `Gravatar`'ları endekslerken kullanılan `id` temsillerinde bir uyumsuzluk olduğunu fark ettim. `handleNewGravatar` onu bir hex'e dönüştürürken (`event.params.id.toHex()`), `handleUpdatedGravatar` bir int32 (`event.params.id.toI32()`) kullanıyor, bu da `handleUpdatedGravatar`'ın "Gravatar not found!" hatasını vermesine neden oluyor. İkisini de `id`'yi hex'e dönüştürecek şekilde düzenledim. -3. Değişiklikleri yaptıktan sonra, **_hatalı subgraph'i çatallayarak_** ve `subgraph.yaml` dosyasında `dataSources.source.startBlock` değerini `6190343` olarak ayarlayarak subgraph'imi yerel Graph Düğümü'ne dağıttım: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. Yerel Graph Düğümü tarafından üretilen günlükleri inceliyorum ve yaşasın! Her şey yolunda görünüyor. -5. Artık hatasız olan `subgraph`imi uzak bir Graph Düğümü'nde dağıtıyorum ve sonsuza kadar mutlu yaşıyorum! diff --git a/website/src/pages/tr/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/tr/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index bd935dd33689..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Güvenli Subgraph Kod Oluşturucu ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) (çökmeyen subgraph), bir projenin graphql şemasından bir dizi yardımcı fonksiyon üreten bir kod oluşturma aracıdır. `subgraph`inizdeki varlıklarla tüm etkileşimlerin tamamen güvenli ve tutarlı olmasını sağlar. - -## Neden Subgraph Uncrashable'ı entegre etmelisiniz? - -- **Sürekli Çalışırlık**. Yanlış yönetilen varlıklar subgraph'lerin çökmesine neden olabilir. Bu da The Graph'e bağımlı olan projeler için işleri aksatabilir. Subgraph'lerinizi "çökmez" hale getirmek ve iş sürekliliğini sağlamak için yardımcı fonksiyonları ayarlayın. - -- **Tamamen Güvenli**. `subgraph` geliştirme sırasında yaygın görülen sorunlar, tanımsız varlıkların yüklenmesi, varlıkların tüm değerlerinin ayarlanmaması veya ilklendirilmemesi, varlıkların yüklenmemesi ve kaydedilmemesidir. Varlıklarla tüm etkileşimlerin çok az olduğundan emin olun. - -- **Kullanıcı Tarafından Yapılandırılabilir** Varsayılan değerleri ayarlayın ve projenizin ihtiyaçlarına uygun güvenlik kontrol seviyesini yapılandırın. `Subgraph` mantığındaki bir ihlali gösteren uyarı günlükleri kaydedilir ve verilerin doğruluğunu sağlamak için sorunun giderilmesine yardımcı olunur. - -**Ana Özellikler** - -- Kod oluşturma aracı, **tüm** subgraph türlerini destekler ve kullanıcıların değerlerde makul varsayılanlar ayarlamaları için yapılandırılabilir. Kod oluşturma, kullanıcıların belirtimine uygun yardımcı fonksiyonlar oluşturmak için bu yapılandırmayı kullanacaktır. - -- Framework ayrıca unsur değişkenleri grupları için özel, ancak güvenli ayarlayıcı fonksiyonları oluşturmanın bir yolunu (yapılandırma dosyası aracılığıyla) içerir. Bu sayede, kullanıcının eski bir graph unsurunu yüklemesi/kullanması ve ayrıca fonksiyonun gerektirdiği bir değişkeni kaydetmeyi veya ayarlamayı unutması imkansız hale gelir. - -- Uyarı günlükleri, subgraph mantığında bir ihlalin nerede olduğunu gösteren günlükler olarak kaydedilir ve veri doğruluğunu sağlamak için sorunun düzeltilmesine yardımcı olur. - -Subgraph Uncrashable, Graph CLI codegen komutu kullanılarak isteğe bağlı bir bayrak olarak çalıştırılabilir. - -```sh -graph codegen -u [options] [] -``` - -Daha fazla bilgi edinmek ve daha güvenli subgraph'ler geliştirmeye başlamak için [Subgraph Uncrashable dokümantasyonuna](https://float-capital.github.io/float-subgraph-uncrashable/docs/) göz atın veya bu [video rehberini](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) izleyin. diff --git a/website/src/pages/tr/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/tr/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index a02f136958c2..000000000000 --- a/website/src/pages/tr/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: The Graph'e Transfer ---- - -Subgraph'lerinizi herhangi bir platformdan hızlıca [The Graph'in merkezi olmayan ağına](https://thegraph.com/networks/) yükseltin. - -## The Graph'e Geçmenin Avantajları - -- Uygulamalarınızın zaten kullandığı subgraph'i kesinti yaşamadan aynı şekilde kullanabilirsiniz. -- Yüzden fazla Endeksleyici tarafından desteklenip global bir ağdan gelen güvenilirliği artırabilirsiniz. -- Subgraph'ler için, her zaman yardıma hazır mühendislik ekibinden 7/24 yıldırım hızında destek alabilirsiniz. - -## Subgraph'inizi The Graph'e 3 Kolay Adımda Yükseltin - -1. [Studio Ortamınızı Kurun](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Subgraph'inizi Studio'ya Dağıtın](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [The Graph Ağı'nda Yayımlayın](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Stüdyo Ortamınızı Ayarlayın - -### Subgraph Studio'da Bir Subgraph Oluştur - -- [Subgraph Studio](https://thegraph.com/studio/)'ya gidin ve cüzdanınızı bağlayın. -- "Subgraph Oluştur" düğmesine tıklayın. Subgraph'in adını başlık formunda vermeniz önerilir: "Subgraph Adı Ağ Adı". - -> Not: Yayımladıktan sonra subgraph ismi değiştirilebilir, ancak bunu yapmak her seferinde zincir üzerinde işlem gerektirir. Bu yüzden isim verirken iyi düşünün. - -### Graph CLI'ı Yükle - -Graph CLI'ı kullanmak için [Node.js](https://nodejs.org/) ve tercih ettiğiniz bir paket yöneticisi (`npm` veya `pnpm`) kurulu olmalıdır. [En son](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI sürümünü kontrol edin. - -Yerel makinenizde şu komutu çalıştırın: - -[npm](https://www.npmjs.com/) kullanarak: - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -CLI kullanarak Studio'da subgraph oluşturmak için aşağıdaki komutu kullanın: - -```sh -graph init --product subgraph-studio -``` - -### Subgraph'inizi Doğrulayın - -The Graph CLI'da, Subgraph Studio'da görülen auth komutunu kullanın: - -```sh -graph auth -``` - -## 2. Subgraph'inizi Studio'ya Dağıtın - -Kaynak kodunuz elinizdeyse kodunuzu Studio'ya kolayca dağıtabilirsiniz. Kaynak kodunuza sahip değilseniz, subgraph'inizi dağıtmanın hızlı yolunu aşağıda bulabilirsiniz. - -The Graph CLI'de aşağıdaki komutu çalıştırın: - -```sh -graph deploy --ipfs-hash - -``` - -> **Not:** Her subgraph'in bir IPFS hash değeri (Dağıtım Kimliği) vardır ve bu şekilde görünür: "Qmasdfad...". Dağıtmak için bu **IPFS hash'ini** kullanmanız yeterlidir. Sizden bir versiyon girmeniz istenecektir (örneğin, v0.0.1). - -## 3. Subgraph'inizi The Graph Ağı'nda Yayımlayın - -![yayımla butonu](/img/publish-sub-transfer.png) - -### Subgraph'inizi Sorgulayın - -> Subgraph'inizi sorgulamak için yaklaşık üç endeksleyici çekmek için, en az 3000 GRT ile kürasyon yapmanız önerilir. Kürasyon hakkında daha fazla bilgi için, The Graph üzerindeki [Kürasyon](/resources/roles/curating/) sayfasına göz atın. - -Herhangi bir subgraph'i [sorgulamaya](/subgraphs/querying/introduction/) başlamak için, bir GraphQL sorgusunu subgraph’in sorgu URL uç noktasına gönderebilirsiniz. Bu uç nokta Subgraph Studio'daki Gezgin sayfasının üst kısmında bulunur. - -#### Örnek - -Messari tarafından hazırlanmış [CryptoPunks Ethereum subgraph'i](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK): - -![Sorgu URL'si](/img/cryptopunks-screenshot-transfer.png) - -Bu subgraph için sorgu URL'si: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**kendi-api-anahtarınız**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Artık, bu uç noktaya GraphQL sorguları göndermeye başlamak için **kendi API Anahtarınızı** girmeniz yeterlidir. - -### Kendi API Anahtarınızı Almak - -API Anahtarlarını Subgraph Studio'da sayfanın üst kısmındaki “API Anahtarları” menüsünden oluşturabilirsiniz: - -![API anahtarları](/img/Api-keys-screenshot.png) - -### Subgraph Durumunu İzle - -Yükseltme yaptıktan sonra, [Subgraph Studio](https://thegraph.com/studio/) üzerinde subgraph'lerinize erişip onları yönetebilirsiniz. Ayrıca, [The Graph Gezgini](https://thegraph.com/networks/) içindeki tüm subgraph'leri burada keşfedebilirsiniz. - -### Ek Kaynaklar - -- Hızlı bir şekilde yeni bir subgraph oluşturmak ve yayımlamak için [Hızlı Başlangıç](/subgraphs/quick-start/) bölümüne göz atın. -- Daha iyi bir performans için subgraph'inizi optimize etmenin ve özelleştirmenin tüm yollarını keşfetmek için [subgraph oluşturma](/developing/creating-a-subgraph/) hakkında daha fazla okuyun. diff --git a/website/src/pages/tr/subgraphs/guides/_meta.js b/website/src/pages/tr/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/tr/subgraphs/guides/arweave.mdx b/website/src/pages/tr/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/tr/subgraphs/guides/enums.mdx b/website/src/pages/tr/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/tr/subgraphs/guides/grafting.mdx b/website/src/pages/tr/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/tr/subgraphs/guides/near.mdx b/website/src/pages/tr/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/tr/subgraphs/guides/polymarket.mdx b/website/src/pages/tr/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/tr/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/tr/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/tr/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/tr/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/tr/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/tr/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/tr/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/tr/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/tr/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/uk/subgraphs/_meta-titles.json b/website/src/pages/uk/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/uk/subgraphs/_meta-titles.json +++ b/website/src/pages/uk/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/uk/subgraphs/_meta.js b/website/src/pages/uk/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/uk/subgraphs/_meta.js +++ b/website/src/pages/uk/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/uk/subgraphs/cookbook/_meta.js b/website/src/pages/uk/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/uk/subgraphs/cookbook/arweave.mdx b/website/src/pages/uk/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 6b54757440a0..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Building Subgraphs on Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. - -## What is Arweave? - -The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. - -Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## What are Arweave Subgraphs? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Building an Arweave Subgraph - -To be able to build and deploy Arweave Subgraphs, you need two packages: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Subgraph's components - -There are three components of a subgraph: - -### 1. Manifest - `subgraph.yaml` - -Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. - -### 2. Schema - `schema.graphql` - -Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. - -During subgraph development there are two key commands: - -``` -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -## Визначення маніфесту підграфів - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet - -Arweave data sources support two types of handlers: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> The source.owner can be the owner's address, or their Public Key. -> -> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Визначення схеми - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Querying an Arweave Subgraph - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Приклади підграфів - -Here is an example subgraph for reference: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Can a subgraph index Arweave and other chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can I index the stored files on Arweave? - -Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). - -### Can I identify Bundlr bundles in my subgraph? - -This is not currently supported. - -### How can I filter transactions to a specific account? - -The source.owner can be the user's public key or account address. - -### What is the current encryption format? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/uk/subgraphs/cookbook/enums.mdx b/website/src/pages/uk/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 4fa07dc05765..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Додаткові матеріали - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/uk/subgraphs/cookbook/grafting.mdx b/website/src/pages/uk/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 5455042183df..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Замініть контракт та збережіть його історію за допомогою графтингу ---- - -У цьому гайді ви дізнаєтеся, як створювати та розгортати нові підграфи шляхом поєднання наявних підграфів. - -## Що таке Grafting? - -При цьому процесі повторно використовуються дані з наявного підграфа і починається їх індексування з наступного блоку. Це корисно під час розробки для швидкого усунення простих помилок у схемах або для тимчасового відновлення працездатності наявного підграфа після його збою. Також його можна використовувати при додаванні об'єкта до підграфа, індексація якого з нуля займає багато часу. - -Підграф, утворений в результаті може використовувати схему GraphQL, яка не є ідентичною схемі базового підграфа, а лише сумісною з нею. Вона повинна бути валідною схемою підграфа сама по собі, але може відхилятися від схеми базового підграфа у такому випадку: - -- Додає або видаляє типи елементів -- Видаляє атрибути з типів елементів -- Додає до типів об'єктів атрибути, які можна скасувати -- Перетворює атрибути, які не можна скасувати, на атрибути, які можна скасувати -- Додає значення до переліків -- Додає або видаляє інтерфейси -- Визначає, для яких типів елементів реалізовано інтерфейс - -Для отримання додаткової інформації ви можете ознайомитися: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Важливе зауваження щодо графтингу при оновленні в мережі - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Чому це так важливо? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Найкращі практики - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -Дотримуючись цих рекомендацій, ви мінімізуєте ризики та забезпечите безперешкодний процес міграції. - -## Побудова наявного підграфа - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Визначення маніфесту підграфів - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Визначення Grafting Manifest - -Графтинг вимагає додавання двох нових елементів до оригінального маніфесту підграфів: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Розгортання базового підграфа - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Закінчивши, перевірте, чи правильно індексується підграф. Ви можете зробити це запустивши наступну команду у вікні The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Це повертає щось на зразок цього: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Після того, як ви переконалися, що підграф індексується належним чином, ви можете швидко оновити його за допомогою графтингу. - -## Розгортання підграфів для графтингу - -При цьому процесі підрозділ subgraph.yaml матиме нову адресу контракту. Це може статися, коли ви оновлюєте децентралізований додаток, перерозподіляєте контракт тощо. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Закінчивши, перевірте, чи правильно індексується підграф. Ви можете зробити це запустивши наступну команду у вікні The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -Це має повернути наступне: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Додаткові матеріали - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/uk/subgraphs/cookbook/near.mdx b/website/src/pages/uk/subgraphs/cookbook/near.mdx deleted file mode 100644 index a94bd9531fdb..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: Building Subgraphs on NEAR ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## What is NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## What are NEAR subgraphs? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Block handlers: these are run on every new block -- Receipt handlers: run every time a message is executed at a specified account - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. - -## Building a NEAR Subgraph - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> Building a NEAR subgraph is very similar to building a subgraph that indexes Ethereum. - -There are three aspects of subgraph definition: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -During subgraph development there are two key commands: - -```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -### Визначення маніфесту підграфів - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR data sources support two types of handlers: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### Визначення схеми - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## Deploying a NEAR Subgraph - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -The node configuration will depend on where the subgraph is being deployed. - -### Субграф Студія - -```sh -graph auth -graph deploy -``` - -### Local Graph Node (based on default configuration) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### Indexing NEAR with a Local Graph Node - -Running a Graph Node that indexes NEAR has the following operational requirements: - -- NEAR Indexer Framework with Firehose instrumentation -- NEAR Firehose Component(s) -- Graph Node with Firehose endpoint configured - -We will provide more information on running the above components soon. - -## Querying a NEAR Subgraph - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Приклади підграфів - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### How does the beta work? - -NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! - -### Can a subgraph index both NEAR and EVM chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can subgraphs react to more specific triggers? - -Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. - -### Will receipt handlers trigger for accounts and their sub-accounts? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### Can NEAR subgraphs make view calls to NEAR accounts during mappings? - -This is not supported. We are evaluating whether this functionality is required for indexing. - -### Can I use data source templates in my NEAR subgraph? - -This is not currently supported. We are evaluating whether this functionality is required for indexing. - -### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? - -Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. - -### My question hasn't been answered, where can I get more help building NEAR subgraphs? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## References - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/uk/subgraphs/cookbook/polymarket.mdx b/website/src/pages/uk/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/uk/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/uk/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index fc7e0ff52eb4..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## Overview - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/uk/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/uk/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 6610f19da66d..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Quick and Easy Subgraph Debugging Using Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## Ok, what is it? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## What?! How? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## Please, show me some code! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -The usual way to attempt a fix is: - -1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Wait for it to sync-up. -4. If it breaks again go back to 1, otherwise: Hooray! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. If it breaks again, go back to 1, otherwise: Hooray! - -Now, you may have 2 questions: - -1. fork-base what??? -2. Forking who?! - -And I answer: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Forking is easy, no need to sweat: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -So, here is what I do: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/uk/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/uk/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 0cc91a0fa2c3..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Safe Subgraph Code Generator ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Why integrate with Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/uk/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/uk/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index aed61c2c695b..000000000000 --- a/website/src/pages/uk/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Example - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Додаткові матеріали - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/uk/subgraphs/guides/_meta.js b/website/src/pages/uk/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/uk/subgraphs/guides/arweave.mdx b/website/src/pages/uk/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/uk/subgraphs/guides/enums.mdx b/website/src/pages/uk/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/uk/subgraphs/guides/grafting.mdx b/website/src/pages/uk/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/uk/subgraphs/guides/near.mdx b/website/src/pages/uk/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/uk/subgraphs/guides/polymarket.mdx b/website/src/pages/uk/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/uk/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/uk/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/uk/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/uk/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/uk/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/uk/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/uk/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/uk/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/uk/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ur/subgraphs/_meta-titles.json b/website/src/pages/ur/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/ur/subgraphs/_meta-titles.json +++ b/website/src/pages/ur/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/ur/subgraphs/_meta.js b/website/src/pages/ur/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/ur/subgraphs/_meta.js +++ b/website/src/pages/ur/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/ur/subgraphs/cookbook/_meta.js b/website/src/pages/ur/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/ur/subgraphs/cookbook/arweave.mdx b/website/src/pages/ur/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 035056b7f5a6..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: بناۓ گئے سب گرافز آرویو(Arweave) پر ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -اس گائڈ میں، آپ سیکھیں گے کہ آرویو(Arweave) بلاکچین کو انڈیکس کرنے کیلئے سب گرافز بنانے اور مستعمل کرنے کا طریقہ کار کیسے ہے۔ - -## آرویو(Arweave) کیا ہے؟ - -آرویو (Arweave) پروٹوکول ڈیولپرز کو اجازت دیتا کے وہ ڈیٹا کو مستقل طور پر اسٹور کرے اور یہی آرویو(Arweave) اور IPFS میں سب سے بڑا فرق ہے،جہاں IPFS میں خصوصیئت کی کمی ہے؛مستقل مزاجی ، اور فایلز جو آرویو(Arweave) پر اسٹور ہوتی ہیں بدل یا ختم نہیں ہو سکتی. - -آرویو(Arweave) نے پہلے ہی بہت سی کتابخانےاں تیار کی ہیں جو مختلف پروگرامنگ زبانوں میں پروٹوکول کو اندر ملانے کے لئے بنائی گئی ہیں۔ مزید معلومات کے لئے آپ یہ چیک کر سکتے ہیں: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## آرویو(Arweave) سب گرافز کیا ہوتے ہیں؟ - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## آرویو(Arweave) سب گراف بنانا - -آرویو کے سب گراف بنانے اور تعینات کرنے کے لئے،آپ کو دو پیکجوں کی ضرورت ہے: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## سب گراف کے حصے - -سب گراف کے تین حصے ہیں: - -### 1. Manifest - `subgraph.yaml` - -دلچسپی کے ڈیٹا کے ذرایع کو بیان کرتا ہے،اور کیسے ان پر کاروائ کی جاۓ۔ آرویو ایک نئ طرح کا ڈیٹا کا ذریعہ ہے. - -### 2. Schema - `schema.graphql` - -یہاں آپ بیان کرتے ہیں کے کونسا ڈیٹا آپ کے سب گراف کا کیوری گراف کیو ایل کا استعمال کرتے ہوۓ کر سکے۔یہ دراصل اے پی آی(API) کے ماڈل سے ملتا ہے،جہاں ماڈل درخواست کے جسم کے ڈھانچے کو بیان کرتا ہے. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -یہ وہ منطق جو اس بات کا پتہ لگاتا ہے کے کیسے ڈیٹا کو بازیافت اور مہفوظ کیا جاۓ جب کوئ اس ڈیٹا کے ذخیرہ سے تعامل کرے جسے آپ سن رہے ہیں۔اس ڈیٹا کا ترجمہ کیا جاتا ہے اور آپ کے درج کردہ اسکیما کی بنیاد پر مہفوظ کیا جاتا ہے. - -سب گراف کی ترقی کے دوران دو اہم کمانڈز ہیں: - -``` -$graph codegen # ظاہر میں شناخت کردہ اسکیما فائل سے اقسام تیار کرتا ہے۔ -$graph build # اسمبلی سکرپٹ فائلوں سے ویب اسمبلی تیار کرتا ہے، اور تمام ذیلی گراف فائلوں کو /build فولڈر میں تیار کرتا ہے۔ -``` - -## سب گراف مینی فیسٹ کی تعریف - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- آرویو ڈیٹا کے ذرائع ایک اختیاری source.owner فیلڈ متعارف کراتے ہیں، جو آرویو والیٹ کی عوامی کلید ہے - -آرویو ڈیٹا کے ذرائع دو قسم کے ہینڈلرز کو سپورٹ کرتے ہیں: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> Source.owner مالک کا پتہ، یا ان کی عوامی کلید ہو سکتا ہے. -> -> ٹرانزیکشنز آرویو پرما ویب کے تعمیراتی بلاکس ہیں اور یہ آخری صارفین کے ذریعہ تخلیق کردہ اشیاء ہیں. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## اسکیما کی تعریف - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## اسمبلی اسکرپٹ سب میپنک - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## آرویو سب گراف سے کیوری کرنا - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## سب گراف کی مثال - -حوالہ کے لیے سب گراف کی ایک مثال یہ ہے: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### کیا ایک سب گراف آرویو اور دیگر چینس کو انڈیکس کر سکتا ہے؟ - -نہیں، ایک سب گراف صرف ایک چین/نیٹ ورک سے ڈیٹا کے ذرائع کو سپورٹ کر سکتا ہے. - -### کیا میں آرویو پر ذخیرہ شدہ فائلوں کو انڈیکس کر سکتا ہوں؟ - -فی الحال، دی گراف صرف آرویو کو بلاک چین (اس کے بلاکس اور لین دین) کے طور پر ترتیب دے رہا ہے. - -### کیا میں اپنے سب گراف میں Bundlr کے بنڈلوں کی شناخت کر سکتا ہوں؟ - -یہ فی الحال سپورٹڈ نہیں ہے. - -### میں کسی مخصوص اکاؤنٹ میں لین دین کو کیسے فلٹر کر سکتا ہوں؟ - -Source.owner صارف کی عوامی کلید یا اکاؤنٹ ایڈریس ہو سکتا ہے. - -### موجودہ خفیہ کاری کا فارمیٹ کیا ہے؟ - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/ur/subgraphs/cookbook/enums.mdx b/website/src/pages/ur/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 8991c45dd81a..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## اضافی وسائل - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ur/subgraphs/cookbook/grafting.mdx b/website/src/pages/ur/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 6cda9bfe1f6e..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: ایک کنٹریکٹ کو تبدیل کریں اور اس کی تاریخ کو گرافٹنگ کے ساتھ رکھیں ---- - -اس گائیڈ میں، آپ سیکھیں گے کہ موجودہ سب گراف کو گرافٹنگ کرکے نئے سب گراف کیسے بنائے اور ان کو تعینات کریں. - -## گرافٹنگ کیا ہے؟ - -گرافٹنگ موجودہ سب گراف سے ڈیٹا کو دوبارہ استعمال کرتا ہے اور اسے بعد کے بلاک میں انڈیکس کرنا شروع کرتا ہے۔ میپنگ میں ماضی کی سادہ غلطیوں کو تیزی سے حاصل کرنے یا کسی موجودہ سب گراف کے ناکام ہونے کے بعد اسے عارضی طور پر دوبارہ کام کرنے کے لیے یہ ترقی کے دوران مفید ہے۔ نیز، اس کا استعمال کسی سب گراف میں فیچر شامل کرتے وقت کیا جا سکتا ہے جو شروع سے انڈیکس میں زیادہ وقت لیتا ہے. - -گرافٹڈ سب گراف ایک گراف کیو ایل اسکیما استعمال کرسکتا ہے جو بیس سب گراف میں سے ایک سے مماثل نہیں ہے، لیکن اس کے ساتھ محض مطابقت رکھتا ہے۔ اسے اپنے طور پر ایک درست سب گراف سکیما ہونا چاہیے، لیکن درج ذیل طریقوں سے بنیادی سب گراف کے سکیما سے انحراف ہو سکتا ہے: - -- یہ ہستی کی اقسام کو جوڑتا یا ہٹاتا ہے -- یہ ہستی کی اقسام سے صفات کو ہٹاتا ہے -- یہ ہستی کی قسموں میں کالعدم صفات کو شامل کرتا ہے -- یہ غیر کالعدم صفات کو کالعدم صفات میں بدل دیتا ہے -- یہ enums میں اقدار کا اضافہ کرتا ہے -- یہ انٹرفیس کو جوڑتا یا ہٹاتا ہے -- یہ تبدیل ہوتا ہے جس کے لیے ایک انٹرفیس لاگو کیا جاتا ہے - -مزید معلومات کے لۓ، آپ دیکہ سکتے ہیں: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## نیٹ ورک میں اپ گریڈ کرتے وقت گرافٹنگ پر اہم نوٹ - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### یہ کیوں اہم ہے؟ - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### بہترین طریقے - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -ان رہنما خطوط پر عمل پیرا ہو کر، آپ خطرات کو کم کرتے ہیں اور منتقلی کے ایک ہموار عمل کو یقینی بناتے ہیں. - -## ایک موجودہ سب گراف بنانا - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## سب گراف مینی فیسٹ کی تعریف - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## گرافٹنگ مینی فیسٹ کی تعریف - -گرافٹنگ کے لیے اصل سب گراف مینی فیسٹ میں دو نئے آئٹمز شامل کرنے کی ضرورت ہے: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## بیس سب گراف تعینات کرنا - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. ایک دفعہ ختم ہو جاۓ، تصدیق کریں کے سب گراف صحیح سے انڈیکس ہو رہا ہے. اگر آپ درج کمانڈ گراف پلے گراونڈ میں چلائیں - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -یہ کچھ اس طرح لوٹاتا ہے: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -ایک بار آپ نے تصدیق کر لی کے سب گراف صحیح سے انڈیکس ہو رہا، آپ جلدی سے گرافٹنگ سے اسے اپڈیٹ کر سکتے ہیں. - -## گرافٹنگ سب گراف کو تعینات کرنا - -گرافٹ متبادل subgraph.yaml کے پاس ایک نیا کنٹریکٹ ایڈریس ہوگا۔ یہ اس وقت ہو سکتا ہے جب آپ اپنے ڈیپ کو اپ ڈیٹ کرتے ہیں، کسی کنٹریکٹ کو دوبارہ استعمال کرتے ہیں، وغیر. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. ایک دفعہ ختم ہو جاۓ، تصدیق کریں کے سب گراف صحیح سے انڈیکس ہو رہا ہے. اگر آپ درج کمانڈ گراف پلے گراونڈ میں چلائیں - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -اسے مندرجہ ذیل کو واپس کرنا چاہئے: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## اضافی وسائل - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ur/subgraphs/cookbook/near.mdx b/website/src/pages/ur/subgraphs/cookbook/near.mdx deleted file mode 100644 index 3ff637ebf556..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: سب گرافس کو NEAR پر بنانا ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## NEAR کیا ہے؟ - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## NEAR سب گراف کیا ہیں؟ - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- بلاک ہینڈلرز: یہ ہر نۓ بلاک پر چلتے ہیں -- ریسیپٹ ہینڈلرز: ہر بار جب کسی مخصوص اکاؤنٹ پر کوئی پیغام عمل میں آۓ تو چلتا ہے - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> نظام میں ایک ریسیپٹ واحد قابل عمل شے ہے۔ جب ہم NEAR پلیٹ فارم پر "ایک ٹرانزیکشن پر کارروائی" کے بارے میں بات کرتے ہیں، تو اس کا مطلب بالآخر کسی وقت "ریسیپٹ لگانا" ہوتا ہے. - -## NEAR سب گراف بنانا - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> NEAR سب گراف کی تعمیر ایک سب گراف بنانے کے مترادف ہے جو ایتھریم کو انڈیکس کرتا ہے. - -سب گراف کی تعریف کے تین پہلو ہیں: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -سب گراف کی ترقی کے دوران دو اہم کمانڈز ہیں: - -```bash -$graph codegen # ظاہر میں شناخت کردہ اسکیما فائل سے اقسام تیار کرتا ہے۔ -$graph build # اسمبلی سکرپٹ فائلوں سے ویب اسمبلی تیار کرتا ہے، اور تمام ذیلی گراف فائلوں کو /build فولڈر میں تیار کرتا ہے۔ -``` - -### سب گراف مینی فیسٹ کی تعریف - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -قریبی ڈیٹا ذرائع دو قسم کے ہینڈلرز کی حمایت کرتے ہیں: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### اسکیما کی تعریف - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### اسمبلی اسکرپٹ سب میپنک - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## NEAR سب گراف کی تعیناتی - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -نوڈ کنفیگریشن کا انحصار اس بات پر ہوگا کہ سب گراف کہاں تعینات کیا جا رہا ہے. - -### سب گراف سٹوڈیو - -```sh -graph auth -graph deploy -``` - -### مقامی گراف نوڈ (پہلے سے طے شدہ ترتیب پر مبنی) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -ایک دفعہ آپ کا سب گراف تعینات ہو جاۓ، گراف نوڈ اسے انڈیکس کرے گا. آپ سب گراف سے ہی کیوری کرکے اس کی پیشرفت چیک کرسکتے ہیں: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### NEAR کو مقامی گراف نوڈ سے انڈیکس کرنا - -ایک گراف نوڈ چلانا جو NEAR کو انڈیکس کرتا ہے اس کے لیے درج ذیل آپریشنل تقاضے ہوتے ہیں: - -- فائر ہوز انسٹرومینٹیشن کے ساتھ NEAR انڈیکسر فریم ورک -- NEAR فائر ہوز اجزاء -- فائر ہوز اینڈ پوائنٹ کے ساتھ گراف نوڈ کنفیگر ہو گیا - -ہم جلد ہی مندرجہ بالا اجزاء کو چلانے کے بارے میں مزید معلومات فراہم کریں گے. - -## NEAR سب گراف کا کیوری کرنا - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## سب گراف کی مثال - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### بیٹا کیسے کام کرتا ہے؟ - -NEAR سپورٹ بیٹا میں ہے، جس کا مطلب ہے کہ API میں تبدیلیاں ہو سکتی ہیں کیونکہ ہم انضمام کو بہتر بنانے پر کام جاری رکھے ہوئے ہیں۔ براہ کرم near@thegraph.com پر ای میل کریں تاکہ ہم NEAR سب گراف بنانے میں آپ کی مدد کر سکیں، اور آپ کو تازہ ترین پیش رفت سے آگاہ رکھ سکیں! - -### کیا ایک سب گراف دونو NEAR اور EVM چینز کو انڈیکس ہو سکتا ہے؟ - -نہیں، ایک سب گراف صرف ایک چین/نیٹ ورک سے ڈیٹا کے ذرائع کو سپورٹ کر سکتا ہے. - -### کیا سب گراف زیادہ مخصوص محرکات پر ردعمل ظاہر کر سکتے ہیں؟ - -فی الحال، صرف بلاک اور رسید کے محرکات تعاون یافتہ ہیں۔ ہم ایک مخصوص اکاؤنٹ پر فنکشن کالز کے محرکات کی چھان بین کر رہے ہیں۔ ہم ایونٹ کے محرکات کو سپورٹ کرنے میں بھی دلچسپی رکھتے ہیں، ایک بار جب NEAR کو مقامی ایونٹ سپورٹ مل جائے. - -### کیا رسید ہینڈلرز اکاؤنٹس اور ان کے سب اکاؤنٹس کو متحرک کریں گے؟ - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### کیا میپنگ کے دوران NEAR سب گرافس NEAR اکاؤنٹس کو ویو کال کر سکتے ہیں؟ - -یہ تعاون یافتہ نہیں ہے۔ ہم اس بات کا جائزہ لے رہے ہیں کہ آیا یہ فعالیت انڈیکسنگ کے لیے درکار ہے. - -### کیا میں اپنے NEAR سب گراف میں ڈیٹا سورس ٹیمپلیٹس استعمال کر سکتا ہوں؟ - -یہ فی الحال تعاون یافتہ نہیں ہے۔ ہم اس بات کا جائزہ لے رہے ہیں کہ آیا یہ فعالیت اشاریہ سازی کے لیے درکار ہے. - -### ایتھیریم سب گرافس "پینڈنگ" اور "موجودہ" ورژن کی حمایت کرتے ہیں، میں NEAR سب گراف کے "پینڈنگ" ورژن کو کیسے تعینات کر سکتا ہوں؟ - -زیر التواء فعالیت ابھی تک NEAR سب گراف کے لیے تعاون یافتہ نہیں ہے۔ عبوری طور پر، آپ ایک نئے ورژن کو ایک مختلف "نام والے" سب گراف میں تعینات کر سکتے ہیں، اور پھر جب وہ چین ہیڈ کے ساتھ مطابقت پذیر ہو جاتا ہے، تو آپ اپنے بنیادی "نام والے" سب گراف پر دوبارہ تعینات کر سکتے ہیں، جو اسی بنیادی تعیناتی ID کو استعمال کرے گا، لہذا مرکزی سب گراف کو فوری طور پر ہم آہنگ کیا جائے گا. - -### میرے سوال کا جواب نہیں دیا گیا ہے، مجھے NEAR سب گراف بنانے میں مزید مدد کہاں سے مل سکتی ہے؟ - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## حوالہ جات - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ur/subgraphs/cookbook/polymarket.mdx b/website/src/pages/ur/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ur/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/ur/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index 132c4cd07884..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## جائزہ - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ur/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/ur/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 7a0dadaa4dfe..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: فورکس کا استعمال کرتے ہوۓ تیز اور آسان ڈیبگنگ ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## ٹھیک ہے، یہ ہے کیا؟ - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## کیا؟! کیسے؟ - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## براۓ مہربانی، مجہے کچھ کوڈ دکھائیں! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -درست کرنے کی کوشش کرنے کا معمول کا طریقہ یہ ہے: - -1. میپنگ کے ماخذ میں تبدیلی کریں، جس کے بارے میں آپ کو یقین ہے کہ مسئلہ حل ہو جائے گا (جبکہ میں جانتا ہوں کہ ایسا نہیں ہوگا). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. اس کے مطابقت پذیر ہونے کا انتظار کریں. -4. اگر یہ دوبارہ ٹوٹ جاتا ہے تو 1 پر واپس جائیں، ورنہ: ہورے! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. میپنگ کے ماخذ میں تبدیلی کریں، جس سے آپ کو یقین ہے کہ مسئلہ حل ہو جائے گا. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. اگر یہ دوبارہ ٹوٹ جاتا ہے، تو 1 پر واپس جائیں، ورنہ: ہورے! - -اب، آپ کے پاس 2 سوالات ہوسکتے ہیں: - -1. فورک بیس کیا؟؟؟ -2. فورکنگ کون؟! - -اور میرا جواب: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. فورکنگ آسان ہے، پریشان ہونے کی ضرورت نہیں ہے: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -تو، یہاں میں کیا کرتا ہوں: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ur/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/ur/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 1ce722e5639d..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: محفوظ سب گراف کوڈ جنریٹر ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## سب گراف ان کریش ایبل کے ساتھ کیوں ضم کیا جائے؟ - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- فریم ورک میں ہستی متغیرات کے گروپس کے لیے حسب ضرورت، لیکن محفوظ، سیٹر فنکشنز بنانے کا ایک طریقہ (کنفگ فائل کے ذریعے) بھی شامل ہے۔ اس طرح صارف کے لیے کسی باسی گراف ہستی کو لوڈ/استعمال کرنا ناممکن ہے اور فنکشن کے لیے مطلوبہ متغیر کو محفوظ کرنا یا سیٹ کرنا بھولنا بھی ناممکن ہے. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -گراف CLI کوڈجن کمانڈ کا استعمال کرتے ہوئے سب گراف ان کریش ایبل کو اختیاری پرچم کے طور پر چلایا جا سکتا ہے. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/ur/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/ur/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 43fd50c14672..000000000000 --- a/website/src/pages/ur/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -[npm](https://www.npmjs.com/) کا استعمال: - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### مثال - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### اضافی وسائل - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ur/subgraphs/guides/_meta.js b/website/src/pages/ur/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/ur/subgraphs/guides/arweave.mdx b/website/src/pages/ur/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/ur/subgraphs/guides/enums.mdx b/website/src/pages/ur/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/ur/subgraphs/guides/grafting.mdx b/website/src/pages/ur/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/ur/subgraphs/guides/near.mdx b/website/src/pages/ur/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/ur/subgraphs/guides/polymarket.mdx b/website/src/pages/ur/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/ur/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/ur/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/ur/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/ur/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/ur/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/ur/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/ur/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/ur/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/ur/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/vi/subgraphs/_meta-titles.json b/website/src/pages/vi/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/vi/subgraphs/_meta-titles.json +++ b/website/src/pages/vi/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/vi/subgraphs/_meta.js b/website/src/pages/vi/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/vi/subgraphs/_meta.js +++ b/website/src/pages/vi/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/vi/subgraphs/cookbook/_meta.js b/website/src/pages/vi/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/vi/subgraphs/cookbook/arweave.mdx b/website/src/pages/vi/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 2372025621d1..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: Building Subgraphs on Arweave ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. - -## What is Arweave? - -The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. - -Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## What are Arweave Subgraphs? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## Building an Arweave Subgraph - -To be able to build and deploy Arweave Subgraphs, you need two packages: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## Subgraph's components - -There are three components of a subgraph: - -### 1. Manifest - `subgraph.yaml` - -Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. - -### 2. Schema - `schema.graphql` - -Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. - -During subgraph development there are two key commands: - -``` -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder -``` - -## Subgraph Manifest Definition - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet - -Arweave data sources support two types of handlers: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> The source.owner can be the owner's address, or their Public Key. -> -> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## Schema Definition - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript Mappings - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## Querying an Arweave Subgraph - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## Example Subgraphs - -Here is an example subgraph for reference: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### Can a subgraph index Arweave and other chains? - -No, a subgraph can only support data sources from one chain/network. - -### Can I index the stored files on Arweave? - -Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). - -### Can I identify Bundlr bundles in my subgraph? - -This is not currently supported. - -### How can I filter transactions to a specific account? - -The source.owner can be the user's public key or account address. - -### What is the current encryption format? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/vi/subgraphs/cookbook/enums.mdx b/website/src/pages/vi/subgraphs/cookbook/enums.mdx deleted file mode 100644 index a10970c1539f..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## Additional Resources - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/vi/subgraphs/cookbook/grafting.mdx b/website/src/pages/vi/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 2d9b2a16a1ef..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Replace a Contract and Keep its History With Grafting ---- - -In this guide, you will learn how to build and deploy new subgraphs by grafting existing subgraphs. - -## What is Grafting? - -Grafting reuses the data from an existing subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing subgraph working again after it has failed. Also, it can be used when adding a feature to a subgraph that takes long to index from scratch. - -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right, but may deviate from the base subgraph's schema in the following ways: - -- It adds or removes entity types -- It removes attributes from entity types -- It adds nullable attributes to entity types -- It turns non-nullable attributes into nullable attributes -- It adds values to enums -- It adds or removes interfaces -- Nó thay đổi đối với loại thực thể nào mà một giao diện được triển khai - -For more information, you can check: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## Building an Existing Subgraph - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## Subgraph Manifest Definition - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## Grafting Manifest Definition - -Grafting requires adding two new items to the original subgraph manifest: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## Deploying the Base Subgraph - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It returns something like this: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -Once you have verified the subgraph is indexing properly, you can quickly update the subgraph with grafting. - -## Deploying the Grafting Subgraph - -The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. Once finished, verify the subgraph is indexing properly. If you run the following command in The Graph Playground - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It should return the following: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## Additional Resources - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/vi/subgraphs/cookbook/polymarket.mdx b/website/src/pages/vi/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/vi/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/vi/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index e83414fea5e5..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## Tổng quan - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/vi/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/vi/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 6610f19da66d..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Quick and Easy Subgraph Debugging Using Forks ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## Ok, what is it? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## What?! How? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## Please, show me some code! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -The usual way to attempt a fix is: - -1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Wait for it to sync-up. -4. If it breaks again go back to 1, otherwise: Hooray! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. Make a change in the mappings source, which you believe will solve the issue. -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. If it breaks again, go back to 1, otherwise: Hooray! - -Now, you may have 2 questions: - -1. fork-base what??? -2. Forking who?! - -And I answer: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. Forking is easy, no need to sweat: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -So, here is what I do: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/vi/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/vi/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 0cc91a0fa2c3..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Safe Subgraph Code Generator ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## Why integrate with Subgraph Uncrashable? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/vi/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/vi/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 78493fe55b06..000000000000 --- a/website/src/pages/vi/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### Ví dụ - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### Additional Resources - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/vi/subgraphs/guides/_meta.js b/website/src/pages/vi/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/vi/subgraphs/guides/arweave.mdx b/website/src/pages/vi/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/vi/subgraphs/guides/enums.mdx b/website/src/pages/vi/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/vi/subgraphs/guides/grafting.mdx b/website/src/pages/vi/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/vi/subgraphs/guides/near.mdx b/website/src/pages/vi/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/vi/subgraphs/guides/polymarket.mdx b/website/src/pages/vi/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/vi/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/vi/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/vi/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/vi/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/vi/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/vi/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/vi/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/vi/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/vi/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/zh/subgraphs/_meta-titles.json b/website/src/pages/zh/subgraphs/_meta-titles.json index 0556abfc236c..3fd405eed29a 100644 --- a/website/src/pages/zh/subgraphs/_meta-titles.json +++ b/website/src/pages/zh/subgraphs/_meta-titles.json @@ -1,6 +1,6 @@ { "querying": "Querying", "developing": "Developing", - "cookbook": "Cookbook", + "guides": "How-to Guides", "best-practices": "Best Practices" } diff --git a/website/src/pages/zh/subgraphs/_meta.js b/website/src/pages/zh/subgraphs/_meta.js index 3b490f214d14..ed3e5db7a6f0 100644 --- a/website/src/pages/zh/subgraphs/_meta.js +++ b/website/src/pages/zh/subgraphs/_meta.js @@ -6,6 +6,6 @@ export default { querying: titles.querying, developing: titles.developing, billing: '', - cookbook: titles.cookbook, + guides: titles.guides, 'best-practices': titles['best-practices'], } diff --git a/website/src/pages/zh/subgraphs/cookbook/_meta.js b/website/src/pages/zh/subgraphs/cookbook/_meta.js deleted file mode 100644 index 1093ca048416..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/_meta.js +++ /dev/null @@ -1,13 +0,0 @@ -export default { - 'subgraph-composition-three-sources': '', - 'subgraph-composition': '', - 'subgraph-debug-forking': '', - near: '', - arweave: '', - grafting: '', - 'subgraph-uncrashable': '', - 'transfer-to-the-graph': '', - enums: '', - 'secure-api-keys-nextjs': '', - polymarket: '', -} diff --git a/website/src/pages/zh/subgraphs/cookbook/arweave.mdx b/website/src/pages/zh/subgraphs/cookbook/arweave.mdx deleted file mode 100644 index 24eafa5cdebe..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/arweave.mdx +++ /dev/null @@ -1,239 +0,0 @@ ---- -title: 在 Arweave 上构建子图 ---- - -> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave subgraphs! - -在本指南中,您将学习如何构建和部署子图以索引Arweave区块链。 - -## Arweave是什么? - -Arweave 协议允许开发者永久存储数据,这是 Arweave 和 IPFS 的主要区别,IPFS 没有这个特性,永久性和存储在 Arweave 上的文件不能被更改或删除。 - -Arweave 已经构建了许多库,用于将协议集成到许多不同的编程语言中。更多信息可以查看: - -- [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) - -## Arweave子图是什么? - -The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). - -[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. - -## 构建 Arweave 子图 - -为了能够构建和部署 Arweave 子图,您需要两个包: - -1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. -2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. - -## 子图的组成部分 - -一个子图有三个组成部分: - -### 1. Manifest - `subgraph.yaml` - -定义感兴趣的数据源,以及如何处理它们。Arweave是一种新型数据源。 - -### 2. Schema - `schema.graphql` - -在这里,您可以定义在使用 GraphQL 索引子图之后希望能够查询的数据。这实际上类似于 API 的模型,其中模型定义了请求主体的结构。 - -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -### 3. AssemblyScript Mappings - `mapping.ts` - -这种逻辑决定了当有人与您正在监听的数据源进行交互时,应该如何检索和存储数据。数据将被翻译并根据您列出的模式进行存储。 - -在子图开发过程中,有两个关键命令: - -``` -$ graph codegen # 从清单中标识的模式文件生成类型 -$ graph build # 从 AssemblyScript 文件生成 Web Assembly,并在 /build 文件夹中准备所有子图文件 -``` - -## 子图清单定义 - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for an Arweave subgraph: - -```yaml -specVersion: 0.0.5 -description: Arweave Blocks Indexing -schema: - file: ./schema.graphql # link to the schema file -dataSources: - - kind: arweave - name: arweave-blocks - network: arweave-mainnet # The Graph only supports Arweave Mainnet - source: - owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet - startBlock: 0 # set this to 0 to start indexing from chain genesis - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - file: ./src/blocks.ts # link to the file with the Assemblyscript mappings - entities: - - Block - - Transaction - blockHandlers: - - handler: handleBlock # the function name in the mapping file - transactionHandlers: - - handler: handleTx # the function name in the mapping file -``` - -- Arweave subgraphs introduce a new kind of data source (`arweave`) -- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` -- Arweave 数据源引入了一个可选的 source. owner 字段,它是 Arweave 钱包的公钥 - -Arweave 数据源支持两种类型的处理程序: - -- `blockHandlers` - Run on every new Arweave block. No source.owner is required. -- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` - -> Source.Owner 可以是所有者的地址,也可以是他们的公钥。 -> -> 交易是 Arweave permaweb 的构建区块,它们是终端用户创建的对象。 -> -> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. - -## 模式定义 - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -## AssemblyScript 映射 - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```tsx -class Block { - timestamp: u64 - lastRetarget: u64 - height: u64 - indepHash: Bytes - nonce: Bytes - previousBlock: Bytes - diff: Bytes - hash: Bytes - txRoot: Bytes - txs: Bytes[] - walletList: Bytes - rewardAddr: Bytes - tags: Tag[] - rewardPool: Bytes - weaveSize: Bytes - blockSize: Bytes - cumulativeDiff: Bytes - hashListMerkle: Bytes - poa: ProofOfAccess -} - -class Transaction { - format: u32 - id: Bytes - lastTx: Bytes - owner: Bytes - tags: Tag[] - target: Bytes - quantity: Bytes - data: Bytes - dataSize: Bytes - dataRoot: Bytes - signature: Bytes - reward: Bytes -} -``` - -Block handlers receive a `Block`, while transactions receive a `Transaction`. - -Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). - -## Deploying an Arweave Subgraph in Subgraph Studio - -Once your subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. - -```bash -graph deploy --access-token -``` - -## 查询 Arweave 子图 - -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## 示例子图 - -下面是一个子图的例子,以供参考: - -- [Example subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) - -## FAQ - -### 子图可以索引 Arweave 和其他链吗? - -不,子图只能支持来自一个链/网络的数据源。 - -### 我可以索引存储在 Arweave 上的文件吗? - -目前,Graph 只是将 Arweave 索引为区块链(它的区块和交易)。 - -### 我可以识别我的子图中的 Bundlr 包吗? - -目前还不支持。 - -### 如何筛选特定账户的交易? - -Source.owner可以是用户的公钥或账户地址。 - -### 当前的加密格式是什么? - -Data is generally passed into the mappings as Bytes, which if stored directly is returned in the subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). - -The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: - -``` -const base64Alphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" -]; - -const base64UrlAlphabet = [ - "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", - "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", - "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" -]; - -function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { - let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; - - let result = '', i: i32, l = bytes.length; - for (i = 2; i < l; i += 3) { - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; - result += alphabet[bytes[i] & 0x3F]; - } - if (i === l + 1) { // 1 octet yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[(bytes[i - 2] & 0x03) << 4]; - if (!urlSafe) { - result += "=="; - } - } - if (!urlSafe && i === l) { // 2 octets yet to write - result += alphabet[bytes[i - 2] >> 2]; - result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; - result += alphabet[(bytes[i - 1] & 0x0F) << 2]; - if (!urlSafe) { - result += "="; - } - } - return result; -} -``` diff --git a/website/src/pages/zh/subgraphs/cookbook/enums.mdx b/website/src/pages/zh/subgraphs/cookbook/enums.mdx deleted file mode 100644 index 43d1ad4cc0c2..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/enums.mdx +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Categorize NFT Marketplaces Using Enums ---- - -Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. - -## What are Enums? - -Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. - -### Example of Enums in Your Schema - -If you're building a subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. - -You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. - -Here's what an enum definition might look like in your schema, based on the example above: - -```graphql -enum TokenStatus { - OriginalOwner - SecondOwner - ThirdOwner -} -``` - -This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. - -To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). - -## Benefits of Using Enums - -- **Clarity:** Enums provide meaningful names for values, making data easier to understand. -- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. -- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. - -### Without Enums - -If you choose to define the type as a string instead of using an Enum, your code might look like this: - -```graphql -type Token @entity { - id: ID! - tokenId: BigInt! - owner: Bytes! # Owner of the token - tokenStatus: String! # String field to track token status - timestamp: BigInt! -} -``` - -In this schema, `TokenStatus` is a simple string with no specific, allowed values. - -#### Why is this a problem? - -- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. -- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. - -### With Enums - -Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. - -Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. - -## Defining Enums for NFT Marketplaces - -> Note: The following guide uses the CryptoCoven NFT smart contract. - -To define enums for the various marketplaces where NFTs are traded, use the following in your subgraph schema: - -```gql -# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) -enum Marketplace { - OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace - OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace - SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace - LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace - # ...and other marketplaces -} -``` - -## Using Enums for NFT Marketplaces - -Once defined, enums can be used throughout your subgraph to categorize transactions or events. - -For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. - -### Implementing a Function for NFT Marketplaces - -Here's how you can implement a function to retrieve the marketplace name from the enum as a string: - -```ts -export function getMarketplaceName(marketplace: Marketplace): string { - // Using if-else statements to map the enum value to a string - if (marketplace === Marketplace.OpenSeaV1) { - return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation - } else if (marketplace === Marketplace.OpenSeaV2) { - return 'OpenSeaV2' - } else if (marketplace === Marketplace.SeaPort) { - return 'SeaPort' // If the marketplace is SeaPort, return its string representation - } else if (marketplace === Marketplace.LooksRare) { - return 'LooksRare' // If the marketplace is LooksRare, return its string representation - // ... and other market places - } -} -``` - -## Best Practices for Using Enums - -- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. -- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. -- **Documentation:** Add comments to enum to clarify their purpose and usage. - -## Using Enums in Queries - -Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. - -**Specifics** - -- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. -- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. - -### Sample Queries - -#### Query 1: Account With The Highest NFT Marketplace Interactions - -This query does the following: - -- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. -- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. - -```gql -{ - accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { - id - sendCount - receiveCount - totalSpent - uniqueMarketplacesCount - marketplaces { - marketplace # This field returns the enum value representing the marketplace - } - } -} -``` - -#### Returns - -This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: - -```gql -{ - "data": { - "accounts": [ - { - "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", - "sendCount": "44", - "receiveCount": "44", - "totalSpent": "1197500000000000000", - "uniqueMarketplacesCount": "7", - "marketplaces": [ - { - "marketplace": "OpenSeaV1" - }, - { - "marketplace": "OpenSeaV2" - }, - { - "marketplace": "GenieSwap" - }, - { - "marketplace": "CryptoCoven" - }, - { - "marketplace": "Unknown" - }, - { - "marketplace": "LooksRare" - }, - { - "marketplace": "NFTX" - } - ] - } - ] - } -} -``` - -#### Query 2: Most Active Marketplace for CryptoCoven transactions - -This query does the following: - -- It identifies the marketplace with the highest volume of CryptoCoven transactions. -- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. - -```gql -{ - marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { - marketplace - transactionCount - } -} -``` - -#### Result 2 - -The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "Unknown", - "transactionCount": "222" - } - ] - } -} -``` - -#### Query 3: Marketplace Interactions with High Transaction Counts - -This query does the following: - -- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. -- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. - -```gql -{ - marketplaceInteractions( - first: 4 - orderBy: transactionCount - orderDirection: desc - where: { transactionCount_gt: "100", marketplace_not: "Unknown" } - ) { - marketplace - transactionCount - } -} -``` - -#### Result 3 - -Expected output includes the marketplaces that meet the criteria, each represented by an enum value: - -```gql -{ - "data": { - "marketplaceInteractions": [ - { - "marketplace": "NFTX", - "transactionCount": "201" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "148" - }, - { - "marketplace": "CryptoCoven", - "transactionCount": "117" - }, - { - "marketplace": "OpenSeaV1", - "transactionCount": "111" - } - ] - } -} -``` - -## 其他资源 - -For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/zh/subgraphs/cookbook/grafting.mdx b/website/src/pages/zh/subgraphs/cookbook/grafting.mdx deleted file mode 100644 index 321b5b115bec..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/grafting.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: 用嫁接替换合约并保持合约的历史 ---- - -在本指南中,您将学习如何通过嫁接现有的子图来构建和部署新的子图。 - -## 什么是嫁接? - -嫁接重用现有子图中的数据,并开始在稍后的区块中对其进行索引。这在开发过程中非常有用,可以快速克服映射中的简单错误,或者在现有子图失败后暂时使其重新工作。此外,当向子图添加特性时可以使用它,因为从头开始索引需要很长时间。 - -嫁接子图可以使用一个 GraphQL 模式 schema,该模式与基子图之一不同,但仅与基子图兼容。它本身必须是一个有效的子图模式,但是可以通过以下方式偏离基子图的模式: - -- 它添加或删除实体类型 -- 它从实体类型中删除属性 -- 它将可为空的属性添加到实体类型 -- 它将不可为空的属性转换为可空的属性 -- 它将值添加到枚举类型中 -- 它添加或删除接口 -- 它改变了实现接口的实体类型 - -有关详情,请参阅: - -- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) - -In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing subgraph onto the "base" subgraph that tracks the new contract. - -## Important Note on Grafting When Upgrading to the Network - -> **Caution**: It is recommended to not use grafting for subgraphs published to The Graph Network - -### Why Is This Important? - -Grafting is a powerful feature that allows you to "graft" one subgraph onto another, effectively transferring historical data from the existing subgraph to a new version. It is not possible to graft a subgraph from The Graph Network back to Subgraph Studio. - -### Best Practices - -**Initial Migration**: when you first deploy your subgraph to the decentralized network, do so without grafting. Ensure that the subgraph is stable and functioning as expected. - -**Subsequent Updates**: once your subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. - -By adhering to these guidelines, you minimize risks and ensure a smoother migration process. - -## Building an Existing Subgraph - -Building subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing subgraph used in this tutorial, the following repo is provided: - -- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) - -> Note: The contract used in the subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). - -## 子图清单定义 - -The subgraph manifest `subgraph.yaml` identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest that you will use: - -```yaml -specVersion: 0.0.4 -schema: - file: ./schema.graphql -dataSources: - - kind: ethereum - name: Lock - network: sepolia - source: - address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' - abi: Lock - startBlock: 5955690 - mapping: - kind: ethereum/events - apiVersion: 0.0.6 - language: wasm/assemblyscript - entities: - - Withdrawal - abis: - - name: Lock - file: ./abis/Lock.json - eventHandlers: - - event: Withdrawal(uint256,uint256) - handler: handleWithdrawal - file: ./src/lock.ts -``` - -- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract -- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` -- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. - -## 嫁接清单定义 - -嫁接需要在原始子图清单中添加两个新项: - -```yaml ---- -features: - - grafting # feature name -graft: - base: Qm... # subgraph ID of base subgraph - block: 5956000 # block number -``` - -- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). -- `graft:` is a map of the `base` subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base subgraph up to and including the given block and then continue indexing the new subgraph from that block on. - -The `base` and `block` values can be found by deploying two subgraphs: one for the base indexing and one with grafting - -## 部署基子图 - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-example` -2. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-example` folder from the repo -3. 完成后,验证子图是否正确索引。如果在Graph Playground中运行下列指令。 - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -It returns something like this: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - } - ] - } -} -``` - -一旦您验证了子图是正确的索引,您可以快速更新子图与嫁接。 - -## 部署嫁接子图 - -嫁接替代Subgraph.yaml将获得一个新的合约地址。这可能发生在更新dapp、重新部署合约等时。 - -1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a subgraph on Sepolia testnet called `graft-replacement` -2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old subgraph. The `base` subgraph ID is the `Deployment ID` of your original `graph-example` subgraph. You can find this in Subgraph Studio. -3. Follow the directions in the `AUTH & DEPLOY` section on your subgraph page in the `graft-replacement` folder from the repo -4. 完成后,验证子图是否正确索引。如果在Graph Playground中运行下列指令。 - -```graphql -{ - withdrawals(first: 5) { - id - amount - when - } -} -``` - -它返回的结果是这样的: - -``` -{ - "data": { - "withdrawals": [ - { - "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", - "amount": "0", - "when": "1716394824" - }, - { - "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", - "amount": "0", - "when": "1716394848" - }, - { - "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", - "amount": "0", - "when": "1716429732" - } - ] - } -} -``` - -You can see that the `graft-replacement` subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` subgraph. - -Congrats! You have successfully grafted a subgraph onto another subgraph. - -## 其他资源 - -If you want more experience with grafting, here are a few examples for popular contracts: - -- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) -- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) -- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), - -To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results - -> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/zh/subgraphs/cookbook/near.mdx b/website/src/pages/zh/subgraphs/cookbook/near.mdx deleted file mode 100644 index 6bac46becff8..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/near.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: 在 NEAR 上构建子图 ---- - -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). - -## What is NEAR? - -[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. - -## What are NEAR subgraphs? - -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. - -Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR subgraphs: - -- Block handlers: these are run on every new block -- Receipt handlers: run every time a message is executed at a specified account - -[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): - -> Receipt 是系统中唯一可操作的对象。 当我们在 NEAR 平台上谈论“处理交易”时,这最终意味着在某个时候“应用收据”。 - -## 构建 NEAR 子图 - -`@graphprotocol/graph-cli` is a command-line tool for building and deploying subgraphs. - -`@graphprotocol/graph-ts` is a library of subgraph-specific types. - -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. - -> 构建 NEAR 子图与构建索引以太坊的子图非常相似。 - -子图定义包括三个方面: - -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. - -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). - -**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. - -在子图开发过程中,有两个关键命令: - -```bash -$ graph codegen # 从清单中标识的模式文件生成类型 -$ graph build # 从 AssemblyScript 文件生成 Web Assembly,并在 /build 文件夹中准备所有子图文件 -``` - -### 子图清单定义 - -The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph: - -```yaml -specVersion: 0.0.2 -schema: - file: ./src/schema.graphql # link to the schema file -dataSources: - - kind: near - network: near-mainnet - source: - account: app.good-morning.near # This data source will monitor this account - startBlock: 10662188 # Required for NEAR - mapping: - apiVersion: 0.0.5 - language: wasm/assemblyscript - blockHandlers: - - handler: handleNewBlock # the function name in the mapping file - receiptHandlers: - - handler: handleReceipt # the function name in the mapping file - file: ./src/mapping.ts # link to the file with the Assemblyscript mappings -``` - -- NEAR subgraphs introduce a new `kind` of data source (`near`) -- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` -- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. -- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. - -```yaml -accounts: - prefixes: - - app - - good - suffixes: - - morning.near - - morning.testnet -``` - -NEAR data sources support two types of handlers: - -- `blockHandlers`: run on every new NEAR block. No `source.account` is required. -- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). - -### 模式定义 - -Schema definition describes the structure of the resulting subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). - -### AssemblyScript 映射 - -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). - -NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). - -```typescript - -class ExecutionOutcome { - gasBurnt: u64, - blockHash: Bytes, - id: Bytes, - logs: Array, - receiptIds: Array, - tokensBurnt: BigInt, - executorId: string, - } - -class ActionReceipt { - predecessorId: string, - receiverId: string, - id: CryptoHash, - signerId: string, - gasPrice: BigInt, - outputDataReceivers: Array, - inputDataIds: Array, - actions: Array, - } - -class BlockHeader { - height: u64, - prevHeight: u64,// Always zero when version < V3 - epochId: Bytes, - nextEpochId: Bytes, - chunksIncluded: u64, - hash: Bytes, - prevHash: Bytes, - timestampNanosec: u64, - randomValue: Bytes, - gasPrice: BigInt, - totalSupply: BigInt, - latestProtocolVersion: u32, - } - -class ChunkHeader { - gasUsed: u64, - gasLimit: u64, - shardId: u64, - chunkHash: Bytes, - prevBlockHash: Bytes, - balanceBurnt: BigInt, - } - -class Block { - author: string, - header: BlockHeader, - chunks: Array, - } - -class ReceiptWithOutcome { - outcome: ExecutionOutcome, - receipt: ActionReceipt, - block: Block, - } -``` - -These types are passed to block & receipt handlers: - -- Block handlers will receive a `Block` -- Receipt handlers will receive a `ReceiptWithOutcome` - -Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR subgraph developers during mapping execution. - -This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. - -## 部署 NEAR 子图 - -Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). - -Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: - -- `near-mainnet` -- `near-testnet` - -More information on creating and deploying subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). - -As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a subgraph". - -Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: - -```sh -$ graph create --node # creates a subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) -$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash -``` - -节点配置将取决于子图的部署位置。 - -### 子图工作室 - -```sh -graph auth -graph deploy -``` - -### 本地Graph节点(基于默认配置) - -```sh -graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 -``` - -部署子图后,它将由 Graph节点索引。 您可以通过查询子图本身来检查其进度: - -```graphql -{ - _meta { - block { - number - } - } -} -``` - -### 使用本地Graph节点索引 NEAR - -运行索引 NEAR 的 Graph节点有以下操作要求: - -- 带有 Firehose 工具的 NEAR 索引人框架 -- NEAR Firehose 组件 -- 配置了 Firehose 端点的Graph节点 - -我们将很快提供有关运行上述组件的更多信息。 - -## 查询 NEAR 子图 - -The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. - -## 示例子图 - -Here are some example subgraphs for reference: - -[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) - -[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) - -## FAQ - -### 测试版是如何工作的? - -NEAR 支持处于测试阶段,这意味着随着我们继续致力于改进集成,API 可能会发生变化。 请发送电子邮件至 near@thegraph.com,以便我们支持您构建 NEAR 子图,并让您了解最新进展! - -### 子图可以同时索引 NEAR 和 EVM 链吗? - -不,子图只能支持来自一个链/网络的数据源。 - -### 子图可以对更具体的触发器做出反应吗? - -目前,仅支持 Block 和 Receipt 触发器。 我们正在调查对指定帐户的函数调用的触发器。 一旦 NEAR 拥有原生事件支持,我们也对支持事件触发器感兴趣。 - -### 接受处理程序会触发账户及其子账户吗? - -If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: - -```yaml -accounts: - suffixes: - - mintbase1.near -``` - -### NEAR 子图可以在映射期间对 NEAR 帐户进行视图调用吗? - -这是不支持的。 我们正在评估索引是否需要此功能。 - -### 我可以在 NEAR 子图中使用数据源模板吗? - -目前不支持此功能。 我们正在评估索引是否需要此功能。 - -### 以太坊子图支持“待定”和“当前”版本,如何部署 NEAR 子图的“待定”版本? - -NEAR 子图尚不支持挂起的功能。 在此期间,您可以将新版本部署到不同的“命名”子图,然后当它与链头同步时,您可以重新部署到您的主“命名”子图,它将使用相同的底层部署 ID,所以 主子图将立即同步。 - -### 我的问题尚未得到解答,在哪里可以获得更多构建 NEAR 子图的帮助? - -If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. - -## References - -- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/zh/subgraphs/cookbook/polymarket.mdx b/website/src/pages/zh/subgraphs/cookbook/polymarket.mdx deleted file mode 100644 index 2edab84a377b..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/polymarket.mdx +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph -sidebarTitle: Query Polymarket Data ---- - -Query Polymarket’s onchain data using GraphQL via subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. - -## Polymarket Subgraph on Graph Explorer - -You can see an interactive query playground on the [Polymarket subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. - -![Polymarket Playground](/img/Polymarket-playground.png) - -## How to use the Visual Query Editor - -The visual query editor helps you test sample queries from your subgraph. - -You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. - -### Example Query: Get the top 5 highest payouts from Polymarket - -``` -{ - redemptions(orderBy: payout, orderDirection: desc, first: 5) { - payout - redeemer - id - timestamp - } -} -``` - -### Example output - -``` -{ - "data": { - "redemptions": [ - { - "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", - "payout": "6274509531681", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929672" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", - "payout": "2246253575996", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", - "payout": "2135448291991", - "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", - "timestamp": "1704932625" - }, - { - "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", - "payout": "1917395333835", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1726701528" - }, - { - "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", - "payout": "1862505580000", - "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", - "timestamp": "1722929866" - } - ] - } -} -``` - -## Polymarket's GraphQL Schema - -The schema for this subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). - -### Polymarket Subgraph Endpoint - -https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp - -The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). - -![Polymarket Endpoint](/img/Polymarket-endpoint.png) - -## How to Get your own API Key - -1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet -2. Go to https://thegraph.com/studio/apikeys/ to create an API key - -You can use this API key on any subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. - -100k queries per month are free which is perfect for your side project! - -## Additional Polymarket Subgraphs - -- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) -- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) -- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) -- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) - -## How to Query with the API - -You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. - -This following code example will return the exact same output as above. - -### Sample Code from node.js - -``` -const axios = require('axios'); - -const graphqlQuery = `{ - positions(first: 5) { - condition - outcomeIndex - } -}; - -const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' - -const graphQLRequest = { - method: 'post', - url: queryUrl, - data: { - query: graphqlQuery, - }, -}; - -// Send the GraphQL query -axios(graphQLRequest) - .then((response) => { - // Handle the response here - const data = response.data.data - console.log(data) - - }) - .catch((error) => { - // Handle any errors - console.error(error); - }); -``` - -### Additional resources - -For more information about querying data from your subgraph, read more [here](/subgraphs/querying/introduction/). - -To explore all the ways you can optimize & customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/zh/subgraphs/cookbook/secure-api-keys-nextjs.mdx b/website/src/pages/zh/subgraphs/cookbook/secure-api-keys-nextjs.mdx deleted file mode 100644 index ae2201109356..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/secure-api-keys-nextjs.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: How to Secure API Keys Using Next.js Server Components ---- - -## 概述 - -We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). - -In this cookbook, we will go over how to create a Next.js server component that queries a subgraph while also hiding the API key from the frontend. - -### Caveats - -- Next.js server components do not protect API keys from being drained using denial of service attacks. -- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. -- Next.js server components introduce centralization risks as the server can go down. - -### Why It's Needed - -In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. - -### Using client-side rendering to query a subgraph - -![Client-side rendering](/img/api-key-client-side-rendering.png) - -### Prerequisites - -- An API key from [Subgraph Studio](https://thegraph.com/studio) -- Basic knowledge of Next.js and React. -- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). - -## Step-by-Step Cookbook - -### Step 1: Set Up Environment Variables - -1. In our Next.js project root, create a `.env.local` file. -2. Add our API key: `API_KEY=`. - -### Step 2: Create a Server Component - -1. In our `components` directory, create a new file, `ServerComponent.js`. -2. Use the provided example code to set up the server component. - -### Step 3: Implement Server-Side API Request - -In `ServerComponent.js`, add the following code: - -```javascript -const API_KEY = process.env.API_KEY - -export default async function ServerComponent() { - const response = await fetch( - `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: /* GraphQL */ ` - { - factories(first: 5) { - id - poolCount - txCount - totalVolumeUSD - } - } - `, - }), - }, - ) - - const responseData = await response.json() - const data = responseData.data - - return ( -
-

Server Component

- {data ? ( -
    - {data.factories.map((factory) => ( -
  • -

    ID: {factory.id}

    -

    Pool Count: {factory.poolCount}

    -

    Transaction Count: {factory.txCount}

    -

    Total Volume USD: {factory.totalVolumeUSD}

    -
  • - ))} -
- ) : ( -

Loading data...

- )} -
- ) -} -``` - -### Step 4: Use the Server Component - -1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. -2. Render the component: - -```javascript -import ServerComponent from './components/ServerComponent' - -export default function Home() { - return ( -
- -
- ) -} -``` - -### Step 5: Run and Test Our Dapp - -Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. - -![Server-side rendering](/img/api-key-server-side-rendering.png) - -### Conclusion - -By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/zh/subgraphs/cookbook/subgraph-debug-forking.mdx b/website/src/pages/zh/subgraphs/cookbook/subgraph-debug-forking.mdx deleted file mode 100644 index 7eef54e247ea..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/subgraph-debug-forking.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: 使用分叉快速轻松地调试子图 ---- - -As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging! - -## 好的,那是什么? - -**Subgraph forking** is the process of lazily fetching entities from _another_ subgraph's store (usually a remote one). - -In the context of debugging, **subgraph forking** allows you to debug your failed subgraph at block _X_ without needing to wait to sync-up to block _X_. - -## 什么?! 如何处理? - -When you deploy a subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. - -In a nutshell, we are going to _fork the failing subgraph_ from a remote Graph Node that is guaranteed to have the subgraph indexed up to block _X_ in order to provide the locally deployed subgraph being debugged at block _X_ an up-to-date view of the indexing state. - -## 请给我看一些代码! - -To stay focused on subgraph debugging, let's keep things simple and run along with the [example-subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. - -Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: - -```tsx -export function handleNewGravatar(event: NewGravatar): void { - let gravatar = new Gravatar(event.params.id.toHex().toString()) - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} - -export function handleUpdatedGravatar(event: UpdatedGravatar): void { - let gravatar = Gravatar.load(event.params.id.toI32().toString()) - if (gravatar == null) { - log.critical('Gravatar not found!', []) - return - } - gravatar.owner = event.params.owner - gravatar.displayName = event.params.displayName - gravatar.imageUrl = event.params.imageUrl - gravatar.save() -} -``` - -Oops, how unfortunate, when I deploy my perfect looking subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. - -The usual way to attempt a fix is: - -1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). -2. Re-deploy the subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). -3. Wait for it to sync-up. -4. If it breaks again go back to 1, otherwise: Hooray! - -It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ - -Using **subgraph forking** we can essentially eliminate this step. Here is how it looks: - -0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. -1. 按照你认为可以解决问题的方法,在映射源中进行更改。 -2. Deploy to the local Graph Node, **_forking the failing subgraph_** and **_starting from the problematic block_**. -3. 如果它再次中断,则返回 第1步,否则:搞定! - -现在,你可能有 2 个问题: - -1. 子分叉集是什么??? -2. 分叉什么?! - -回答如下: - -1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the subgraph's store. -2. 分叉容易,不要紧张: - -```bash -$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -Also, don't forget to set the `dataSources.source.startBlock` field in the subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! - -所以,我是这么做的: - -1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). - -``` -$ cargo run -p graph-node --release -- \ - --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ - --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ - --ipfs 127.0.0.1:5001 - --fork-base https://api.thegraph.com/subgraphs/id/ -``` - -2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. -3. After I made the changes I deploy my subgraph to the local Graph Node, **_forking the failing subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: - -```bash -$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 -``` - -4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. -5. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/zh/subgraphs/cookbook/subgraph-uncrashable.mdx b/website/src/pages/zh/subgraphs/cookbook/subgraph-uncrashable.mdx deleted file mode 100644 index 959ec7b532cc..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/subgraph-uncrashable.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: 安全子图代码生成器 ---- - -[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your subgraph are completely safe and consistent. - -## 为什么要整合子图使其不崩溃? - -- **Continuous Uptime**. Mishandled entities may cause subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your subgraphs “uncrashable” and ensure business continuity. - -- **Completely Safe**. Common problems seen in subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. - -- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -**Key Features** - -- The code generation tool accommodates **all** subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. - -- 该框架还包括一种方法(通过配置文件) 为实体变量组创建自定义但安全的 setter 函数。这样,用户就不可能加载/使用过时的图形实体,也不可能忘记保存或设置函数所需的变量。 - -- Warning logs are recorded as logs indicating where there is a breach of subgraph logic to help patch the issue to ensure data accuracy. - -使用 Graph CLI codegen 命令,Subgraph Uncrashable 可以作为一个可选标志运行。 - -```sh -graph codegen -u [options] [] -``` - -Visit the [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer subgraphs. diff --git a/website/src/pages/zh/subgraphs/cookbook/transfer-to-the-graph.mdx b/website/src/pages/zh/subgraphs/cookbook/transfer-to-the-graph.mdx deleted file mode 100644 index 497dc254ddf1..000000000000 --- a/website/src/pages/zh/subgraphs/cookbook/transfer-to-the-graph.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Tranfer to The Graph ---- - -Quickly upgrade your subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). - -## Benefits of Switching to The Graph - -- Use the same subgraph that your apps already use with zero-downtime migration. -- Increase reliability from a global network supported by 100+ Indexers. -- Receive lightning-fast support for subgraphs 24/7, with an on-call engineering team. - -## Upgrade Your Subgraph to The Graph in 3 Easy Steps - -1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) -2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) -3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) - -## 1. Set Up Your Studio Environment - -### Create a Subgraph in Subgraph Studio - -- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. -- Click "Create a Subgraph". It is recommended to name the subgraph in Title Case: "Subgraph Name Chain Name". - -> Note: After publishing, the subgraph name will be editable but requires onchain action each time, so name it properly. - -### Install the Graph CLI⁠ - -You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. - -On your local machine, run the following command: - -Using [npm](https://www.npmjs.com/): - -```sh -npm install -g @graphprotocol/graph-cli@latest -``` - -Use the following command to create a subgraph in Studio using the CLI: - -```sh -graph init --product subgraph-studio -``` - -### Authenticate Your Subgraph - -In The Graph CLI, use the auth command seen in Subgraph Studio: - -```sh -graph auth -``` - -## 2. Deploy Your Subgraph to Studio - -If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your subgraph. - -In The Graph CLI, run the following command: - -```sh -graph deploy --ipfs-hash - -``` - -> **Note:** Every subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). - -## 3. Publish Your Subgraph to The Graph Network - -![publish button](/img/publish-sub-transfer.png) - -### Query Your Subgraph - -> To attract about 3 indexers to query your subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. - -You can start [querying](/subgraphs/querying/introduction/) any subgraph by sending a GraphQL query into the subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. - -#### 示例 - -[CryptoPunks Ethereum subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: - -![Query URL](/img/cryptopunks-screenshot-transfer.png) - -The query URL for this subgraph is: - -```sh -https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK -``` - -Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. - -### Getting your own API Key - -You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: - -![API keys](/img/Api-keys-screenshot.png) - -### Monitor Subgraph Status - -Once you upgrade, you can access and manage your subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all subgraphs in [The Graph Explorer](https://thegraph.com/networks/). - -### 其他资源 - -- To quickly create and publish a new subgraph, check out the [Quick Start](/subgraphs/quick-start/). -- To explore all the ways you can optimize and customize your subgraph for a better performance, read more about [creating a subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/zh/subgraphs/guides/_meta.js b/website/src/pages/zh/subgraphs/guides/_meta.js new file mode 100644 index 000000000000..e642f12ef11d --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/_meta.js @@ -0,0 +1,11 @@ +export default { + 'subgraph-debug-forking': '', + near: '', + arweave: '', + grafting: '', + 'subgraph-uncrashable': '', + 'transfer-to-the-graph': '', + enums: '', + 'secure-api-keys-nextjs': '', + polymarket: '', +} diff --git a/website/src/pages/zh/subgraphs/guides/arweave.mdx b/website/src/pages/zh/subgraphs/guides/arweave.mdx new file mode 100644 index 000000000000..08e6c4257268 --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/arweave.mdx @@ -0,0 +1,239 @@ +--- +title: Building Subgraphs on Arweave +--- + +> Arweave support in Graph Node and on Subgraph Studio is in beta: please reach us on [Discord](https://discord.gg/graphprotocol) with any questions about building Arweave Subgraphs! + +In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. + +## What is Arweave? + +The Arweave protocol allows developers to store data permanently and that is the main difference between Arweave and IPFS, where IPFS lacks the feature; permanence, and files stored on Arweave can't be changed or deleted. + +Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: + +- [Arwiki](https://arwiki.wiki/#/en/main) +- [Arweave Resources](https://www.arweave.org/build) + +## What are Arweave Subgraphs? + +The Graph allows you to build custom open APIs called "Subgraphs". Subgraphs are used to tell indexers (server operators) which data to index on a blockchain and save on their servers in order for you to be able to query it at any time using [GraphQL](https://graphql.org/). + +[Graph Node](https://github.com/graphprotocol/graph-node) is now able to index data on Arweave protocol. The current integration is only indexing Arweave as a blockchain (blocks and transactions), it is not indexing the stored files yet. + +## Building an Arweave Subgraph + +To be able to build and deploy Arweave Subgraphs, you need two packages: + +1. `@graphprotocol/graph-cli` above version 0.30.2 - This is a command-line tool for building and deploying Subgraphs. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-cli) to download using `npm`. +2. `@graphprotocol/graph-ts` above version 0.27.0 - This is library of Subgraph-specific types. [Click here](https://www.npmjs.com/package/@graphprotocol/graph-ts) to download using `npm`. + +## Subgraph's components + +There are three components of a Subgraph: + +### 1. Manifest - `subgraph.yaml` + +Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. + +### 2. Schema - `schema.graphql` + +Here you define which data you want to be able to query after indexing your Subgraph using GraphQL. This is actually similar to a model for an API, where the model defines the structure of a request body. + +The requirements for Arweave Subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +### 3. AssemblyScript Mappings - `mapping.ts` + +This is the logic that determines how data should be retrieved and stored when someone interacts with the data sources you are listening to. The data gets translated and is stored based off the schema you have listed. + +During Subgraph development there are two key commands: + +``` +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for an Arweave Subgraph: + +```yaml +specVersion: 1.3.0 +description: Arweave Blocks Indexing +schema: + file: ./schema.graphql # link to the schema file +dataSources: + - kind: arweave + name: arweave-blocks + network: arweave-mainnet # The Graph only supports Arweave Mainnet + source: + owner: 'ID-OF-AN-OWNER' # The public key of an Arweave wallet + startBlock: 0 # set this to 0 to start indexing from chain genesis + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + file: ./src/blocks.ts # link to the file with the Assemblyscript mappings + entities: + - Block + - Transaction + blockHandlers: + - handler: handleBlock # the function name in the mapping file + transactionHandlers: + - handler: handleTx # the function name in the mapping file +``` + +- Arweave Subgraphs introduce a new kind of data source (`arweave`) +- The network should correspond to a network on the hosting Graph Node. In Subgraph Studio, Arweave's mainnet is `arweave-mainnet` +- Arweave data sources introduce an optional source.owner field, which is the public key of an Arweave wallet + +Arweave data sources support two types of handlers: + +- `blockHandlers` - Run on every new Arweave block. No source.owner is required. +- `transactionHandlers` - Run on every transaction where the data source's `source.owner` is the owner. Currently an owner is required for `transactionHandlers`, if users want to process all transactions they should provide "" as the `source.owner` + +> The source.owner can be the owner's address, or their Public Key. + +> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. + +> Note: [Irys (previously Bundlr)](https://irys.xyz/) transactions are not supported yet. + +## Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on the Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +## AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```tsx +class Block { + timestamp: u64 + lastRetarget: u64 + height: u64 + indepHash: Bytes + nonce: Bytes + previousBlock: Bytes + diff: Bytes + hash: Bytes + txRoot: Bytes + txs: Bytes[] + walletList: Bytes + rewardAddr: Bytes + tags: Tag[] + rewardPool: Bytes + weaveSize: Bytes + blockSize: Bytes + cumulativeDiff: Bytes + hashListMerkle: Bytes + poa: ProofOfAccess +} + +class Transaction { + format: u32 + id: Bytes + lastTx: Bytes + owner: Bytes + tags: Tag[] + target: Bytes + quantity: Bytes + data: Bytes + dataSize: Bytes + dataRoot: Bytes + signature: Bytes + reward: Bytes +} +``` + +Block handlers receive a `Block`, while transactions receive a `Transaction`. + +Writing the mappings of an Arweave Subgraph is very similar to writing the mappings of an Ethereum Subgraph. For more information, click [here](/developing/creating-a-subgraph/#writing-mappings). + +## Deploying an Arweave Subgraph in Subgraph Studio + +Once your Subgraph has been created on your Subgraph Studio dashboard, you can deploy by using the `graph deploy` CLI command. + +```bash +graph deploy --access-token +``` + +## Querying an Arweave Subgraph + +The GraphQL endpoint for Arweave Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here is an example Subgraph for reference: + +- [Example Subgraph for Arweave](https://github.com/graphprotocol/graph-tooling/tree/main/examples/arweave-blocks-transactions) + +## FAQ + +### Can a Subgraph index Arweave and other chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can I index the stored files on Arweave? + +Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). + +### Can I identify Bundlr bundles in my Subgraph? + +This is not currently supported. + +### How can I filter transactions to a specific account? + +The source.owner can be the user's public key or account address. + +### What is the current encryption format? + +Data is generally passed into the mappings as Bytes, which if stored directly is returned in the Subgraph in a `hex` format (ex. block and transaction hashes). You may want to convert to a `base64` or `base64 URL`-safe format in your mappings, in order to match what is displayed in block explorers like [Arweave Explorer](https://viewblock.io/arweave/). + +The following `bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string` helper function can be used, and will be added to `graph-ts`: + +``` +const base64Alphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/" +]; + +const base64UrlAlphabet = [ + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_" +]; + +function bytesToBase64(bytes: Uint8Array, urlSafe: boolean): string { + let alphabet = urlSafe? base64UrlAlphabet : base64Alphabet; + + let result = '', i: i32, l = bytes.length; + for (i = 2; i < l; i += 3) { + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)]; + result += alphabet[bytes[i] & 0x3F]; + } + if (i === l + 1) { // 1 octet yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[(bytes[i - 2] & 0x03) << 4]; + if (!urlSafe) { + result += "=="; + } + } + if (!urlSafe && i === l) { // 2 octets yet to write + result += alphabet[bytes[i - 2] >> 2]; + result += alphabet[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += alphabet[(bytes[i - 1] & 0x0F) << 2]; + if (!urlSafe) { + result += "="; + } + } + return result; +} +``` diff --git a/website/src/pages/zh/subgraphs/guides/enums.mdx b/website/src/pages/zh/subgraphs/guides/enums.mdx new file mode 100644 index 000000000000..9f55ae07c54b --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/enums.mdx @@ -0,0 +1,274 @@ +--- +title: Categorize NFT Marketplaces Using Enums +--- + +Use Enums to make your code cleaner and less error-prone. Here's a full example of using Enums on NFT marketplaces. + +## What are Enums? + +Enums, or enumeration types, are a specific data type that allows you to define a set of specific, allowed values. + +### Example of Enums in Your Schema + +If you're building a Subgraph to track the ownership history of tokens on a marketplace, each token might go through different ownerships, such as `OriginalOwner`, `SecondOwner`, and `ThirdOwner`. By using enums, you can define these specific ownerships, ensuring only predefined values are assigned. + +You can define enums in your schema, and once defined, you can use the string representation of the enum values to set an enum field on an entity. + +Here's what an enum definition might look like in your schema, based on the example above: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +This means that when you use the `TokenStatus` type in your schema, you expect it to be exactly one of predefined values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`, ensuring consistency and validity. + +To learn more about enums, check out [Creating a Subgraph](/developing/creating-a-subgraph/#enums) and [GraphQL documentation](https://graphql.org/learn/schema/#enumeration-types). + +## Benefits of Using Enums + +- **Clarity:** Enums provide meaningful names for values, making data easier to understand. +- **Validation:** Enums enforce strict value definitions, preventing invalid data entries. +- **Maintainability:** When you need to change or add new categories, enums allow you to do this in a focused manner. + +### Without Enums + +If you choose to define the type as a string instead of using an Enum, your code might look like this: + +```graphql +type Token @entity { + id: ID! + tokenId: BigInt! + owner: Bytes! # Owner of the token + tokenStatus: String! # String field to track token status + timestamp: BigInt! +} +``` + +In this schema, `TokenStatus` is a simple string with no specific, allowed values. + +#### Why is this a problem? + +- There's no restriction of `TokenStatus` values, so any string can be accidentally assigned. This makes it hard to ensure that only valid statuses like `OriginalOwner`, `SecondOwner`, or `ThirdOwner` are set. +- It's easy to make typos such as `Orgnalowner` instead of `OriginalOwner`, making the data and potential queries unreliable. + +### With Enums + +Instead of assigning free-form strings, you can define an enum for `TokenStatus` with specific values: `OriginalOwner`, `SecondOwner`, or `ThirdOwner`. Using an enum ensures only allowed values are used. + +Enums provide type safety, minimize typo risks, and ensure consistent and reliable results. + +## Defining Enums for NFT Marketplaces + +> Note: The following guide uses the CryptoCoven NFT smart contract. + +To define enums for the various marketplaces where NFTs are traded, use the following in your Subgraph schema: + +```gql +# Enum for Marketplaces that the CryptoCoven contract interacted with(likely a Trade/Mint) +enum Marketplace { + OpenSeaV1 # Represents when a CryptoCoven NFT is traded on the marketplace + OpenSeaV2 # Represents when a CryptoCoven NFT is traded on the OpenSeaV2 marketplace + SeaPort # Represents when a CryptoCoven NFT is traded on the SeaPort marketplace + LooksRare # Represents when a CryptoCoven NFT is traded on the LookRare marketplace + # ...and other marketplaces +} +``` + +## Using Enums for NFT Marketplaces + +Once defined, enums can be used throughout your Subgraph to categorize transactions or events. + +For example, when logging NFT sales, you can specify the marketplace involved in the trade using the enum. + +### Implementing a Function for NFT Marketplaces + +Here's how you can implement a function to retrieve the marketplace name from the enum as a string: + +```ts +export function getMarketplaceName(marketplace: Marketplace): string { + // Using if-else statements to map the enum value to a string + if (marketplace === Marketplace.OpenSeaV1) { + return 'OpenSeaV1' // If the marketplace is OpenSea, return its string representation + } else if (marketplace === Marketplace.OpenSeaV2) { + return 'OpenSeaV2' + } else if (marketplace === Marketplace.SeaPort) { + return 'SeaPort' // If the marketplace is SeaPort, return its string representation + } else if (marketplace === Marketplace.LooksRare) { + return 'LooksRare' // If the marketplace is LooksRare, return its string representation + // ... and other market places + } +} +``` + +## Best Practices for Using Enums + +- **Consistent Naming:** Use clear, descriptive names for enum values to improve readability. +- **Centralized Management:** Keep enums in a single file for consistency. This makes enums easier to update and ensures they are the single source of truth. +- **Documentation:** Add comments to enum to clarify their purpose and usage. + +## Using Enums in Queries + +Enums in queries help you improve data quality and make your results easier to interpret. They function as filters and response elements, ensuring consistency and reducing errors in marketplace values. + +**Specifics** + +- **Filtering with Enums:** Enums provide clear filters, allowing you to confidently include or exclude specific marketplaces. +- **Enums in Responses:** Enums guarantee that only recognized marketplace names are returned, making the results standardized and accurate. + +### Sample Queries + +#### Query 1: Account With The Highest NFT Marketplace Interactions + +This query does the following: + +- It finds the account with the highest unique NFT marketplace interactions, which is great for analyzing cross-marketplace activity. +- The marketplaces field uses the marketplace enum, ensuring consistent and validated marketplace values in the response. + +```gql +{ + accounts(first: 1, orderBy: uniqueMarketplacesCount, orderDirection: desc) { + id + sendCount + receiveCount + totalSpent + uniqueMarketplacesCount + marketplaces { + marketplace # This field returns the enum value representing the marketplace + } + } +} +``` + +#### Returns + +This response provides account details and a list of unique marketplace interactions with enum values for standardized clarity: + +```gql +{ + "data": { + "accounts": [ + { + "id": "0xb3abc96cb9a61576c03c955d75b703a890a14aa0", + "sendCount": "44", + "receiveCount": "44", + "totalSpent": "1197500000000000000", + "uniqueMarketplacesCount": "7", + "marketplaces": [ + { + "marketplace": "OpenSeaV1" + }, + { + "marketplace": "OpenSeaV2" + }, + { + "marketplace": "GenieSwap" + }, + { + "marketplace": "CryptoCoven" + }, + { + "marketplace": "Unknown" + }, + { + "marketplace": "LooksRare" + }, + { + "marketplace": "NFTX" + } + ] + } + ] + } +} +``` + +#### Query 2: Most Active Marketplace for CryptoCoven transactions + +This query does the following: + +- It identifies the marketplace with the highest volume of CryptoCoven transactions. +- It uses the marketplace enum to ensure that only valid marketplace types appear in the response, adding reliability and consistency to your data. + +```gql +{ + marketplaceInteractions(first: 1, orderBy: transactionCount, orderDirection: desc) { + marketplace + transactionCount + } +} +``` + +#### Result 2 + +The expected response includes the marketplace and the corresponding transaction count, using the enum to indicate the marketplace type: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "Unknown", + "transactionCount": "222" + } + ] + } +} +``` + +#### Query 3: Marketplace Interactions with High Transaction Counts + +This query does the following: + +- It retrieves the top four marketplaces with over 100 transactions, excluding "Unknown" marketplaces. +- It uses enums as filters to ensure that only valid marketplace types are included, increasing accuracy. + +```gql +{ + marketplaceInteractions( + first: 4 + orderBy: transactionCount + orderDirection: desc + where: { transactionCount_gt: "100", marketplace_not: "Unknown" } + ) { + marketplace + transactionCount + } +} +``` + +#### Result 3 + +Expected output includes the marketplaces that meet the criteria, each represented by an enum value: + +```gql +{ + "data": { + "marketplaceInteractions": [ + { + "marketplace": "NFTX", + "transactionCount": "201" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "148" + }, + { + "marketplace": "CryptoCoven", + "transactionCount": "117" + }, + { + "marketplace": "OpenSeaV1", + "transactionCount": "111" + } + ] + } +} +``` + +## Additional Resources + +For additional information, check out this guide's [repo](https://github.com/chidubemokeke/Subgraph-Tutorial-Enums). diff --git a/website/src/pages/zh/subgraphs/guides/grafting.mdx b/website/src/pages/zh/subgraphs/guides/grafting.mdx new file mode 100644 index 000000000000..d9abe0e70d2a --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/grafting.mdx @@ -0,0 +1,202 @@ +--- +title: Replace a Contract and Keep its History With Grafting +--- + +In this guide, you will learn how to build and deploy new Subgraphs by grafting existing Subgraphs. + +## What is Grafting? + +Grafting reuses the data from an existing Subgraph and starts indexing it at a later block. This is useful during development to get past simple errors in the mappings quickly or to temporarily get an existing Subgraph working again after it has failed. Also, it can be used when adding a feature to a Subgraph that takes long to index from scratch. + +The grafted Subgraph can use a GraphQL schema that is not identical to the one of the base Subgraph, but merely compatible with it. It has to be a valid Subgraph schema in its own right, but may deviate from the base Subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +For more information, you can check: + +- [Grafting](/developing/creating-a-subgraph/#grafting-onto-existing-subgraphs) + +In this tutorial, we will be covering a basic use case. We will replace an existing contract with an identical contract (with a new address, but the same code). Then, graft the existing Subgraph onto the "base" Subgraph that tracks the new contract. + +## Important Note on Grafting When Upgrading to the Network + +> **Caution**: It is recommended to not use grafting for Subgraphs published to The Graph Network + +### Why Is This Important? + +Grafting is a powerful feature that allows you to "graft" one Subgraph onto another, effectively transferring historical data from the existing Subgraph to a new version. It is not possible to graft a Subgraph from The Graph Network back to Subgraph Studio. + +### Best Practices + +**Initial Migration**: when you first deploy your Subgraph to the decentralized network, do so without grafting. Ensure that the Subgraph is stable and functioning as expected. + +**Subsequent Updates**: once your Subgraph is live and stable on the decentralized network, you may use grafting for future versions to make the transition smoother and to preserve historical data. + +By adhering to these guidelines, you minimize risks and ensure a smoother migration process. + +## Building an Existing Subgraph + +Building Subgraphs is an essential part of The Graph, described more in depth [here](/subgraphs/quick-start/). To be able to build and deploy the existing Subgraph used in this tutorial, the following repo is provided: + +- [Subgraph example repo](https://github.com/Shiyasmohd/grafting-tutorial) + +> Note: The contract used in the Subgraph was taken from the following [Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit). + +## Subgraph Manifest Definition + +The Subgraph manifest `subgraph.yaml` identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest that you will use: + +```yaml +specVersion: 1.3.0 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: sepolia + source: + address: '0xb3aabe721794b85fe4e72134795c2f93b4eb7e63' + abi: Lock + startBlock: 5955690 + mapping: + kind: ethereum/events + apiVersion: 0.0.9 + language: wasm/assemblyscript + entities: + - Withdrawal + abis: + - name: Lock + file: ./abis/Lock.json + eventHandlers: + - event: Withdrawal(uint256,uint256) + handler: handleWithdrawal + file: ./src/lock.ts +``` + +- The `Lock` data source is the abi and contract address we will get when we compile and deploy the contract +- The network should correspond to an indexed network being queried. Since we're running on Sepolia testnet, the network is `sepolia` +- The `mapping` section defines the triggers of interest and the functions that should be run in response to those triggers. In this case, we are listening for the `Withdrawal` event and calling the `handleWithdrawal` function when it is emitted. + +## Grafting Manifest Definition + +Grafting requires adding two new items to the original Subgraph manifest: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # Subgraph ID of base Subgraph + block: 5956000 # block number +``` + +- `features:` is a list of all used [feature names](/developing/creating-a-subgraph/#experimental-features). +- `graft:` is a map of the `base` Subgraph and the block to graft on to. The `block` is the block number to start indexing from. The Graph will copy the data of the base Subgraph up to and including the given block and then continue indexing the new Subgraph from that block on. + +The `base` and `block` values can be found by deploying two Subgraphs: one for the base indexing and one with grafting + +## Deploying the Base Subgraph + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-example` +2. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-example` folder from the repo +3. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It returns something like this: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + } + ] + } +} +``` + +Once you have verified the Subgraph is indexing properly, you can quickly update the Subgraph with grafting. + +## Deploying the Grafting Subgraph + +The graft replacement subgraph.yaml will have a new contract address. This could happen when you update your dapp, redeploy a contract, etc. + +1. Go to [Subgraph Studio](https://thegraph.com/studio/) and create a Subgraph on Sepolia testnet called `graft-replacement` +2. Create a new manifest. The `subgraph.yaml` for `graph-replacement` contains a different contract address and new information about how it should graft. These are the `block` of the [last event emitted](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452) you care about by the old contract and the `base` of the old Subgraph. The `base` Subgraph ID is the `Deployment ID` of your original `graph-example` Subgraph. You can find this in Subgraph Studio. +3. Follow the directions in the `AUTH & DEPLOY` section on your Subgraph page in the `graft-replacement` folder from the repo +4. Once finished, verify the Subgraph is indexing properly. If you run the following command in The Graph Playground + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +It should return the following: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d0a000000", + "amount": "0", + "when": "1716394824" + }, + { + "id": "0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc45203000000", + "amount": "0", + "when": "1716394848" + }, + { + "id": "0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af06000000", + "amount": "0", + "when": "1716429732" + } + ] + } +} +``` + +You can see that the `graft-replacement` Subgraph is indexing from older `graph-example` data and newer data from the new contract address. The original contract emitted two `Withdrawal` events, [Event 1](https://sepolia.etherscan.io/tx/0xe8323d21c4f104607b10b0fff9fc24b9612b9488795dea8196b2d5f980d3dc1d) and [Event 2](https://sepolia.etherscan.io/tx/0xea1cee35036f2cacb72f2a336be3e54ab911f5bebd58f23400ebb8ecc5cfc452). The new contract emitted one `Withdrawal` after, [Event 3](https://sepolia.etherscan.io/tx/0x2410475f76a44754bae66d293d14eac34f98ec03a3689cbbb56a716d20b209af). The two previously indexed transactions (Event 1 and 2) and the new transaction (Event 3) were combined together in the `graft-replacement` Subgraph. + +Congrats! You have successfully grafted a Subgraph onto another Subgraph. + +## Additional Resources + +If you want more experience with grafting, here are a few examples for popular contracts: + +- [Curve](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/config/templates/curve.template.yaml) +- [ERC-721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [Uniswap](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3-forks/protocols/uniswap-v3/config/templates/uniswapV3Template.yaml), + +To become even more of a Graph expert, consider learning about other ways to handle changes in underlying datasources. Alternatives like [Data Source Templates](/developing/creating-a-subgraph/#data-source-templates) can achieve similar results + +> Note: A lot of material from this article was taken from the previously published [Arweave article](/subgraphs/cookbook/arweave/) diff --git a/website/src/pages/zh/subgraphs/guides/near.mdx b/website/src/pages/zh/subgraphs/guides/near.mdx new file mode 100644 index 000000000000..e78a69eb7fa2 --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/near.mdx @@ -0,0 +1,283 @@ +--- +title: Building Subgraphs on NEAR +--- + +This guide is an introduction to building Subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralized applications. Visit the [official documentation](https://docs.near.org/concepts/basics/protocol) for more information. + +## What are NEAR Subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a Subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build Subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process onchain events. There are currently two types of handlers supported for NEAR Subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/build/data-infrastructure/lake-data-structures/receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command-line tool for building and deploying Subgraphs. + +`@graphprotocol/graph-ts` is a library of Subgraph-specific types. + +NEAR Subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR Subgraph is very similar to building a Subgraph that indexes Ethereum. + +There are three aspects of Subgraph definition: + +**subgraph.yaml:** the Subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your Subgraph, and how to query it via GraphQL. The requirements for NEAR Subgraphs are covered by [the existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/subgraphs/developing/creating/graph-ts/api/) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types and new JSON parsing functionality. + +During Subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the Subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The Subgraph manifest (`subgraph.yaml`) identifies the data sources for the Subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example Subgraph manifest for a NEAR Subgraph: + +```yaml +specVersion: 1.3.0 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.9 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR Subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On Subgraph Studio, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human-readable ID corresponding to a [NEAR account](https://docs.near.org/concepts/protocol/account-model). This can be an account or a sub-account. +- NEAR data sources introduce an alternative optional `source.accounts` field, which contains optional suffixes and prefixes. At least prefix or suffix must be specified, they will match the any account starting or ending with the list of values respectively. The example below would match: `[app|good].*[morning.near|morning.testnet]`. If only a list of prefixes or suffixes is necessary the other field can be omitted. + +```yaml +accounts: + prefixes: + - app + - good + suffixes: + - morning.near + - morning.testnet +``` + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/tutorials/crosswords/basics/add-functions-call#create-a-subaccount) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting Subgraph database and the relationships between entities. This is agnostic of the original data source. There are more details on Subgraph schema definition [here](/developing/creating-a-subgraph/#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise, the rest of the [AssemblyScript API](/subgraphs/developing/creating/graph-ts/api/) is available to NEAR Subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/subgraphs/developing/creating/graph-ts/api/#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built Subgraph, it is time to deploy it to Graph Node for indexing. NEAR Subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +Subgraph Studio and the upgrade Indexer on The Graph Network currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying Subgraphs on Subgraph Studio can be found [here](/deploying/deploying-a-subgraph-to-studio/). + +As a quick primer - the first step is to "create" your Subgraph - this only needs to be done once. On Subgraph Studio, this can be done from [your Dashboard](https://thegraph.com/studio/): "Create a Subgraph". + +Once your Subgraph has been created, you can deploy your Subgraph by using the `graph deploy` CLI command: + +```sh +$ graph create --node # creates a Subgraph on a local Graph Node (on Subgraph Studio, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the Subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend on where the Subgraph is being deployed. + +### Subgraph Studio + +```sh +graph auth +graph deploy +``` + +### Local Graph Node (based on default configuration) + +```sh +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your Subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the Subgraph itself: + +```graphql +{ + _meta { + block { + number + } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR Subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/subgraphs/querying/graphql-api/) for more information. + +## Example Subgraphs + +Here are some example Subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-blocks) + +[NEAR Receipts](https://github.com/graphprotocol/graph-tooling/tree/main/examples/near-receipts) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR Subgraphs, and keep you up to date on the latest developments! + +### Can a Subgraph index both NEAR and EVM chains? + +No, a Subgraph can only support data sources from one chain/network. + +### Can Subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub-accounts? + +If an `account` is specified, that will only match the exact account name. It is possible to match sub-accounts by specifying an `accounts` field, with `suffixes` and `prefixes` specified to match accounts and sub-accounts, for example the following would match all `mintbase1.near` sub-accounts: + +```yaml +accounts: + suffixes: + - mintbase1.near +``` + +### Can NEAR Subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR Subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum Subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR Subgraph? + +Pending functionality is not yet supported for NEAR Subgraphs. In the interim, you can deploy a new version to a different "named" Subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" Subgraph, which will use the same underlying deployment ID, so the main Subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR Subgraphs? + +If it is a general question about Subgraph development, there is a lot more information in the rest of the [Developer documentation](/subgraphs/quick-start/). Otherwise please join [The Graph Protocol Discord](https://discord.gg/graphprotocol) and ask in the #near channel or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/tutorials/crosswords/basics/set-up-skeleton) diff --git a/website/src/pages/zh/subgraphs/guides/polymarket.mdx b/website/src/pages/zh/subgraphs/guides/polymarket.mdx new file mode 100644 index 000000000000..74efe387b0d7 --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/polymarket.mdx @@ -0,0 +1,148 @@ +--- +title: Querying Blockchain Data from Polymarket with Subgraphs on The Graph +sidebarTitle: Query Polymarket Data +--- + +Query Polymarket’s onchain data using GraphQL via Subgraphs on The Graph Network. Subgraphs are decentralized APIs powered by The Graph, a protocol for indexing & querying data from blockchains. + +## Polymarket Subgraph on Graph Explorer + +You can see an interactive query playground on the [Polymarket Subgraph’s page on The Graph Explorer](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one), where you can test any query. + +![Polymarket Playground](/img/Polymarket-playground.png) + +## How to use the Visual Query Editor + +The visual query editor helps you test sample queries from your Subgraph. + +You can use the GraphiQL Explorer to compose your GraphQL queries by clicking on the fields you want. + +### Example Query: Get the top 5 highest payouts from Polymarket + +``` +{ + redemptions(orderBy: payout, orderDirection: desc, first: 5) { + payout + redeemer + id + timestamp + } +} +``` + +### Example output + +``` +{ + "data": { + "redemptions": [ + { + "id": "0x8fbb68b7c0cbe9aca6024d063a843a23d046b5522270fd25c6a81c511cf517d1_0x3b", + "payout": "6274509531681", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929672" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0x7", + "payout": "2246253575996", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0x983b71c64b5075fc1179f4e03849af9c727be60de71c9e86e37ad0b3e43f9db9_0x26", + "payout": "2135448291991", + "redeemer": "0x5a181dcf3eb53a09fb32b20a5a9312fb8d26f689", + "timestamp": "1704932625" + }, + { + "id": "0x2b2826448fcacde7931828cfcd3cc4aaeac8080fdff1e91363f0589c9b503eca_0xa", + "payout": "1917395333835", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1726701528" + }, + { + "id": "0xfe82e117201f5169abc822281ccf0469e6b3740fcb4e799d1b599f83b8f11656_0x30", + "payout": "1862505580000", + "redeemer": "0xfffe4013adfe325c6e02d36dc66e091f5476f52c", + "timestamp": "1722929866" + } + ] + } +} +``` + +## Polymarket's GraphQL Schema + +The schema for this Subgraph is defined [here in Polymarket’s GitHub](https://github.com/Polymarket/polymarket-subgraph/blob/main/polymarket-subgraph/schema.graphql). + +### Polymarket Subgraph Endpoint + +https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp + +The Polymarket Subgraph endpoint is available on [Graph Explorer](https://thegraph.com/explorer). + +![Polymarket Endpoint](/img/Polymarket-endpoint.png) + +## How to Get your own API Key + +1. Go to [https://thegraph.com/studio](http://thegraph.com/studio) and connect your wallet +2. Go to https://thegraph.com/studio/apikeys/ to create an API key + +You can use this API key on any Subgraph in [Graph Explorer](https://thegraph.com/explorer), and it’s not limited to just Polymarket. + +100k queries per month are free which is perfect for your side project! + +## Additional Polymarket Subgraphs + +- [Polymarket](https://thegraph.com/explorer/subgraphs/81Dm16JjuFSrqz813HysXoUPvzTwE7fsfPk2RTf66nyC?view=Query&chain=arbitrum-one) +- [Polymarket Activity Polygon](https://thegraph.com/explorer/subgraphs/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp?view=Query&chain=arbitrum-one) +- [Polymarket Profit & Loss](https://thegraph.com/explorer/subgraphs/6c58N5U4MtQE2Y8njfVrrAfRykzfqajMGeTMEvMmskVz?view=Query&chain=arbitrum-one) +- [Polymarket Open Interest](https://thegraph.com/explorer/subgraphs/ELaW6RtkbmYNmMMU6hEPsghG9Ko3EXSmiRkH855M4qfF?view=Query&chain=arbitrum-one) + +## How to Query with the API + +You can pass any GraphQL query to the Polymarket endpoint and receive data in json format. + +This following code example will return the exact same output as above. + +### Sample Code from node.js + +``` +const axios = require('axios'); + +const graphqlQuery = `{ + positions(first: 5) { + condition + outcomeIndex + } +}; + +const queryUrl = 'https://gateway.thegraph.com/api/{api-key}/subgraphs/id/Bx1W4S7kDVxs9gC3s2G6DS8kdNBJNVhMviCtin2DiBp' + +const graphQLRequest = { + method: 'post', + url: queryUrl, + data: { + query: graphqlQuery, + }, +}; + +// Send the GraphQL query +axios(graphQLRequest) + .then((response) => { + // Handle the response here + const data = response.data.data + console.log(data) + + }) + .catch((error) => { + // Handle any errors + console.error(error); + }); +``` + +### Additional resources + +For more information about querying data from your Subgraph, read more [here](/subgraphs/querying/introduction/). + +To explore all the ways you can optimize & customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/). diff --git a/website/src/pages/zh/subgraphs/guides/secure-api-keys-nextjs.mdx b/website/src/pages/zh/subgraphs/guides/secure-api-keys-nextjs.mdx new file mode 100644 index 000000000000..e17e594408ff --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/secure-api-keys-nextjs.mdx @@ -0,0 +1,123 @@ +--- +title: How to Secure API Keys Using Next.js Server Components +--- + +## Overview + +We can use [Next.js server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) to properly secure our API key from exposure in the frontend of our dapp. To further increase our API key security, we can also [restrict our API key to certain Subgraphs or domains in Subgraph Studio](/cookbook/upgrading-a-subgraph/#securing-your-api-key). + +In this cookbook, we will go over how to create a Next.js server component that queries a Subgraph while also hiding the API key from the frontend. + +### Caveats + +- Next.js server components do not protect API keys from being drained using denial of service attacks. +- The Graph Network gateways have denial of service detection and mitigation strategies in place, however using server components may weaken these protections. +- Next.js server components introduce centralization risks as the server can go down. + +### Why It's Needed + +In a standard React application, API keys included in the frontend code can be exposed to the client-side, posing a security risk. While `.env` files are commonly used, they don't fully protect the keys since React's code is executed on the client side, exposing the API key in the headers. Next.js Server Components address this issue by handling sensitive operations server-side. + +### Using client-side rendering to query a Subgraph + +![Client-side rendering](/img/api-key-client-side-rendering.png) + +### Prerequisites + +- An API key from [Subgraph Studio](https://thegraph.com/studio) +- Basic knowledge of Next.js and React. +- An existing Next.js project that uses the [App Router](https://nextjs.org/docs/app). + +## Step-by-Step Cookbook + +### Step 1: Set Up Environment Variables + +1. In our Next.js project root, create a `.env.local` file. +2. Add our API key: `API_KEY=`. + +### Step 2: Create a Server Component + +1. In our `components` directory, create a new file, `ServerComponent.js`. +2. Use the provided example code to set up the server component. + +### Step 3: Implement Server-Side API Request + +In `ServerComponent.js`, add the following code: + +```javascript +const API_KEY = process.env.API_KEY + +export default async function ServerComponent() { + const response = await fetch( + `https://gateway-arbitrum.network.thegraph.com/api/${API_KEY}/subgraphs/id/HUZDsRpEVP2AvzDCyzDHtdc64dyDxx8FQjzsmqSg4H3B`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query: /* GraphQL */ ` + { + factories(first: 5) { + id + poolCount + txCount + totalVolumeUSD + } + } + `, + }), + }, + ) + + const responseData = await response.json() + const data = responseData.data + + return ( +
+

Server Component

+ {data ? ( +
    + {data.factories.map((factory) => ( +
  • +

    ID: {factory.id}

    +

    Pool Count: {factory.poolCount}

    +

    Transaction Count: {factory.txCount}

    +

    Total Volume USD: {factory.totalVolumeUSD}

    +
  • + ))} +
+ ) : ( +

Loading data...

+ )} +
+ ) +} +``` + +### Step 4: Use the Server Component + +1. In our page file (e.g., `pages/index.js`), import `ServerComponent`. +2. Render the component: + +```javascript +import ServerComponent from './components/ServerComponent' + +export default function Home() { + return ( +
+ +
+ ) +} +``` + +### Step 5: Run and Test Our Dapp + +Start our Next.js application using `npm run dev`. Verify that the server component is fetching data without exposing the API key. + +![Server-side rendering](/img/api-key-server-side-rendering.png) + +### Conclusion + +By utilizing Next.js Server Components, we've effectively hidden the API key from the client-side, enhancing the security of our application. This method ensures that sensitive operations are handled server-side, away from potential client-side vulnerabilities. Finally, be sure to explore [other API key security measures](/subgraphs/querying/managing-api-keys/) to increase your API key security even further. diff --git a/website/src/pages/zh/subgraphs/guides/subgraph-debug-forking.mdx b/website/src/pages/zh/subgraphs/guides/subgraph-debug-forking.mdx new file mode 100644 index 000000000000..91aa7484d2ec --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/subgraph-debug-forking.mdx @@ -0,0 +1,101 @@ +--- +title: Quick and Easy Subgraph Debugging Using Forks +--- + +As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your Subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing **Subgraph forking**, developed by [LimeChain](https://limechain.tech/), and in this article I will show you how this feature can be used to substantially speed-up Subgraph debugging! + +## Ok, what is it? + +**Subgraph forking** is the process of lazily fetching entities from _another_ Subgraph's store (usually a remote one). + +In the context of debugging, **Subgraph forking** allows you to debug your failed Subgraph at block _X_ without needing to wait to sync-up to block _X_. + +## What?! How? + +When you deploy a Subgraph to a remote Graph Node for indexing and it fails at block _X_, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block _X_. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block _X_. + +In a nutshell, we are going to _fork the failing Subgraph_ from a remote Graph Node that is guaranteed to have the Subgraph indexed up to block _X_ in order to provide the locally deployed Subgraph being debugged at block _X_ an up-to-date view of the indexing state. + +## Please, show me some code! + +To stay focused on Subgraph debugging, let's keep things simple and run along with the [example-Subgraph](https://github.com/graphprotocol/graph-tooling/tree/main/examples/ethereum-gravatar) indexing the Ethereum Gravity smart contract. + +Here are the handlers defined for indexing `Gravatar`s, with no bugs whatsoever: + +```tsx +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex().toString()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let gravatar = Gravatar.load(event.params.id.toI32().toString()) + if (gravatar == null) { + log.critical('Gravatar not found!', []) + return + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +Oops, how unfortunate, when I deploy my perfect looking Subgraph to [Subgraph Studio](https://thegraph.com/studio/) it fails with the _"Gravatar not found!"_ error. + +The usual way to attempt a fix is: + +1. Make a change in the mappings source, which you believe will solve the issue (while I know it won't). +2. Re-deploy the Subgraph to [Subgraph Studio](https://thegraph.com/studio/) (or another remote Graph Node). +3. Wait for it to sync-up. +4. If it breaks again go back to 1, otherwise: Hooray! + +It is indeed pretty familiar to an ordinary debug process, but there is one step that horribly slows down the process: _3. Wait for it to sync-up._ + +Using **Subgraph forking** we can essentially eliminate this step. Here is how it looks: + +0. Spin-up a local Graph Node with the **_appropriate fork-base_** set. +1. Make a change in the mappings source, which you believe will solve the issue. +2. Deploy to the local Graph Node, **_forking the failing Subgraph_** and **_starting from the problematic block_**. +3. If it breaks again, go back to 1, otherwise: Hooray! + +Now, you may have 2 questions: + +1. fork-base what??? +2. Forking who?! + +And I answer: + +1. `fork-base` is the "base" URL, such that when the _subgraph id_ is appended the resulting URL (`/`) is a valid GraphQL endpoint for the Subgraph's store. +2. Forking is easy, no need to sweat: + +```bash +$ graph deploy --debug-fork --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +Also, don't forget to set the `dataSources.source.startBlock` field in the Subgraph manifest to the number of the problematic block, so you can skip indexing unnecessary blocks and take advantage of the fork! + +So, here is what I do: + +1. I spin-up a local Graph Node ([here is how to do it](https://github.com/graphprotocol/graph-node#running-a-local-graph-node)) with the `fork-base` option set to: `https://api.thegraph.com/subgraphs/id/`, since I will fork a Subgraph, the buggy one I deployed earlier, from [Subgraph Studio](https://thegraph.com/studio/). + +``` +$ cargo run -p graph-node --release -- \ + --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ + --ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \ + --ipfs 127.0.0.1:5001 + --fork-base https://api.thegraph.com/subgraphs/id/ +``` + +2. After careful inspection I notice that there is a mismatch in the `id` representations used when indexing `Gravatar`s in my two handlers. While `handleNewGravatar` converts it to a hex (`event.params.id.toHex()`), `handleUpdatedGravatar` uses an int32 (`event.params.id.toI32()`) which causes the `handleUpdatedGravatar` to panic with "Gravatar not found!". I make them both convert the `id` to a hex. +3. After I made the changes I deploy my Subgraph to the local Graph Node, **_forking the failing Subgraph_** and setting `dataSources.source.startBlock` to `6190343` in `subgraph.yaml`: + +```bash +$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020 +``` + +4. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working. +5. I deploy my now bug-free Subgraph to a remote Graph Node and live happily ever after! (no potatoes tho) diff --git a/website/src/pages/zh/subgraphs/guides/subgraph-uncrashable.mdx b/website/src/pages/zh/subgraphs/guides/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..a08e2a7ad8c9 --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Safe Subgraph Code Generator +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) is a code generation tool that generates a set of helper functions from the graphql schema of a project. It ensures that all interactions with entities in your Subgraph are completely safe and consistent. + +## Why integrate with Subgraph Uncrashable? + +- **Continuous Uptime**. Mishandled entities may cause Subgraphs to crash, which can be disruptive for projects that are dependent on The Graph. Set up helper functions to make your Subgraphs “uncrashable” and ensure business continuity. + +- **Completely Safe**. Common problems seen in Subgraph development are issues of loading undefined entities, not setting or initializing all values of entities, and race conditions on loading and saving entities. Ensure all interactions with entities are completely atomic. + +- **User Configurable** Set default values and configure the level of security checks that suits your individual project's needs. Warning logs are recorded indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +**Key Features** + +- The code generation tool accommodates **all** Subgraph types and is configurable for users to set sane defaults on values. The code generation will use this config to generate helper functions that are to the users specification. + +- The framework also includes a way (via the config file) to create custom, but safe, setter functions for groups of entity variables. This way it is impossible for the user to load/use a stale graph entity and it is also impossible to forget to save or set a variable that is required by the function. + +- Warning logs are recorded as logs indicating where there is a breach of Subgraph logic to help patch the issue to ensure data accuracy. + +Subgraph Uncrashable can be run as an optional flag using the Graph CLI codegen command. + +```sh +graph codegen -u [options] [] +``` + +Visit the [Subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) or watch this [video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) to learn more and to get started with developing safer Subgraphs. diff --git a/website/src/pages/zh/subgraphs/guides/transfer-to-the-graph.mdx b/website/src/pages/zh/subgraphs/guides/transfer-to-the-graph.mdx new file mode 100644 index 000000000000..a62072c48373 --- /dev/null +++ b/website/src/pages/zh/subgraphs/guides/transfer-to-the-graph.mdx @@ -0,0 +1,104 @@ +--- +title: Transfer to The Graph +--- + +Quickly upgrade your Subgraphs from any platform to [The Graph's decentralized network](https://thegraph.com/networks/). + +## Benefits of Switching to The Graph + +- Use the same Subgraph that your apps already use with zero-downtime migration. +- Increase reliability from a global network supported by 100+ Indexers. +- Receive lightning-fast support for Subgraphs 24/7, with an on-call engineering team. + +## Upgrade Your Subgraph to The Graph in 3 Easy Steps + +1. [Set Up Your Studio Environment](/subgraphs/cookbook/transfer-to-the-graph/#1-set-up-your-studio-environment) +2. [Deploy Your Subgraph to Studio](/subgraphs/cookbook/transfer-to-the-graph/#2-deploy-your-subgraph-to-studio) +3. [Publish to The Graph Network](/subgraphs/cookbook/transfer-to-the-graph/#publish-your-subgraph-to-the-graphs-decentralized-network) + +## 1. Set Up Your Studio Environment + +### Create a Subgraph in Subgraph Studio + +- Go to [Subgraph Studio](https://thegraph.com/studio/) and connect your wallet. +- Click "Create a Subgraph". It is recommended to name the Subgraph in Title Case: "Subgraph Name Chain Name". + +> Note: After publishing, the Subgraph name will be editable but requires onchain action each time, so name it properly. + +### Install the Graph CLI⁠ + +You must have [Node.js](https://nodejs.org/) and a package manager of your choice (`npm` or `pnpm`) installed to use the Graph CLI. Check for the [most recent](https://github.com/graphprotocol/graph-tooling/releases?q=%40graphprotocol%2Fgraph-cli&expanded=true) CLI version. + +On your local machine, run the following command: + +Using [npm](https://www.npmjs.com/): + +```sh +npm install -g @graphprotocol/graph-cli@latest +``` + +Use the following command to create a Subgraph in Studio using the CLI: + +```sh +graph init --product subgraph-studio +``` + +### Authenticate Your Subgraph + +In The Graph CLI, use the auth command seen in Subgraph Studio: + +```sh +graph auth +``` + +## 2. Deploy Your Subgraph to Studio + +If you have your source code, you can easily deploy it to Studio. If you don't have it, here's a quick way to deploy your Subgraph. + +In The Graph CLI, run the following command: + +```sh +graph deploy --ipfs-hash + +``` + +> **Note:** Every Subgraph has an IPFS hash (Deployment ID), which looks like this: "Qmasdfad...". To deploy simply use this **IPFS hash**. You’ll be prompted to enter a version (e.g., v0.0.1). + +## 3. Publish Your Subgraph to The Graph Network + +![publish button](/img/publish-sub-transfer.png) + +### Query Your Subgraph + +> To attract about 3 indexers to query your Subgraph, it’s recommended to curate at least 3,000 GRT. To learn more about curating, check out [Curating](/resources/roles/curating/) on The Graph. + +You can start [querying](/subgraphs/querying/introduction/) any Subgraph by sending a GraphQL query into the Subgraph’s query URL endpoint, which is located at the top of its Explorer page in Subgraph Studio. + +#### Example + +[CryptoPunks Ethereum Subgraph](https://thegraph.com/explorer/subgraphs/HdVdERFUe8h61vm2fDyycHgxjsde5PbB832NHgJfZNqK) by Messari: + +![Query URL](/img/cryptopunks-screenshot-transfer.png) + +The query URL for this Subgraph is: + +```sh +https://gateway-arbitrum.network.thegraph.com/api/`**your-own-api-key**`/subgraphs/id/HdVdERFUe8h61vm2fDyycgxjsde5PbB832NHgJfZNqK +``` + +Now, you simply need to fill in **your own API Key** to start sending GraphQL queries to this endpoint. + +### Getting your own API Key + +You can create API Keys in Subgraph Studio under the “API Keys” menu at the top of the page: + +![API keys](/img/Api-keys-screenshot.png) + +### Monitor Subgraph Status + +Once you upgrade, you can access and manage your Subgraphs in [Subgraph Studio](https://thegraph.com/studio/) and explore all Subgraphs in [The Graph Explorer](https://thegraph.com/networks/). + +### Additional Resources + +- To quickly create and publish a new Subgraph, check out the [Quick Start](/subgraphs/quick-start/). +- To explore all the ways you can optimize and customize your Subgraph for a better performance, read more about [creating a Subgraph here](/developing/creating-a-subgraph/).