From 1e53977821d423564f6bab8244d82ed112e97402 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Rouleau?= Date: Fri, 24 Mar 2023 14:12:35 -0400 Subject: [PATCH] New Crowdin updates (#328) * New translations global.json (Spanish) * New translations global.json (Japanese) * New translations global.json (Ukrainian) * New translations global.json (Chinese Simplified) * New translations index.json (Spanish) * New translations index.json (Japanese) * New translations index.json (Chinese Simplified) * New translations docsearch.json (Spanish) * New translations docsearch.json (Japanese) * New translations docsearch.json (Chinese Simplified) * New translations cosmos.mdx (Spanish) * New translations cosmos.mdx (Japanese) * New translations cosmos.mdx (Urdu (Pakistan)) * New translations managing-api-keys.mdx (Spanish) * New translations managing-api-keys.mdx (Japanese) * New translations arweave.mdx (Japanese) * New translations arweave.mdx (Russian) * New translations migrating-a-subgraph.mdx (Spanish) * New translations migrating-a-subgraph.mdx (Japanese) * New translations migrating-a-subgraph.mdx (Urdu (Pakistan)) * New translations migrating-a-subgraph.mdx (Hindi) * New translations subgraph-debug-forking.mdx (Spanish) * New translations subgraph-debug-forking.mdx (Japanese) * New translations subgraph-debug-forking.mdx (Urdu (Pakistan)) * New translations deploying-a-subgraph-to-studio.mdx (Spanish) * New translations deploying-a-subgraph-to-studio.mdx (Japanese) * New translations deploying-a-subgraph-to-studio.mdx (Russian) * New translations deploying-a-subgraph-to-studio.mdx (Urdu (Pakistan)) * New translations subgraph-studio-faqs.mdx (Spanish) * New translations subgraph-studio-faqs.mdx (Japanese) * New translations subgraph-studio-faqs.mdx (Urdu (Pakistan)) * New translations subgraph-studio-faqs.mdx (Hindi) * New translations assemblyscript-api.mdx (Spanish) * New translations assemblyscript-api.mdx (Japanese) * New translations assemblyscript-api.mdx (Urdu (Pakistan)) * New translations unit-testing-framework.mdx (Spanish) * New translations unit-testing-framework.mdx (Japanese) * New translations unit-testing-framework.mdx (Urdu (Pakistan)) * New translations transferring-subgraph-ownership.mdx (Spanish) * New translations transferring-subgraph-ownership.mdx (Japanese) * New translations curating.mdx (Spanish) * New translations curating.mdx (Japanese) * New translations curating.mdx (Ukrainian) * New translations delegating.mdx (Japanese) * New translations delegating.mdx (Ukrainian) * New translations delegating.mdx (Urdu (Pakistan)) * New translations distributed-systems.mdx (Spanish) * New translations distributed-systems.mdx (Japanese) * New translations distributed-systems.mdx (Russian) * New translations querying-best-practices.mdx (Spanish) * New translations querying-best-practices.mdx (Japanese) * New translations querying-best-practices.mdx (Urdu (Pakistan)) * New translations querying-the-hosted-service.mdx (Spanish) * New translations querying-the-hosted-service.mdx (Japanese) * New translations assemblyscript-migration-guide.mdx (Spanish) * New translations assemblyscript-migration-guide.mdx (Japanese) * New translations assemblyscript-migration-guide.mdx (Urdu (Pakistan)) * New translations grafting.mdx (Japanese) * New translations grafting.mdx (Hindi) * New translations firehose.mdx (Spanish) * New translations firehose.mdx (Japanese) * New translations glossary.mdx (Spanish) * New translations glossary.mdx (Japanese) * New translations arbitrum-faq.mdx (Spanish) * New translations arbitrum-faq.mdx (Japanese) * New translations arbitrum-faq.mdx (Urdu (Pakistan)) * New translations subgraph-uncrashable.mdx (Spanish) * New translations subgraph-uncrashable.mdx (Japanese) * New translations subgraph-uncrashable.mdx (Urdu (Pakistan)) * New translations subgraph-uncrashable.mdx (Hindi) * New translations base-testnet.mdx (Spanish) * New translations base-testnet.mdx (Japanese) * New translations base-testnet.mdx (Russian) * New translations base-testnet.mdx (Urdu (Pakistan)) * New translations mips-faqs.mdx (Spanish) * New translations mips-faqs.mdx (Japanese) * New translations arweave.mdx (Japanese) * New translations near.mdx (Urdu (Pakistan)) * New translations assemblyscript-migration-guide.mdx (Japanese) * Run `pnpm lint:fix` --- website/pages/ar/cookbook/cosmos.mdx | 1 - website/pages/es/arbitrum-faq.mdx | 80 +++ website/pages/es/cookbook/base-testnet.mdx | 112 +++ website/pages/es/cookbook/cosmos.mdx | 1 - .../es/cookbook/migrating-a-subgraph.mdx | 188 +++-- .../es/cookbook/subgraph-uncrashable.mdx | 29 + .../deploying-a-subgraph-to-studio.mdx | 12 +- .../es/deploying/subgraph-studio-faqs.mdx | 22 +- .../es/developing/assemblyscript-api.mdx | 320 +++++---- .../es/developing/unit-testing-framework.mdx | 647 ++++++++++++++--- website/pages/es/docsearch.json | 52 +- website/pages/es/firehose.mdx | 11 + website/pages/es/global.json | 26 +- website/pages/es/glossary.mdx | 79 +++ website/pages/es/index.json | 8 +- .../transferring-subgraph-ownership.mdx | 12 +- website/pages/es/mips-faqs.mdx | 125 ++++ website/pages/es/network/curating.mdx | 58 +- .../pages/es/querying/distributed-systems.mdx | 14 +- .../pages/es/querying/managing-api-keys.mdx | 42 +- .../es/querying/querying-best-practices.mdx | 348 ++++------ .../querying/querying-the-hosted-service.mdx | 10 +- .../assemblyscript-migration-guide.mdx | 76 +- website/pages/hi/cookbook/grafting.mdx | 186 +++++ .../hi/cookbook/migrating-a-subgraph.mdx | 219 ++++++ .../hi/cookbook/subgraph-uncrashable.mdx | 29 + .../hi/deploying/subgraph-studio-faqs.mdx | 31 + website/pages/ja/arbitrum-faq.mdx | 80 +++ website/pages/ja/cookbook/arweave.mdx | 196 +++--- website/pages/ja/cookbook/base-testnet.mdx | 112 +++ website/pages/ja/cookbook/cosmos.mdx | 1 - website/pages/ja/cookbook/grafting.mdx | 186 +++++ .../ja/cookbook/migrating-a-subgraph.mdx | 140 +++- .../ja/cookbook/subgraph-debug-forking.mdx | 10 +- .../ja/cookbook/subgraph-uncrashable.mdx | 29 + .../deploying-a-subgraph-to-studio.mdx | 10 +- .../ja/deploying/subgraph-studio-faqs.mdx | 22 +- .../ja/developing/assemblyscript-api.mdx | 184 +++-- .../ja/developing/unit-testing-framework.mdx | 655 +++++++++++++++--- website/pages/ja/docsearch.json | 52 +- website/pages/ja/firehose.mdx | 11 + website/pages/ja/global.json | 42 +- website/pages/ja/glossary.mdx | 79 +++ website/pages/ja/index.json | 24 +- website/pages/ja/mips-faqs.mdx | 125 ++++ website/pages/ja/network/curating.mdx | 10 +- website/pages/ja/network/delegating.mdx | 60 +- .../pages/ja/querying/distributed-systems.mdx | 2 +- .../pages/ja/querying/managing-api-keys.mdx | 42 +- .../ja/querying/querying-best-practices.mdx | 342 ++++----- .../querying/querying-the-hosted-service.mdx | 4 +- .../assemblyscript-migration-guide.mdx | 14 +- website/pages/ko/cookbook/cosmos.mdx | 1 - website/pages/ru/cookbook/arweave.mdx | 2 +- website/pages/ru/cookbook/base-testnet.mdx | 110 +++ .../deploying-a-subgraph-to-studio.mdx | 70 ++ .../pages/ru/querying/distributed-systems.mdx | 134 ++++ website/pages/uk/global.json | 2 +- website/pages/uk/network/curating.mdx | 68 +- website/pages/ur/arbitrum-faq.mdx | 80 +++ website/pages/ur/cookbook/base-testnet.mdx | 112 +++ .../ur/cookbook/migrating-a-subgraph.mdx | 14 +- website/pages/ur/cookbook/near.mdx | 2 +- .../ur/cookbook/subgraph-uncrashable.mdx | 29 + .../deploying-a-subgraph-to-studio.mdx | 12 +- .../ur/deploying/subgraph-studio-faqs.mdx | 2 +- .../ur/developing/assemblyscript-api.mdx | 7 + .../ur/developing/unit-testing-framework.mdx | 8 +- website/pages/vi/cookbook/cosmos.mdx | 1 - website/pages/zh/cookbook/cosmos.mdx | 1 - website/pages/zh/docsearch.json | 52 +- website/pages/zh/global.json | 44 +- website/pages/zh/index.json | 36 +- website/route-lockfile.txt | 25 +- 74 files changed, 4508 insertions(+), 1474 deletions(-) delete mode 120000 website/pages/ar/cookbook/cosmos.mdx create mode 100644 website/pages/es/arbitrum-faq.mdx create mode 100644 website/pages/es/cookbook/base-testnet.mdx delete mode 120000 website/pages/es/cookbook/cosmos.mdx create mode 100644 website/pages/es/cookbook/subgraph-uncrashable.mdx create mode 100644 website/pages/es/firehose.mdx create mode 100644 website/pages/es/glossary.mdx create mode 100644 website/pages/es/mips-faqs.mdx create mode 100644 website/pages/hi/cookbook/grafting.mdx create mode 100644 website/pages/hi/cookbook/migrating-a-subgraph.mdx create mode 100644 website/pages/hi/cookbook/subgraph-uncrashable.mdx create mode 100644 website/pages/hi/deploying/subgraph-studio-faqs.mdx create mode 100644 website/pages/ja/arbitrum-faq.mdx create mode 100644 website/pages/ja/cookbook/base-testnet.mdx delete mode 120000 website/pages/ja/cookbook/cosmos.mdx create mode 100644 website/pages/ja/cookbook/grafting.mdx create mode 100644 website/pages/ja/cookbook/subgraph-uncrashable.mdx create mode 100644 website/pages/ja/firehose.mdx create mode 100644 website/pages/ja/glossary.mdx create mode 100644 website/pages/ja/mips-faqs.mdx delete mode 120000 website/pages/ko/cookbook/cosmos.mdx create mode 100644 website/pages/ru/cookbook/base-testnet.mdx create mode 100644 website/pages/ru/deploying/deploying-a-subgraph-to-studio.mdx create mode 100644 website/pages/ru/querying/distributed-systems.mdx create mode 100644 website/pages/ur/arbitrum-faq.mdx create mode 100644 website/pages/ur/cookbook/base-testnet.mdx create mode 100644 website/pages/ur/cookbook/subgraph-uncrashable.mdx delete mode 120000 website/pages/vi/cookbook/cosmos.mdx delete mode 120000 website/pages/zh/cookbook/cosmos.mdx diff --git a/website/pages/ar/cookbook/cosmos.mdx b/website/pages/ar/cookbook/cosmos.mdx deleted file mode 120000 index 66acfa28a317..000000000000 --- a/website/pages/ar/cookbook/cosmos.mdx +++ /dev/null @@ -1 +0,0 @@ -../../en/cookbook/cosmos.mdx \ No newline at end of file diff --git a/website/pages/es/arbitrum-faq.mdx b/website/pages/es/arbitrum-faq.mdx new file mode 100644 index 000000000000..cd214d9416ae --- /dev/null +++ b/website/pages/es/arbitrum-faq.mdx @@ -0,0 +1,80 @@ +--- +title: Preguntas frecuentes sobre Arbitrum +--- + +Haz clic [aquí](#billing-on-arbitrum-faqs) si deseas saltar a las preguntas frecuentes sobre facturación de Arbitrum. + +## Preguntas Frecuentes generales + +### ¿Por qué The Graph está implementando una solución L2? + +Al escalar The Graph en L2, los participantes de la red pueden esperar: + +- 26x de ahorros en tarifas de gas + +- Mayor velocidad de transacción + +- Asegurado por Ethereum + +El protocolo permite que los participantes de la red interactúen con mayor frecuencia a un costo reducido en las tarifas de gas. Esto permite a los Indexadores indexar una mayor cantidad de subgrafos, permite a los desarrolladores deployar y actualizar subgrafos con mayor facilidad, permite a los Delegadores delegar GRT con mayor frecuencia y brinda a los Curadores la capacidad de agregar señal a una mayor cantidad de subgrafos. + +La comunidad de The Graph [decidió](https://forum.thegraph.com/t/gip-0031-arbitrum-grt-bridge/3305) avanzar con Arbitrum el año pasado. + +### ¿Qué debo hacer para usar The Graph en L2? + +Los usuarios realizan el bridge de su GRT y ETH mediante uno de los siguientes métodos: + +- [The Graph Bridge en Arbitrum](https://bridge.arbitrum.io/?l2ChainId=42161) +- [TransferTo](https://transferto.xyz/swap) +- [Connext Bridge](https://bridge.connext.network/) +- [Hop Exchange](https://app.hop.exchange/#/send?token=ETH) + +Para aprovechar el uso de The Graph en L2, usa este conmutador desplegable para alternar entre cadenas. + +{/* Insert an image */} ![Dropdown desplegable para alternar Arbitrum](/img/arbitrum-screenshot-toggle.png) + +### Como developer de subgrafos, consumidor de datos, Indexador, Curador o Delegador, ¿qué debo hacer ahora? + +No se requiere ninguna acción inmediata. + +Los equipos de core devs están trabajando para crear asistentes de migración que facilitarán significativamente el traslado de la delegación, la curación y los subgrafos a Arbitrum. Los participantes de la red pueden esperar que los asistentes de migración estén disponibles en abril de 2023. + +La comunidad de The Graph también puede esperar que las recompensas de indexación se habiliten en Arbitrum en febrero o marzo de 2023. + +### Si me gustaría participar en la red en L2, ¿qué debo hacer? + +Ayuda a [probar la red](https://testnet.thegraph.com/explorer) en L2 y envía comentarios sobre tu experiencia en [Discord](https://discord.gg/vtvv7FP). + +### ¿Existe algún riesgo asociado con escalar la red a L2? + +Todos los contratos inteligentes han sido minuciosamente [auditados](https://github.com/graphprotocol/contracts/blob/dev/audits/OpenZeppelin/2022-07-graph-arbitrum-bridge-audit.pdf). + +Todo se ha probado exhaustivamente y existe un plan de contingencia para garantizar una transición segura y sin problemas. Los detalles se pueden encontrar [aquí](https://forum.thegraph.com/t/gip-0037-the-graph-arbitrum-deployment-with-linear-rewards-minted-in-l2/3551#risks-and -consideraciones-de-seguridad-20). + +### ¿Seguirán funcionando los subgrafos existentes en Ethereum? + +Sí, los contratos de The Graph Network operarán en paralelo tanto en Ethereum como en Arbitrum hasta que pasen completamente a Arbitrum en una fecha posterior. + +### ¿GRT tendrá un nuevo contrato inteligente implementado en Arbitrum? + +Sí, GRT tiene un [contrato inteligente adicional en Arbitrum](https://arbiscan.io/address/0x9623063377ad1b27544c965ccd7342f7ea7e88c7). Sin embargo, el [contrato GRT](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) de la mainnet de Ethereum seguirá operativo. + +## Preguntas frecuentes sobre facturación en Arbitrum + +### ¿Qué debo hacer con el GRT en mi saldo de facturación? + +¡Nada! Tu GRT se ha migrado de forma segura a Arbitrum y se está utilizando para pagar consultas mientras lees esto. + +### ¿Cómo sé que mis fondos han migrado de forma segura a Arbitrum? + +Todos los saldos de facturación de GRT ya se han migrado con éxito a Arbitrum. Puedes ver el contrato de facturación en Arbitrum [aquí](https://arbiscan.io/address/0x1B07D3344188908Fb6DEcEac381f3eE63C48477a). + +### ¿Cómo sé que el bridge Arbitrum es seguro? + +El bridge ha sido [fuertemente auditado](https://code4rena.com/contests/2022-10-the-graph-l2-bridge-contest) para garantizar la seguridad de todos los usuarios. + +### ¿Qué debo hacer si agrego GRT fresco de mi billetera mainnet de Ethereum? + +Puedes agregar GRT a tu saldo de facturación de Arbitrum con una experiencia de un clic en [Subgraph Studio](https://thegraph.com/studio/). Podrás hacer el bridge fácilmente de tu GRT a Arbitrum y completar tus claves API en una sola transacción. + +Visita la [Billing page](https://thegraph.com/docs/en/billing/) para obtener instrucciones más detalladas sobre cómo agregar, retirar o adquirir GRT. diff --git a/website/pages/es/cookbook/base-testnet.mdx b/website/pages/es/cookbook/base-testnet.mdx new file mode 100644 index 000000000000..0fdff9325e9e --- /dev/null +++ b/website/pages/es/cookbook/base-testnet.mdx @@ -0,0 +1,112 @@ +--- +title: Construcción de subgrafos en Base +--- + +Esta guía te conducirá rápidamente a través de cómo iniciar, crear e deployar tu subgrafo en Base testnet. + +Lo que necesitarás: + +- Una dirección de contrato de Base testnet +- Una wallet cripto (por ejemplo, MetaMask o Coinbase Wallet) + +## Subgraph Studio + +### 1. Instala The Graph CLI + +La CLI de The Graph (>=v0.41.0) está escrita en JavaScript y necesitarás tener instalado `npm` o `yarn` para usarlo. + +```sh +# NPM +npm install -g @graphprotocol/graph-cli + +# Yarn +yarn global add @graphprotocol/graph-cli +``` + +### 2. Crea tu subgrafo en Subgraph Studio + +Ve a [Subgraph Studio](https://thegraph.com/studio/) y conecta tu wallet crypto. + +Una vez conectado, haz clic en "Crear un subgrafo" e ingresa un nombre para tu subgrafo. + +Selecciona "Base (testnet)" como la cadena de bloques indexada y haz clic en Crear subgrafo. + +### 3. Inicia tu subgrafo + +> Puedes encontrar comandos específicos para su subgrafo en Subgraph Studio. + +Asegúrate de que el graph-cli esté actualizado a la última versión (superior a 0.41.0) + +```sh +graph --versión +``` + +Inicia tu subgrafo a partir de un contrato existente. + +```sh +graph init --studio +``` + +Tu slug de subgrafo es un identificador para tu subgrafo. La herramienta CLI te guiará a través de los pasos para crear un subgrafo, que incluyen: + +- Protocolo: ethereum +- Slug de subgrafo: `` +- Directorio para crear el subgrafo en: `` +- Red Ethereum: base-testnet \_ Dirección del contrato: `` +- Bloque de inicio (opcional) +- Nombre del contrato: `` +- Sí/no a los eventos de indexación (sí significa que tu subgrafo se iniciará con entidades en el esquema y asignaciones simples para eventos emitidos) + +### 3. Escribe tu subgrafo + +> Si los eventos emitidos son lo único que deseas indexar, entonces no se requiere trabajo adicional y puedes pasar al siguiente paso. + +El comando anterior crea un subgrafo de andamio que puedes usar como punto de partida para construir tu subgrafo. Al realizar cambios en el subgrafo, trabajarás principalmente con tres archivos: + +- Manifiesto (subgraph.yaml): el manifiesto define qué fuentes de datos indexarán tus subgrafos. Asegúrate de agregar `base-testnet` como el nombre de la red en el archivo de manifiesto para implementar tu subgrafo en Base testnet. +- Schema (schema.graphql) - El esquema GraphQL define los datos que deseas recuperar del subgrafo. +- AssemblyScript Mappings (mapping.ts) - Este es el código que traduce los datos de tus fuentes de datos a las entidades definidas en el esquema. + +Si deseas indexar datos adicionales, deberás ampliar el manifiesto, el esquema y los mappings. + +Para obtener más información sobre cómo escribir tu subgrafo, consulta [Crear un subgrafo](/developing/creating-a-subgraph). + +### 4. Deploy en Subgraph Studio + +Antes de que puedas deployar tu subgraph, deberás autenticarte con Subgraph Studio. Puedes hacer esto ejecutando el siguiente comando: + +Autenticar el subgrafo en el estudio + +``` +graph auth --studio +``` + +A continuación, ingresa el directorio de tu subgrafo. + +``` + cd +``` + +Construye tu subgrafo con el siguiente comando: + +```` +``` +graph codegen && graph build +``` +```` + +Finalmente, puedes deployar tu subgrafo usando este comando: + +```` +``` +graph deploy --studio +``` +```` + +### 5. Consulta tu subgrafo + +Una vez que se deploya tu subgrafo, puedes consultarlo desde tu dapp utilizando la "URL de consulta de desarrollo" en Subgraph Studio. + +Nota: la API de Studio tiene un límite de velocidad. Por lo tanto, debe usarse preferentemente para desarrollo y pruebas. + +Para obtener más información sobre cómo consultar datos de tu subgrafo, consulta la página [Consultar un subgrafo](/consultar/consultar-the-graph). diff --git a/website/pages/es/cookbook/cosmos.mdx b/website/pages/es/cookbook/cosmos.mdx deleted file mode 120000 index 66acfa28a317..000000000000 --- a/website/pages/es/cookbook/cosmos.mdx +++ /dev/null @@ -1 +0,0 @@ -../../en/cookbook/cosmos.mdx \ No newline at end of file diff --git a/website/pages/es/cookbook/migrating-a-subgraph.mdx b/website/pages/es/cookbook/migrating-a-subgraph.mdx index 96cc1ea58990..a501f93c501b 100644 --- a/website/pages/es/cookbook/migrating-a-subgraph.mdx +++ b/website/pages/es/cookbook/migrating-a-subgraph.mdx @@ -1,24 +1,24 @@ --- -title: Migrating an Existing Subgraph to The Graph Network +title: Migración de un Subgrafo Existente a The Graph Network --- ## Introducción -This is a guide on how to migrate your subgraph from the Hosted Service to The Graph Network. The migration to The Graph Network has been successful for projects like Opyn, UMA, mStable, Audius, PoolTogether, Livepeer, RAI, Enzyme, DODO, Opyn, Pickle, and BadgerDAO all of which are relying on data served by Indexers on the network. There are now over 200 subgraphs live on The Graph Network, generating query fees and actively indexing web3 data. +Esta es una guía sobre cómo migrar tu subgrafo desde el Servicio Alojado a la red descentralizada de The Graph. La migración a The Graph Network ha sido un éxito para proyectos como Opyn, UMA, mStable, Audius, PoolTogether, Livepeer, RAI, Enzyme, DODO, Pickle y BadgerDAO, todos los cuales dependen de datos servidos por Indexadores en la red. En la actualidad hay más de 700 subgrafos activos en la red descentralizada de The Graph, que generan tasas de consulta e indexan activamente datos de web3. -The process of migration is quick and your subgraphs will forever benefit from the reliability and performance that you can only get on The Graph Network. +El proceso de migración es rápido y tus subgrafos se beneficiarán para siempre de la fiabilidad y el rendimiento que solo puedes obtener en The Graph Network. -### When not to Migrate? +### Supuestos -If your subgraph is: +- Ya has deployado un subgrafo en el Servicio Alojado. +- El subgrafo está indexando una cadena disponible (o disponible en beta) en la red de The Graph. +- El subgrafo no tiene dependencias de IPFS o de búsqueda de texto completo (aún no son totalmente compatibles con la red descentralizada). -- Indexing [IPFS](https://ipfs.io/). -- Using [full-text search fields](/developing/creating-a-subgraph/#defining-fulltext-search-fields). -- Indexing chains other than Ethereum mainnet. +## Migración de un Subgrafo Existente a The Graph Network -### Migrating an Existing Subgraph to The Graph Network +> Puedes encontrar comandos específicos para tu subgrafo en el [Subgraph Studio](https://thegraph.com/studio/). -1. Get the latest version of the graph-cli installed: +1. Obtén la última versión de graph-cli instalada: ```sh npm install -g @graphprotocol/graph-cli @@ -28,26 +28,29 @@ npm install -g @graphprotocol/graph-cli yarn global add @graphprotocol/graph-cli ``` -2. Create a subgraph on the [Subgraph Studio](https://thegraph.com/studio/). Guides on how to do that can be found in the [Subgraph Studio docs](/deploying/subgraph-studio) and in [this video tutorial](https://www.youtube.com/watch?v=HfDgC2oNnwo). -3. Inside the main project subgraph repository, authenticate the subgraph to deploy and build on the studio: +También asegúrate de que tu `apiVersion` en subgraph.yaml es `0.0.5` o mayor. + +2. Dentro del repositorio del proyecto principal del subgrafo, autentifica el subgrafo para deployar y construir en el estudio: ```sh graph auth --studio ``` -4. Generate files and build the subgraph: +3. Genera archivos y construye el subgrafo: ```sh graph codegen && graph build ``` -5. Deploy the subgraph to the Studio. You can find your `` in the Studio UI, which is based on the name of your subgraph. +Si tu subgrafo tiene errores de construcción, consulte la [ Guía de Migración de AssemblyScript](/release-notes/assemblyscript-migration-guide/). + +4. Inicia sesión en [Subgraph Studio](https://thegraph.com/studio/) con tu wallet y realiza el deploy del subgrafo. Puedes encontrar `` en la UI del Studio, que se basa en el nombre de tu subgrafo. ```sh - graph deploy --studio +graph deploy --studio ``` -6. Test queries on the Studio's playground. Here are some examples for the [Sushi - Mainnet Exchange Subgraph](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&view=Playground): +5. Prueba las consultas en el Playground Studio. Aquí hay algunos ejemplos para [Sushi - Mainnet Exchange Subgraph](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&view=Playground): ```sh { @@ -64,92 +67,153 @@ graph codegen && graph build } ``` -7. Fill in the description and the details of your subgraph and choose up to 3 categories. Upload a project image in the Studio if you'd like as well. -8. Publish the subgraph on The Graph's Network by hitting the "Publish" button. +6. En este punto, tu subgrafo está ahora deployado en Subgraph Studio, pero aún no está publicado en la red descentralizada. Ahora puedes probar el subgrafo para asegurarte de que funciona como se espera utilizando la URL de consulta temporal que se ve en la parte superior de la columna derecha. Como este nombre ya sugiere, esta es una URL temporal y no debe ser usada en producción. + +- Recuerda que publicar es una acción on-chain y requerirá que el gas se pague en Ethereum - ve un ejemplo de transacción [aquí](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b). Los precios son aproximadamente alrededor de 0,0425 ETH a 100 gwei. +- Cada vez que necesites actualizar tu subgrafo, se te cobrará una tarifa de actualización. Recuerda que actualizar es simplemente publicar otra versión de tu subgrafo existente on-chain. Debido a que esto conlleva un coste, es muy recomendable deployar y probar tu subgrafo en Goerli antes de deployarlo en mainnet. En algunos casos, también puede requerir algo de GRT si no hay señal en el subgrafo. En el caso de que haya señal/curación en esa versión del subgrafo (usando auto-migración), los impuestos se dividirán. + +7. Publica el subgrafo en la red descentralizada de The Graph pulsando el botón "Publicar". + +Y eso es! Una vez que hayas terminado de publicar, podrás ver tus subgrafos activos en la red descentralizada via [The Graph Explorer](https://thegraph.com/explorer). + +No dudes en aprovechar el [#Curators channel](https://discord.gg/rC8rBuRtbH) en Discord para informar a los Curadores que tu subgrafo está listo para ser señalizado. También sería útil que compartieras tu volumen de consultas previsto con ellos. Así podrán estimar la cantidad de GRT que deben señalizar en tu subgrafo. + +### Crear una clave API + +Puedes generar una clave API en Subgraph Studio [aquí](https://thegraph.com/studio/apikeys/). + +![Página de creación de clave API](/img/api-image.png) + +Al final de cada semana, se generará una factura en función de las tarifas de consulta que hayan incurrido durante ese período. Esta factura se pagará automáticamente utilizando el GRT disponible en tu saldo. Tu saldo se actualizará después de que se retire el costo de las tarifas de consulta. Las tarifas de consulta se pagan en GRT a través de la red de Arbitrum. Deberás agregar GRT al contrato de facturación de Arbitrum para habilitar tu clave API mediante los siguientes pasos: + +- Adquiere GRT en un exchange de tu elección. +- Envía el GRT a tu wallet. +- En la página de facturación en Studio, haz clic en añadir GRT. + +![Añadir GRT en la facturación](/img/Add-GRT-New-Page.png) + +- Sigue los siguientes pasos para agregar tu GRT a tu saldo de facturación. +- Tu GRT se convertirá automáticamente en la red de Arbitrum y se agregará a tu saldo de facturación. + +![Panel de facturación](/img/New-Billing-Pane.png) + +> Nota: consulte la [official billing page](../billing.mdx) para obtener instrucciones completas sobre cómo agregar GRT a tu saldo de facturación. + +### Asegurando tu clave API -- Remember that publishing is an on-chain action and will require gas to be paid for in Ethereum - see an example transaction [here](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b). Prices are roughly around 0.0425 ETH at 100 gwei. -- Any time you need to upgrade your subgraph, you will be charged an upgrade fee. Remember, upgrading is just publishing another version of your existing subgraph on-chain. Because this incurs a cost, it is highly recommended to deploy and test your subgraph on Rinkeby before deploying to mainnet. It can, in some cases, also require some GRT if there is no signal on that subgraph. In the case there is signal/curation on that subgraph version (using auto-migrate), the taxes will be split. +Se recomienda asegurar la API limitando su uso de dos maneras: -And that's it! After you are done publishing, you'll be able to view your subgraphs live on the network via [The Graph Explorer](https://thegraph.com/explorer). +1. Subgrafos autorizados +2. Dominio autorizado + +Puedes proteger tu clave API [here](https://thegraph.com/studio/apikeys/test/). + +![Página de bloqueo del subgrafo](/img/subgraph-lockdown.png) + +### Consulta de su subgrafo en la red descentralizada + +Ahora puedes comprobar el estado de indexación de los Indexadores en la red en el Graph Explorer (ejemplo [aquí](https://thegraph.com/explorer/subgraph?id=S9ihna8D733WTEShJ1KctSTCvY1VJ7gdVwhUujq4Ejo&view=Indexers)). La línea verde de la parte superior indica que en el momento de la publicación 8 Indexadores han indexado con éxito ese subgrafo. También en el tab de Indexadores puedes ver qué Indexadores recogieron tu subgrafo. + +![Subgrafo de Rocket Pool](/img/rocket-pool-subgraph.png) + +Tan pronto como el primer Indexador haya indexado completamente tu subgrafo, podrás empezar a consultarlo en la red descentralizada. Para recuperar la URL de consulta de tu subgrafo, puedes copiar/pegar haciendo clic en el símbolo que aparece junto a la URL de consulta. Verás algo así: + +`https://gateway.thegraph.com/api/[api-key]/subgraphs/id/S9ihna8D733WTEShJ1KctSTCvY1VJ7gdVwhUujq4Ejo` + +Importante: Asegúrate de reemplazar `[api-key]` con una clave API real generada en la sección anterior. + +Ahora puedes usar esa URL de consulta en tu dapp para enviar tus solicitudes de GraphQL. + +¡Felicitaciones! ¡Ahora eres un pionero de la descentralización! + +> Nota: debido a la naturaleza distribuida de la red puede darse el caso que diferentes Indexadores hayan indexado hasta diferentes bloques. Para recibir solo datos recientes, puedes especificar el bloque mínimo que un Indexador tiene que tener indexado para servir tu consulta con el argumento del campo bloque: `{ number_gte: $minBlock }` como se muestra en el ejemplo siguiente: + +```graphql +{ + stakers(block: { number_gte: 14486109 }) { + id + } +} +``` -Feel free to leverage the [#Curators channel](https://discord.gg/rC8rBuRtbH) on Discord to let Curators know that your subgraph is ready to be signaled. It would also be helpful if you share your expected query volume with them. Therefore, they can estimate how much GRT they should signal on your subgraph. +Más información sobre la naturaleza de la red y cómo manejar re-orgs se describe en el artículo de documentación [Sistemas Distribuidos](/querying/distributed-systems/). -### Upgrading a Subgraph on the Network +## Actualización de un Subgrafo en la Red -If you would like to upgrade an existing subgraph on the network, you can do this by deploying a new version of your subgraph to the Subgraph Studio using the Graph CLI. +Si quieres actualizar un subgrafo existente en la red, puedes hacerlo deployando una nueva versión de tu subgrafo en el Subgraph Studio usando el GraphQLI. -1. Make changes to your current subgraph. A good idea is to test small fixes on the Subgraph Studio by publishing to Rinkeby. -2. Deploy the following and specify the new version in the command (eg. v0.0.1, v0.0.2, etc): +1. Haz cambios en tu subgrafo actual. Una buena idea es probar pequeñas correcciones en Subgraph Studio publicando en Goerli. +2. Deploya lo siguiente y especifica la nueva versión en el comando (por ejemplo, v0.0.1, v0.0.2, etc.): ```sh graph deploy --studio ``` -3. Test the new version in the Subgraph Studio by querying in the playground -4. Publish the new version on The Graph Network. Remember that this requires gas (as described in the section above). +3. Prueba la nueva versión en el Subgraph Studio consultando en el Playground +4. Publica la nueva versión en The Graph Network. Recuerda que esto requiere gas (como se describe en la sección anterior). -### Owner Upgrade Fee: Deep Dive +### Tarifa de Actualización del Propietario: Deep Dive -An upgrade requires GRT to be migrated from the old version of the subgraph to the new version. This means that for every upgrade, a new bonding curve will be created (more on bonding curves [here](/network/curating#bonding-curve-101)). +Una actualización requiere que el GRT migre de la versión antigua del subgrafo a la nueva versión. Esto significa que por cada actualización, se creará una nueva bonding curve (más sobre bonding curves [aquí](/network/curating#bonding-curve-101)). -The new bonding curve charges the 2.5% curation tax on all GRT being migrated to the new version. The owner must pay 50% of this, or 1.25%. The other 1.25% is absorbed by all the curators as a fee. This incentive design is in place to prevent an owner of a subgraph from being able to drain all their curator's funds with recursive upgrade calls. If there is no curation activity, you will have to pay a minimum of 100 GRT in order to signal your own subgraph. +La nueva bonding curve cobra 2,5% de tarifa de curación en todo el GRT que se migra a la nueva versión. El propietario debe pagar el 50% de esto o el 1,25%. El otro 1,25% es absorbido por todos los Curadores como tarifa. Este diseño de incentivos se ha implementado para evitar que un propietario de un subgrafo pueda agotar todos los fondos de un Curador con llamadas de actualización recurrentes. Si no hay actividad de curaduría, tendrás que pagar un mínimo de 100 GRT para señalar tu propio subgrafo. -Let's make an example, this is only the case if your subgraph is being actively curated on: +Hagamos un ejemplo, esto es solo el caso si tu subgrafo está siendo curado activamente en: -- 100,000 GRT is signaled using auto-migrate on v1 of a subgraph -- Owner upgrades to v2. 100,000 GRT is migrated to a new bonding curve, where 97,500 GRT get put into the new curve and 2,500 GRT is burned -- The owner then has 1250 GRT burned to pay for half the fee. The owner must have this in their wallet before the upgrade, otherwise, the upgrade will not succeed. This happens in the same transaction as the upgrade. +- Se señalizan 100.000 GRT mediante la auto-migración en v1 de un subgrafo +- El propietario actualiza a la v2. 100.000 GRT se migran a una nueva bonding curve, donde 97.500 GRT se ponen en la nueva curva y 2.500 GRT se queman +- El propietario tiene entonces 1250 GRT quemados para pagar la mitad de la tarifa. El propietario debe tener esto en su wallet antes de la actualización, de lo contrario, la actualización no tendrá éxito. Esto ocurre en la misma transacción que la actualización. -_While this mechanism is currently live on the network, the community is currently discussing ways to reduce the cost of upgrades for subgraph developers._ +_Aunque este mecanismo está actualmente en funcionamiento en la red, la comunidad está debatiendo formas de reducir el coste de las actualizaciones para los desarrolladores de subgrafos._ -### Maintaining a Stable Version of a Subgraph +### Mantener una Versión Estable de un Subgrafo -If you're making a lot of changes to your subgraph, it is not a good idea to continually upgrade it and front the upgrade costs. Maintaining a stable and consistent version of your subgraph is critical, not only from the cost perspective, but also so that Indexers can feel confident in their syncing times. Indexers should be flagged when you plan for an upgrade so that Indexer syncing times do not get impacted. Feel free to leverage the [#Indexers channel](https://discord.gg/rC8rBuRtbH) on Discord to let Indexers know when you're versioning your subgraphs. +Si estás haciendo muchos cambios en tu subgrafo, no es una buena idea actualizarlo continuamente y afrontar los costes de actualización. Mantener una versión estable y consistente de tu subgrafo es crítico, no sólo desde el punto de vista de los costes, sino también para que los Indexadores puedan sentirse seguros en sus tiempos de sincronización. Los Indexadores deben ser avisados cuando se planifica una actualización para que los tiempos de sincronización de los Indexadores no se vean afectados. No dudes en aprovechar el canal [#Indexers](https://discord.gg/rC8rBuRtbH) en Discord para avisar a los Indexadores cuando estés versionando tus subgrafos. -Subgraphs are open APIs that external developers are leveraging. Open APIs need to follow strict standards so that they do not break external developers' applications. In The Graph Network, a subgraph developer must consider Indexers and how long it takes them to sync a new subgraph **as well as** other developers who are using their subgraphs. +Los subgrafos son APIs abiertas que los desarrolladores externos aprovechan. Las APIs abiertas deben seguir normas estrictas para que no rompan las aplicaciones de los desarrolladores externos. En The Graph Network, un desarrollador de subgrafos debe tener en cuenta a los Indexadores y el tiempo que tardan en sincronizar un nuevo subgrafo, **así como** a otros desarrolladores que están utilizando sus subgrafos. -### Updating the Metadata of a Subgraph +### Actualización de los Metadatos de un subgrafo -You can update the metadata of your subgraphs without having to publish a new version. The metadata includes the subgraph name, image, description, website URL, source code URL, and categories. Developers can do this by updating their subgraph details in the Subgraph Studio where you can edit all applicable fields. +Puedes actualizar los metadatos de tu subgrafo sin tener que publicar una nueva versión. Los metadatos incluyen el nombre del subgrafo, la imagen, la descripción, la URL del sitio web, la URL del código fuente y las categorías. Los desarrolladores pueden hacer esto actualizando los detalles de sus subgrafos en el Subgraph Studio, donde se pueden editar todos los campos aplicables. -Make sure **Update Subgraph Details in Explorer** is checked and click on **Save**. If this is checked, an on-chain transaction will be generated that updates subgraph details in the Explorer without having to publish a new version with a new deployment. +Asegúrate de que la opción **Actualizar Detalles del Subgrafo en el Explorador** está marcada y haz clic en **Guardar**. Si está marcada, se generará una transacción on-chain que actualiza los detalles del subgrafo en el Explorador sin tener que publicar una nueva versión con un nuevo deploy. -## Best Practices for Deploying a Subgraph to The Graph Network +## Mejores Prácticas para Deployar un Subgrafo en The Graph Network -1. Leveraging an ENS name for Subgraph Development: +1. Aprovechar un nombre ENS para el Desarrollo de Subgrafos: -- Set up your ENS: [https://app.ens.domains/](https://app.ens.domains/) -- Add your ENS name to your settings [here](https://thegraph.com/explorer/settings?view=display-name). +- Configura tu ENS: [https://app.ens.domains/](https://app.ens.domains/) +- Añade tu nombre ENS a tu configuración [aquí](https://thegraph.com/explorer/settings?view=display-name). -2. The more filled out your profiles are, the better the chances for your subgraphs to be indexed and curated. +2. Cuanto más completos estén tus perfiles, más posibilidades tendrás de que tus subgrafos sean indexados y curados. -## Deprecating a Subgraph on The Graph Network +## Deprecar un Subgrafo en The Graph Network -Follow the steps [here](/managing/deprecating-a-subgraph) to deprecate your subgraph and remove it from The Graph Network. +Sigue los pasos [aquí](/managing/deprecating-a-subgraph) para deprecar tu subgrafo y eliminarlo de The Graph Network. -## Querying a Subgraph + Billing on The Graph Network +## Consulta de un Subgrafo + Facturación en The Graph Network -The Hosted Service was set up to allow developers to deploy their subgraphs without any restrictions. +El Servicio Alojado fue creado para permitir a los desarrolladores deployar sus subgrafos sin ninguna restricción. -In order for The Graph Network to truly be decentralized, query fees have to be paid as a core part of the protocol's incentives. For more information on subscribing to APIs and paying the query fees, check out billing documentation [here](/querying/billing). +Para que The Graph Network sea realmente descentralizada, las tarifas de consulta tienen que ser pagadas como parte central de los incentivos del protocolo. Para obtener más información sobre la suscripción a las API y el pago de las tarifas de consulta, consulta la documentación de facturación [aquí](/billing/). -### Estimate Query Fees on the Network +### Estimación de las Tarifas de Consulta en la Red -While this is not a live feature in the product UI, you can set your maximum budget per query by taking the amount you're willing to pay per month and dividing it by your expected query volume. +Aunque esta función no está disponible en la UI del producto, puedes establecer tu presupuesto máximo por consulta tomando la cantidad que estás dispuesto a pagar al mes y dividiéndola por el volumen de consultas previsto. -While you get to decide on your query budget, there is no guarantee that an Indexer will be willing to serve queries at that price. If a Gateway can match you to an Indexer willing to serve a query at, or lower than, the price you are willing to pay, you will pay the delta/difference of your budget **and** their price. As a consequence, a lower query price reduces the pool of Indexers available to you, which may affect the quality of service you receive. It's beneficial to have high query fees, as that may attract curation and big-name Indexers to your subgraph. +Mientras que tú decides tu presupuesto de consulta, no hay garantía de que un Indexador esté dispuesto a servir consultas a ese precio. Si un Gateway puede ponerle en contacto con un Indexador que esté dispuesto a servir una consulta al precio que tú estás dispuesto a pagar, pagarás el delta/diferencia de su presupuesto **y** su precio. En consecuencia, un precio de consulta más bajo reduce el conjunto de Indexadores disponibles para ti, lo que puede afectar a la calidad del servicio que recibe. Es beneficioso tener un precio de consulta alto, ya que eso puede atraer a Indexadores de renombre a tu subgrafo. -Remember that it's a dynamic and growing market, but how you interact with it is in your control. There is no maximum or minimum price specified in the protocol or the Gateways. For example, you can look at the price paid by a few of the dapps on the network (on a per-week basis), below. See the last column, which shows query fees in GRT. For example, [Pickle Finance](https://www.pickle.finance/) has 8 requests per second and paid 2.4 GRT for one week. +Recuerda que se trata de un mercado dinámico y en crecimiento, pero la forma de interactuar con él está bajo tu control. No hay un precio máximo o mínimo especificado en el protocolo o en los Gateways. Por ejemplo, puedes ver el precio que pagan algunas de las dApps de la red (por semana), a continuación. Véase la última columna, que muestra las tarifas de consulta en GRT. -![QueryFee](/img/QueryFee.png) +![Tarifa de Consulta](/img/QueryFee.png) -## Additional Resources +## Recursos Adicionales -If you're still confused, fear not! Check out the following resources or watch our video guide on migrating subgraphs to the decentralized network below: +Si todavía estás confundido, ¡no temas! Consulta los siguientes recursos o mira nuestra guía en vídeo sobre la migración de subgrafos a la red descentralizada a continuación: -- [The Graph Network Contracts](https://github.com/graphprotocol/contracts) -- [Curation Contract](https://github.com/graphprotocol/contracts/blob/dev/contracts/curation/Curation.sol) - the underlying contract that the GNS wraps around +- [Los Contratos de The Graph Network](https://github.com/graphprotocol/contracts) +- [Contrato de Curación](https://github.com/graphprotocol/contracts/blob/dev/contracts/curation/Curation.sol) - el contrato subyacente en el que se envuelve el GNS - Address - `0x8fe00a685bcb3b2cc296ff6ffeab10aca4ce1538` -- [Subgraph Studio documentation](/deploying/subgraph-studio) +- [Documentación de Subgraph Studio](/deploying/subgraph-studio) diff --git a/website/pages/es/cookbook/subgraph-uncrashable.mdx b/website/pages/es/cookbook/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..b513a0cc6ff3 --- /dev/null +++ b/website/pages/es/cookbook/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: Generador de código de subgrafo seguro +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) es una herramienta de generación de código que genera un conjunto de funciones auxiliares a partir del esquema graphql de un proyecto. Garantiza que todas las interacciones con las entidades en su subgrafo sean completamente seguras y consistentes. + +### ¿Por qué integrarse con Subgraph Uncrashable? + +- **Tiempo de actividad continuo**. Las entidades mal manejadas pueden hacer que los subgrafos se bloqueen, lo que puede ser perjudicial para los proyectos que dependen de The Graph. Configura funciones auxiliares para que tus subgrafos sean "uncrashable" y garantices la continuidad del negocio. + +- **Completamente seguro**. Los problemas comunes que se observan en el desarrollo de subgrafos son problemas de carga de entidades indefinidas, no establecer o inicializar todos los valores de las entidades y condiciones de carrera al cargar y guardar entidades. Asegúrate de que todas las interacciones con las entidades sean completamente atómicas. + +- **Configurable por el usuario** Establece valores predeterminados y configura el nivel de controles de seguridad que se adapte a las necesidades de tu proyecto individual. Se registran registros de advertencia que indican dónde hay una infracción de la lógica del subgrafo para ayudar a solucionar el problema y garantizar la precisión de los datos. + +**Características clave** + +- La herramienta de generación de código se adapta a **todos** los tipos de subgrafos y se puede configurar para que los usuarios establezcan valores predeterminados sensatos. La generación de código utilizará esta configuración para generar funciones auxiliares que cumplan con las especificaciones de los usuarios. + +- 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. + +- Los registros de advertencia se registran como registros que indican donde hay una infracción de la lógica del subgrafo para ayudar a solucionar el problema y garantizar la precisión de los datos. Estos registros se pueden ver en el servicio alojado de The Graph en la sección 'Registros'. + +Subgraph Uncrashable se puede ejecutar como un indicador opcional mediante el comando codegen Graph CLI. + +```sh +graph codegen -u [options] [] +``` + +Visita la [subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/) o mira este [video tutorial](https://float- capital.github.io/float-subgraph-uncrashable/docs/tutorial) para obtener más información y comenzar a desarrollar subgrafos más seguros. diff --git a/website/pages/es/deploying/deploying-a-subgraph-to-studio.mdx b/website/pages/es/deploying/deploying-a-subgraph-to-studio.mdx index 55acbe4f8b50..65ecbc8aff80 100644 --- a/website/pages/es/deploying/deploying-a-subgraph-to-studio.mdx +++ b/website/pages/es/deploying/deploying-a-subgraph-to-studio.mdx @@ -2,17 +2,11 @@ title: Deployar un Subgrafo en Subgraph Studio --- -## Redes admitidas +> Asegúrate de que la red desde la que tu subgrafo está indexando datos sea [compatible](/developing/supported-chains) en la red descentralizada. -La red de The Graph admite subgrafos que indexan la siguiente cadena: +Estos son los pasos para deployar tu subgrafo en Subgraph Studio: -### Ethereum - -- `mainnet` - -Deployar un Subgrafo en Subgraph Studio es bastante simple. Esto te llevará a través de los pasos para: - -- Instala The Graph CLI (con yarn y npm) +- Instala The Graph CLI (con yarn o npm) - Crea tu Subgrafo en Subgraph Studio - Autentica tu cuenta desde la CLI - Deployar un Subgrafo en Subgraph Studio diff --git a/website/pages/es/deploying/subgraph-studio-faqs.mdx b/website/pages/es/deploying/subgraph-studio-faqs.mdx index 56308696424f..3f3462885394 100644 --- a/website/pages/es/deploying/subgraph-studio-faqs.mdx +++ b/website/pages/es/deploying/subgraph-studio-faqs.mdx @@ -2,25 +2,29 @@ title: Preguntas Frecuentes sobre Subgraph Studio --- -### 1. ¿Cómo puedo crear una clave API? +### 1. ¿Qué es Subgraph Studio? -En Subgraph Studio, puedes crear las claves de la API que necesites y añadir configuraciones de seguridad a cada una de ellas. +[Subgraph Studio](https://thegraph.com/studio/) es una dapp para crear, administrar y publicar subgrafos y claves API. -### 2. ¿Puedo crear varias claves API? +### 2. ¿Cómo creo una clave API? -R: ¡Sí! Puedes crear varias claves API para utilizarlas en diferentes proyectos. Consulta el enlace [aquí](https://thegraph.com/studio/apikeys/). +Para crear una API, ve a Subgraph Studio y conecta tu wallet. Podrás hacer click en la pestaña de claves API en la parte superior. Allí, podrás crear una clave API. -### 3. ¿Cómo puedo restringir un dominio para una clave API? +### 3. ¿Puedo crear varias claves de API? -Después de crear una Clave de API, en la sección Seguridad puedes definir los dominios que pueden consultar una Clave de API específica. +¡Sí! Puedes crear varias claves de API para usar en diferentes proyectos. Consulta el enlace [aquí](https://thegraph.com/studio/apikeys/). -### 4. ¿Puedo transferir mi subgrafo a otro titular? +### 4. ¿Cómo restrinjo un dominio para una clave API? -Sí, los subgrafos que han sido publicados en Mainnet pueden ser transferidos a una nueva wallet o a una Multisig. Puedes hacerlo haciendo clic en los tres puntos junto al botón "Publicar" en la página de detalles del subgrafo y seleccionando "Transferir propiedad". +Después de crear una clave de API, en la sección Seguridad, puedes definir los dominios que pueden consultar una clave de API específica. + +### 5. ¿Puedo transferir mi subgrafo a otro propietario? + +Sí, los subgrafos que han sido publicados en Mainnet pueden ser transferidos a una nueva wallet o a una Multisig. Puedes hacerlo haciendo click en los tres puntos junto al botón "Publicar" en la página de detalles del subgrafo y seleccionando "Transferir propiedad". Ten en cuenta que ya no podrás ver o editar el subgrafo en Studio una vez que haya sido transferido. -### 5. ¿Cómo puedo encontrar las URL de consulta de los subgrafos si no soy el desarrollador del subgrafo que quiero utilizar? +### 6. ¿Cómo encuentro URLs de consulta para subgrafos si no soy el developer del subgrafo que quiero usar? Puedes encontrar la consulta URL de cada subgrafo en la sección Detalles del Subgrafo de The Graph Explorer. Cuando haces clic en el botón de "Query" (Consulta), serás dirigido a un panel en el que puedes ver la URL de consulta del subgrafo que te interesa. A continuación, puedes sustituir el marcador de posición `` por la clave API que deseas aprovechar en Subgraph Studio. diff --git a/website/pages/es/developing/assemblyscript-api.mdx b/website/pages/es/developing/assemblyscript-api.mdx index cce54d0796c1..3a5f7088e012 100644 --- a/website/pages/es/developing/assemblyscript-api.mdx +++ b/website/pages/es/developing/assemblyscript-api.mdx @@ -2,25 +2,25 @@ title: AssemblyScript API --- -> Nota: ten en cuenta que si creaste un subgrafo usando el `graph-cli`/`graph-ts` en su versión `0.22.0`, debes saber que estás utilizando una versión antigua del AssemblyScript y te recomendamos mirar la [`guía para migrar`](/release-notes/assemblyscript-migration-guide) tu código +> Nota: si creaste un subgrafo antes de `graph-cli`/`graph-ts` versión `0.22.0`, estás utilizando una versión anterior de AssemblyScript, te recomendamos que consultes la [`Migration Guide`](/release-notes/assemblyscript-migration-guide) -Está página explica que APIs usar para recibir ciertos datos de los subgrafos. Dos tipos de estas APIs se describen a continuación: +Esta página documenta qué API integradas se pueden usar al escribir mappings de subgrafos. Hay dos tipos de API disponibles listas para usar: -- La [librería de Graph TypeScript](https://github.com/graphprotocol/graph-ts) (`graph-ts`) y -- el generador de códigos provenientes de los archivos del subgrafo, `graph codegen`. +- la [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) y +- código generado a partir de archivos de subgrafos por `graph codegen`. -También es posible añadir otras librerías, siempre y cuando sean compatible con [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Debido a que ese lenguaje de mapeo es el que usamos, la [wiki de AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki) es una fuente muy completa para las características de este lenguaje y contiene una librería estándar que te puede resultar útil. +También es posible añadir otras librerías como dependencias, siempre y cuando sean compatible con [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Debido a que ese lenguaje de mapeo es el que usamos, la [wiki de AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki) es una buena fuente para las características de este lenguaje y librería estándar. ## Instalación -Los subgrafos creados con [`graph init`](/developing/creating-a-subgraph) vienen configurados previamente. Todo lo necesario para instalar estás configuraciones lo podrás encontrar en uno de los siguientes comandos: +Los subgrafos creados con [`graph init`](/developing/creating-a-subgraph) vienen con dependencias preconfiguradas. Todo lo que se requiere para instalar estas dependencias es ejecutar uno de los siguientes comandos: ```sh yarn install # Yarn npm install # NPM ``` -Si el subgrafo fue creado con scratch, uno de los siguientes dos comandos podrá instalar la librería TypeScript como una dependencia: +Si el subgrafo se creó desde cero, uno de los siguientes dos comandos instalará la biblioteca Graph TypeScript como una dependencia: ```sh yarn add --dev @graphprotocol/graph-ts # Yarn @@ -32,12 +32,12 @@ npm install --save-dev @graphprotocol/graph-ts # NPM La librería de `@graphprotocol/graph-ts` proporciona las siguientes APIs: - Una API de `ethereum` para trabajar con contratos inteligentes de Ethereum, eventos, bloques, transacciones y valores de Ethereum. -- Un `almacenamiento` para cargar y guardar entidades en Graph Node. -- Una API de `registro` para registrar los mensajes output de The Graph y el Graph Explorer. -- Una API para `ipfs` que permite cargar archivos provenientes de IPFS. +- Un `store` para cargar y guardar entidades en el Graph Node store. +- Una `log` API para registrar mensajes en la salida de Graph Node y Graph Explorer. +- Una API de `ipfs` que permite cargar archivos provenientes de IPFS. - Una API de `json` para analizar datos en formato JSON. -- Una API para `crypto` que permite usar funciones criptográficas. -- Niveles bajos que permiten traducir entre los distintos sistemas, tales como, Ethereum, JSON, GraphQL y AssemblyScript. +- Una API de `crypto` que permite usar funciones criptográficas. +- Primitivas de bajo nivel para traducir entre los distintos tipos de sistemas, tales como, Ethereum, JSON, GraphQL y AssemblyScript. ### Versiones @@ -45,17 +45,18 @@ La `apiVersion` en el manifiesto del subgrafo especifica la versión de la API c | Version | Notas del lanzamiento | | :-: | --- | -| 0.0.6 | Se agregó la casilla `nonce` a las Transacciones de Ethereum, se
añadió `baseFeePerGas` para los bloques de Ethereum | -| 0.0.5 | Se actualizó la versión del AssemblyScript a la v0.19.10 (esta incluye cambios importantes, recomendamos leer la [`guía de migración`](/release-notes/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` actualizada a `ethereum.transaction.gasLimit` | -| 0.0.4 | Añadido la casilla de `functionSignature` para la función de Ethereum SmartContractCall | -| 0.0.3 | Añadida la casilla `from` para la función de Ethereum Call
`ethereum.call.address` actualizada a `ethereum.call.to` | -| 0.0.2 | Añadida la casilla de `input` para la función de Ethereum Transaction | +| 0.0.7 | Agregado de clases `TransactionReceipt` y `Log` a los tipos de Ethereum
Agregado el campo `receipt` al objeto Ethereum Event | +| 0.0.6 | Agregado el campo `nonce` al objeto Ethereum Transaction
Agregado `baseFeePerGas` al objeto Ethereum Block | +| 0.0.5 | AssemblyScript actualizado a la versión 0.19.10 (esto incluye cambios importantes, consulte la [`Migration Guide`](/release-notes/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renombrado a `ethereum.transaction.gasLimit` | +| 0.0.4 | Agregado el campo `functionSignature` al objeto Ethereum SmartContractCall | +| 0.0.3 | Agregado el campo `from` al objeto Ethereum Call
`etherem.call.address` renombrado `ethereum.call.to` | +| 0.0.2 | Agregado el campo `input` al objeto Ethereum Transaction | -### Built-in Types +### Tipos Incorporados La documentación sobre las actualizaciones integradas en AssemblyScript puedes encontrarla en la [wiki de AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki/Types). -Las siguientes integraciones son proporcionada por `@graphprotocol/graph-ts`. +Las siguientes integraciones son proporcionadas por `@graphprotocol/graph-ts`. #### ByteArray @@ -67,22 +68,22 @@ import { ByteArray } from '@graphprotocol/graph-ts' _Construcción_ -- `fromI32(x: i32): ByteArray` - Descompuesta en `x` bytes. -- `fromHexString(hex: string): ByteArray` - La longitud de la entrada debe ser uniforme. Prefijo `0x` es opcional. +- `fromI32(x: i32): ByteArray` - Descompone `x` en bytes. +- `fromHexString(hex: string): ByteArray` - La longitud de la entrada debe ser uniforme. El prefijo con `0x` es opcional. _Tipo de conversiones_ -- `toHexString(): string` - Convierte un prefijo hexadecimal iniciado con `0x`. -- `toString(): string` - Interpreta los bytes en una cadena UTF-8. +- `toHexString(): string` - Se convierte en una cadena hexadecimal con el prefijo `0x`. +- `toString(): string` - Interpreta los bytes como una cadena UTF-8. - `toBase58(): string` - Codifica los bytes en una cadena base58. -- `toU32(): u32` - Interpeta los bytes en base a little-endian `u32`. Se ejecuta en casos de un overflow. -- `toI32(): i32` - Interpreta los bytes en base a little-endian `i32`. Se ejecuta en casos de un overflow. +- `toU32(): u32` - Interpeta los bytes como una little-endian `u32`. Se ejecuta en casos de un overflow. +- `toI32(): i32` - Interpreta la matriz de bytes como `i32` little-endian. Se ejecuta en casos de un overflow. _Operadores_ - `equals(y: ByteArray): bool` – se puede escribir como `x == y`. -- `concat(other: ByteArray) : ByteArray` - return a new `ByteArray` consisting of `this` directly followed by `other` -- `concatI32(other: i32) : ByteArray` - return a new `ByteArray` consisting of `this` directly follow by the byte representation of `other` +- `concat(other: ByteArray) : ByteArray` - regresa un nuevo `ByteArray` que consiste en `this` directamente seguido por `other` +- `concatI32(other: i32) : ByteArray` - devuelve un nuevo `ByteArray` que consta de `this` seguido directamente de la representación de bytes de `other` #### BigDecimal @@ -92,14 +93,16 @@ import { BigDecimal } from '@graphprotocol/graph-ts' `BigDecimal` se usa para representar una precisión decimal arbitraria. +> Nota: [Internally](https://github.com/graphprotocol/graph-node/blob/master/graph/src/data/store/scalar.rs) `BigDecimal` es almacenado en [IEEE-754 decimal128 floating-point format](https://en.wikipedia.org/wiki/Decimal128_floating-point_format), que admite 34 dígitos decimales de significante. Esto hace que `BigDecimal` sea inadecuado para representar tipos de punto fijo que pueden abarcar más de 34 dígitos, como un Solidity [`ufixed256x18`](https://docs.soliditylang.org/en/latest/types.html#fixed-point-numbers) o equivalente. + _Construcción_ -- `constructor(bigInt: BigInt)` – creará un `BigDecimal` en base a un`BigInt`. -- `static fromString(s: string): BigDecimal` – analizará una cadena de decimales. +- `constructor(bigInt: BigInt)` – creará un `BigDecimal` en base a un `BigInt`. +- `static fromString(s: string): BigDecimal` – analiza una cadena de decimales. -_Tipo de conversiones_ +_Conversiones de tipo_ -- `toString(): string` – colocará una cadena de decimales. +- `toString(): string` – imprime en una cadena decimal. _Matemática_ @@ -121,22 +124,22 @@ _Matemática_ import { BigInt } from '@graphprotocol/graph-ts' ``` -`BigInt` es usado para representar nuevos enteros grandes. Esto incluye valores de Ethereum similares a `uint32` hacia `uint256` y `int64` hacia `int256`. Todo por debajo de `uint32`. como el `int32`, `uint24` o `int8` se representa como `i32`. +`BigInt` es usado para representar números enteros grandes. Esto incluye valores de Ethereum de tipo `uint32` hasta `uint256` y `int64` hasta `int256`. Todo por debajo de `uint32`. como el `int32`, `uint24` o `int8` se representa como `i32`. La clase `BigInt` tiene la siguiente API: _Construcción_ - `BigInt.fromI32(x: i32): BigInt` – creará un `BigInt` en base a un `i32`. -- `BigInt.fromString(s: string): BigInt`– Analizará un `BigInt` dentro de una cadena. -- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interpretará `bytes` sin firmar, o un little-endian entero. Si tu entrada es big-endian, deberás llamar primero el código `.reverse()`. -- `BigInt.fromSignedBytes(x: Bytes): BigInt` – interpretará los `bytes` como una firma, en un little-endian entero. Si tu entrada es big-endian, deberás llamar primero el código `.reverse()`. +- `BigInt.fromString(s: string): BigInt`– Analiza un `BigInt` desde una cadena. +- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interpreta `bytes` como un número entero little-endian sin firma. Si su entrada es big-endian, llame primero a `.reverse()`. +- `BigInt.fromSignedBytes(x: Bytes): BigInt` – Interpreta `bytes` como un número entero little-endian con firma. Si su entrada es big-endian, llame primero a `.reverse()`. _Tipo de conversiones_ -- `x.toHex(): string` - se transforma `BigInt` en un string de caracteres hexadecimales. -- `x.toString(): string` – se transforma `BigInt` en un string de numero decimal. -- `x.toI32(): i32` – retorna el `BigInt` como una `i32`; falla si el valor no encaja en `i32`. Es una buena idea comprobar primero `x.isI32()`. +- `x.toHex(): string` - transforma `BigInt` en una cadena de caracteres hexadecimales. +- `x.toString(): string` – transforma `BigInt` en una cadena de números decimales. +- `x.toI32(): i32`: devuelve `BigInt` como `i32`; falla si el valor no encaja en `i32`. Es una buena idea verificar primero `x.isI32()`. - `x.toBigDecimal(): BigDecimal` - se convierte en un decimal sin parte fraccionaria. _Matemática_ @@ -169,14 +172,14 @@ _Matemática_ import { TypedMap } from '@graphprotocol/graph-ts' ``` -`TypedMap` puede utilizarse para almacenar pares clave-valor. Mira [este ejemplo](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). +`TypedMap` se puede utilizar para almacenar pares key-value. Ver [este ejemplo](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). La `TypedMap` clase tiene la siguiente API: - `new TypedMap()` – crea un mapa vacio con claves del tipo `K` y valores del tipo `T` - `map.set(key: K, value: V): void` – establece el valor del `key` a `value` -- `map.getEntry(key: K): TypedMapEntry | null` – devuelve el par clave-valor de un `key` o `null` si el `key` no existe en el mapa -- `map.get(key: K): V | null` – returna el valor de una `key` o `null` si el `key` no existen en el mapa +- `map.getEntry(key: K): TypedMapEntry | null` – devuelve el par key-value de un `key` o `null` si el `key` no existe en el mapa +- `map.get(key: K): V | null` – returna el valor de una `key` o `null` si el `key` no existe en el mapa - `map.isSet(key: K): bool` – returna `true` si el `key` existe en el mapa y `false` no es asi #### Bytes @@ -185,25 +188,25 @@ La `TypedMap` clase tiene la siguiente API: import { Bytes } from '@graphprotocol/graph-ts' ``` -`Bytes` se utiliza para representar matrices de bytes de longitud arbitraria. Esto incluye los valores de Ethereum de tipo `bytes`, `bytes32` etc. +`Bytes` se utiliza para representar matrices de bytes de longitud arbitraria. Esto incluye valores de Ethereum de tipo `bytes`, `bytes32`, etc. -La clase `Bytes` extiende AssemblyScript's [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) y esto soporta todas las `Uint8Array` funcionalidades, mas los siguientes nuevos metodos: +La clase `Bytes` extiende [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) de AssemblyScript y esto soporta todas las funcionalidades de `Uint8Array`, mas los siguientes nuevos métodos: _Construcción_ -- `fromHexString(hex: string) : Bytes` - Convert the string `hex` which must consist of an even number of hexadecimal digits to a `ByteArray`. The string `hex` can optionally start with `0x` -- `fromI32(i: i32) : Bytes` - Convert `i` to an array of bytes +- `fromHexString(hex: string) : Bytes` - Convierte el string `hex` que debe consistir en un número par de dígitos hexadecimales a un `ByteArray`. El string `hex` puede opcionalmente comenzar con `0x` +- `fromI32(i: i32) : Bytes` - Convierte `i` en un matriz de bytes _Tipo de conversiones_ -- `b.toHex()` – returns a hexadecimal string representing the bytes in the array -- `b.toString()` – converts the bytes in the array to a string of unicode characters -- `b.toBase58()` – turns an Ethereum Bytes value to base58 encoding (used for IPFS hashes) +- `b.toHex()` – devuelve una cadena hexadecimal que representa los bytes en la matriz +- `b.toString()` – convierte los bytes en la matriz a una cadena de caracteres unicode +- `b.toBase58()` – convierte un valor Ethereum Bytes en codificacion base58 (usada para los hashes IPFS) _Operadores_ -- `b.concat(other: Bytes) : Bytes` - - return new `Bytes` consisting of `this` directly followed by `other` -- `b.concatI32(other: i32) : ByteArray` - return new `Bytes` consisting of `this` directly follow by the byte representation of `other` +- `b.concat(other: Bytes) : Bytes` - - retorna nuevo `Bytes` consistente en `this` directamente seguido por `other` +- `b.concatI32(other: i32) : ByteArray` - retorna un nuevo `Bytes` que consistente de `this` seguido directamente de la representacion byte de `other` #### Dirección @@ -211,12 +214,12 @@ _Operadores_ import { Address } from '@graphprotocol/graph-ts' ``` -`Address` extends `Bytes` to represent Ethereum `address` values. +`Address` extiende `Bytes` para representar valores de Ethereum `address`. -It adds the following method on top of the `Bytes` API: +Añade el siguiente método sobre la API `Bytes`: -- `Address.fromString(s: string): Address` – creates an `Address` from a hexadecimal string -- `Address.fromBytes(b: Bytes): Address` – create an `Address` from `b` which must be exactly 20 bytes long. Passing in a value with fewer or more bytes will result in an error +- `Address.fromString(s: string): Address` – crea una `Address` desde una cadena hexadecimal +- `Address.fromBytes(b: Bytes): Address` – crea un `Address` desde `b` que debe tener exactamente 20 bytes de longitud. Pasar un valor con menos o mas bytes resultará en un error ### Almacén de API @@ -224,13 +227,13 @@ It adds the following method on top of the `Bytes` API: import { store } from '@graphprotocol/graph-ts' ``` -The `store` API allows to load, save and remove entities from and to the Graph Node store. +La API `store` permite cargar, guardar y eliminar entidades desde y hacia el almacén de Graph Node. -Entities written to the store map one-to-one to the `@entity` types defined in the subgraph's GraphQL schema. To make working with these entities convenient, the `graph codegen` command provided by the [Graph CLI](https://github.com/graphprotocol/graph-cli) generates entity classes, which are subclasses of the built-in `Entity` type, with property getters and setters for the fields in the schema as well as methods to load and save these entities. +Las entidades escritas en el store asignan uno a uno a los tipos `@entity` definidos en el esquema GraphQL del subgrafo. Para facilitar el trabajo con estas entidades, el comando `graph codegen` proporcionado por [Graph CLI](https://github.com/graphprotocol/graph-cli) genera las clases de entidades, que son subclases de `Entity` de tipo integrado, con captadores y definidores de propiedades para los campos en el esquema, así como métodos para cargar y guardar estas entidades. #### Creacion de entidades -The following is a common pattern for creating entities from Ethereum events. +El siguiente es un patrón común para crear entidades a partir de eventos de Ethereum. ```typescript // Import the Transfer event class generated from the ERC20 ABI @@ -255,13 +258,13 @@ export function handleTransfer(event: TransferEvent): void { } ``` -When a `Transfer` event is encountered while processing the chain, it is passed to the `handleTransfer` event handler using the generated `Transfer` type (aliased to `TransferEvent` here to avoid a naming conflict with the entity type). This type allows accessing data such as the event's parent transaction and its parameters. +Cuando se encuentra un evento `Transfer` mientras se procesa la cadena, se pasa al handler de eventos `handleTransfer` utilizando el tipo generado `Transfer` (con el alias de `TransferEvent` aquí para evitar un conflicto de nombres con el tipo de entidad). Este tipo permite acceder a datos como la transacción padre del evento y sus parámetros. -Each entity must have a unique ID to avoid collisions with other entities. It is fairly common for event parameters to include a unique identifier that can be used. Note: Using the transaction hash as the ID assumes that no other events in the same transaction create entities with this hash as the ID. +Cada entidad debe tener un identificador único para evitar colisiones con otras entidades. Es bastante común que los parámetros de los eventos incluyan un identificador único que pueda ser utilizado. Nota: El uso del hash de la transacción como ID asume que ningún otro evento en la misma transacción crea entidades con este hash como ID. -#### Carga de entidades desde el almacén +#### Carga de entidades desde el store -If an entity already exists, it can be loaded from the store with the following: +Si una entidad ya existe, se puede cargar desde el store con lo siguiente: ```typescript let id = event.transaction.hash // or however the ID is constructed @@ -273,18 +276,18 @@ if (transfer == null) { // Use the Transfer entity as before ``` -As the entity may not exist in the store yet, the `load` method returns a value of type `Transfer | null`. It may thus be necessary to check for the `null` case before using the value. +Como la entidad puede no existir todavía en el almacén, el método `load` devuelve un valor de tipo `Transfer | null`. Por lo tanto, puede ser necesario comprobar el caso `null` antes de utilizar el valor. -> **Nota:** La carga de entidades sólo es necesaria si los cambios realizados en la asignación dependen de los datos anteriores de una entidad. Mira en la siguiente sección las dos formas de actualizar las entidades existentes. +> **Nota:** La carga de entidades sólo es necesaria si los cambios realizados en el mapeo dependen de los datos anteriores de una entidad. Consulta en la siguiente sección las dos formas de actualizar las entidades existentes. #### Actualización de las entidades existentes -There are two ways to update an existing entity: +Hay dos maneras de actualizar una entidad existente: -1. Cargar la entidad con, por ejemplo `Transfer.load(id)`, establecer propiedades en la entidad, entonces `.save()` de nuevo en el almacen. -2. Simplemente crear una entidad con, por ejemplo `new Transfer(id)`, establecer las propiedades en la entidad, luego `.save()` en el almacen. Si la entidad ya existe, los cambios se fusionan con ella. +1. Cargar la entidad con, por ejemplo `Transfer.load(id)`, establecer propiedades en la entidad, entonces `.save()` de nuevo en el store. +2. Simplemente crear una entidad con, por ejemplo `new Transfer(id)`, establecer las propiedades en la entidad, luego `.save()` en el store. Si la entidad ya existe, los cambios se fusionan con ella. -Changing properties is straight forward in most cases, thanks to the generated property setters: +Cambiar las propiedades es sencillo en la mayoría de los casos, gracias a los definidores de propiedades generados: ```typescript let transfer = new Transfer(id) @@ -293,32 +296,32 @@ transfer.to = ... transfer.amount = ... ``` -It is also possible to unset properties with one of the following two instructions: +También es posible desajustar las propiedades con una de las dos instrucciones siguientes: ```typescript transfer.from.unset() transfer.from = null ``` -This only works with optional properties, i.e. properties that are declared without a `!` in GraphQL. Two examples would be `owner: Bytes` or `amount: BigInt`. +Esto sólo funciona con propiedades opcionales, es decir, propiedades que se declaran sin un `!` en GraphQL. Dos ejemplos serían `owner: Bytes` o `amount: BigInt`. -Updating array properties is a little more involved, as the getting an array from an entity creates a copy of that array. This means array properties have to be set again explicitly after changing the array. The following assumes `entity` has a `numbers: [BigInt!]!` field. +La actualización de las propiedades de la matriz es un poco más complicada, ya que al obtener una matriz de una entidad se crea una copia de esa matriz. Esto significa que las propiedades de la matriz tienen que ser establecidas de nuevo explícitamente después de cambiar la matriz. Lo siguiente supone que la `entity` tiene un campo `numbers: [BigInt!]!`. ```typescript -// Esto no funciona +// This won't work entity.numbers.push(BigInt.fromI32(1)) entity.save() -// Este si funciona +// This will work let numbers = entity.numbers numbers.push(BigInt.fromI32(1)) entity.numbers = numbers entity.save() ``` -#### Eliminar entidades del almacen +#### Eliminar entidades del store -There is currently no way to remove an entity via the generated types. Instead, removing an entity requires passing the name of the entity type and the entity ID to `store.remove`: +Actualmente no hay forma de eliminar una entidad a través de los tipos generados. En su lugar, la eliminación de una entidad requiere pasar el nombre del tipo de entidad y el ID de la entidad a `store.remove`: ```typescript import { store } from '@graphprotocol/graph-ts' @@ -329,15 +332,15 @@ store.remove('Transfer', id) ### API de Ethereum -The Ethereum API provides access to smart contracts, public state variables, contract functions, events, transactions, blocks and the encoding/decoding Ethereum data. +La API de Ethereum proporciona acceso a los contratos inteligentes, a las variables de estado públicas, a las funciones de los contratos, a los eventos, a las transacciones, a los bloques y a la codificación/decodificación de los datos de Ethereum. #### Compatibilidad con los tipos de Ethereum -As with entities, `graph codegen` generates classes for all smart contracts and events used in a subgraph. For this, the contract ABIs need to be part of the data source in the subgraph manifest. Typically, the ABI files are stored in an `abis/` folder. +Al igual que con las entidades, `graph codegen` genera clases para todos los contratos inteligentes y eventos utilizados en un subgrafo. Para ello, las ABIs de los contratos deben formar parte de la fuente de datos en el manifiesto del subgrafo. Normalmente, los archivos ABI se almacenan en una carpeta `abis/`. -With the generated classes, conversions between Ethereum types and the [built-in types](#built-in-types) take place behind the scenes so that subgraph authors do not have to worry about them. +Con las clases generadas, las conversiones entre los tipos de Ethereum y los tipos [built-in types](#built-in-types) tienen lugar detras de escena para que los autores de los subgrafos no tengan que preocuparse por ellos. -The following example illustrates this. Given a subgraph schema like +El siguiente ejemplo lo ilustra. Dado un esquema de subgrafos como ```graphql type Transfer @entity { @@ -348,7 +351,7 @@ type Transfer @entity { } ``` -and a `Transfer(address,address,uint256)` event signature on Ethereum, the `from`, `to` and `amount` values of type `address`, `address` and `uint256` are converted to `Address` and `BigInt`, allowing them to be passed on to the `Bytes!` and `BigInt!` properties of the `Transfer` entity: +y un evento de firma `Transfer(address,address,uint256)` en Ethereum, el `from`, `to` y `amount` valores del tipo `address`, `address` y `uint256` se convierten a `Address` y `BigInt`, lo que permite pasarlos a las propiedades `Bytes!` y `BigInt!` de la entidad `Transfer`: ```typescript let id = event.transaction.hash @@ -361,7 +364,7 @@ transfer.save() #### Eventos y datos de bloques/transacciones -Ethereum events passed to event handlers, such as the `Transfer` event in the previous examples, not only provide access to the event parameters but also to their parent transaction and the block they are part of. The following data can be obtained from `event` instances (these classes are a part of the `ethereum` module in `graph-ts`): +Los eventos de Ethereum pasados a los handlers de eventos, como el evento `Transfer` de los ejemplos anteriores, no sólo proporcionan acceso a los parámetros del evento, sino también a su transacción padre y al bloque del que forman parte. Los siguientes datos pueden obtenerse de las instancias de `event` (estas clases forman parte del módulo `ethereum` en `graph-ts`): ```typescript class Event { @@ -372,6 +375,7 @@ class Event { block: Block transaction: Transaction parameters: Array + receipt: TransactionReceipt | null } class Block { @@ -403,36 +407,66 @@ class Transaction { input: Bytes nonce: BigInt } + +class TransactionReceipt { + transactionHash: Bytes + transactionIndex: BigInt + blockHash: Bytes + blockNumber: BigInt + cumulativeGasUsed: BigInt + gasUsed: BigInt + contractAddress: Address + logs: Array + status: BigInt + root: Bytes + logsBloom: Bytes +} + +class Log { + address: Address + topics: Array + data: Bytes + blockHash: Bytes + blockNumber: Bytes + transactionHash: Bytes + transactionIndex: BigInt + logIndex: BigInt + transactionLogIndex: BigInt + logType: string + removed: bool | null +} ``` #### Acceso al Estado del Contrato Inteligente -The code generated by `graph codegen` also includes classes for the smart contracts used in the subgraph. These can be used to access public state variables and call functions of the contract at the current block. +El código generado por `graph codegen` también incluye clases para los contratos inteligentes utilizados en el subgrafo. Estas se pueden utilizar para acceder a las variables de estado públicas y llamar a las funciones del contrato en el bloque actual. -A common pattern is to access the contract from which an event originates. This is achieved with the following code: +Un patrón común es acceder al contrato desde el que se origina un evento. Esto se consigue con el siguiente código: ```typescript -// Importar la clase del contrato generado -import { ERC20Contract } from '../generated/ERC20Contract/ERC20Contract' -// Importar la clase de entidad generada +// Import the generated contract class and generated Transfer event class +import { ERC20Contract, Transfer as TransferEvent } from '../generated/ERC20Contract/ERC20Contract' +// Import the generated entity class import { Transfer } from '../generated/schema' -export function handleTransfer(event: Transfer) { - // Vincular la dirección del contrato emitido por el evento +export function handleTransfer(event: TransferEvent) { + // Bind the contract to the address that emitted the event let contract = ERC20Contract.bind(event.address) - // Acceder a las variables y funciones mediante las llamadas + // Access state variables and functions by calling them let erc20Symbol = contract.symbol() } ``` -As long as the `ERC20Contract` on Ethereum has a public read-only function called `symbol`, it can be called with `.symbol()`. For public state variables a method with the same name is created automatically. +`Transfer` tiene un alias de `TransferEvent` aquí para evitar un conflicto de nombres con el tipo de entidad + +Siempre que el `ERC20Contract` de Ethereum tenga una función pública de sólo lectura llamada `symbol`, se puede llamar con `.symbol()`. Para las variables de estado públicas se crea automáticamente un método con el mismo nombre. -Any other contract that is part of the subgraph can be imported from the generated code and can be bound to a valid address. +Cualquier otro contrato que forme parte del subgrafo puede ser importado desde el código generado y puede ser vinculado a una dirección válida. -#### Tratamiento de las llamadas revertidas +#### Tratamiento de las Llamadas Revertidas -If the read-only methods of your contract may revert, then you should handle that by calling the generated contract method prefixed with `try_`. For example, the Gravity contract exposes the `gravatarToOwner` method. This code would be able to handle a revert in that method: +Si los métodos de sólo lectura de tu contrato pueden revertirse, entonces debes manejar eso llamando al método del contrato generado prefijado con `try_`. Por ejemplo, el contrato Gravity expone el método `gravatarToOwner`. Este código sería capaz de manejar una reversión en ese método: ```typescript let gravity = Gravity.bind(event.address) @@ -444,11 +478,11 @@ if (callResult.reverted) { } ``` -Note that a Graph node connected to a Geth or Infura client may not detect all reverts, if you rely on this we recommend using a Graph node connected to a Parity client. +Ten en cuenta que un nodo Graph conectado a un cliente Geth o Infura puede no detectar todas las reversiones, si confías en esto te recomendamos que utilices un nodo Graph conectado a un cliente Parity. #### Codificación/Descodificación ABI -Data can be encoded and decoded according to Ethereum's ABI encoding format using the `encode` and `decode` functions in the `ethereum` module. +Los datos pueden ser codificados y decodificados según el formato de codificación ABI de Ethereum utilizando las funciones `encode` y `decode` del módulo `ethereum`. ```typescript import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts' @@ -465,11 +499,11 @@ let encoded = ethereum.encode(ethereum.Value.fromTuple(tuple))! let decoded = ethereum.decode('(address,uint256)', encoded) ``` -For more information: +Para mas informacion: - [ABI Spec](https://docs.soliditylang.org/en/v0.7.4/abi-spec.html#types) -- Encoding/decoding [Rust library/CLI](https://github.com/rust-ethereum/ethabi) -- More [complex example](https://github.com/graphprotocol/graph-node/blob/6a7806cc465949ebb9e5b8269eeb763857797efc/tests/integration-tests/host-exports/src/mapping.ts#L72). +- Codificación/descodificación [Librería Rust/CLI](https://github.com/rust-ethereum/ethabi) +- Un ejemplo más [complejo](https://github.com/graphprotocol/graph-node/blob/6a7806cc465949ebb9e5b8269eeb763857797efc/tests/integration-tests/host-exports/src/mapping.ts#L72). ### API de Registro @@ -477,17 +511,17 @@ For more information: import { log } from '@graphprotocol/graph-ts' ``` -The `log` API allows subgraphs to log information to the Graph Node standard output as well as the Graph Explorer. Messages can be logged using different log levels. A basic format string syntax is provided to compose log messages from argument. +La API `log` permite a los subgrafos registrar información en la salida estándar del Nodo Graph así como en Graph Explorer. Los mensajes pueden ser registrados usando diferentes niveles de registro. Se proporciona una sintaxis de cadena de formato básico para redactar mensajes de registro a partir del argumento. -The `log` API includes the following functions: +La API `log` incluye las siguientes funciones: -- `log.debug(fmt: string, args: Array): void` - logs a debug message. -- `log.info(fmt: string, args: Array): void` - logs an informational message. -- `log.warning(fmt: string, args: Array): void` - logs a warning. -- `log.error(fmt: string, args: Array): void` - logs an error message. -- `log.critical(fmt: string, args: Array): void` – logs a critical message _and_ terminates the subgraph. +- `log.debug(fmt: string, args: Array): void` - registra un mensaje de depuración. +- `log.debug(fmt: string, args: Array): void` - registra un mensaje informativo. +- `log.warning(fmt: string, args: Array): void` - registra una advertencia. +- `log.error(fmt: string, args: Array): void` - registra un mensaje de error. +- `log.critical(fmt: string, args: Array): void` – registra un mensaje crítico _y_ termina el subgrafo. -The `log` API takes a format string and an array of string values. It then replaces placeholders with the string values from the array. The first `{}` placeholder gets replaced by the first value in the array, the second `{}` placeholder gets replaced by the second value and so on. +La API `log` toma una cadena de formato y una matriz de valores de cadena. Luego reemplaza los marcadores de posición con los valores de cadena de la matriz. El primer marcador de posición `{}` se reemplaza por el primer valor de la matriz, el segundo marcador de posición `{}` se reemplaza por el segundo valor y así sucesivamente. ```typescript log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue.toString(), 'already a string']) @@ -495,9 +529,9 @@ log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue. #### Registro de uno o varios valores -##### Registro de un valor +##### Registro de un solo valor -In the example below, the string value "A" is passed into an array to become`['A']` before being logged: +En el ejemplo siguiente, el valor del string "A" se pasa a un array para convertirse en`['A']` antes de ser registrado: ```typescript let myValue = 'A' @@ -510,7 +544,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### Registro de una sola entrada de una matriz existente -In the example below, only the first value of the argument array is logged, despite the array containing three values. +En el ejemplo siguiente, sólo se registra el primer valor de la matriz de argumentos, a pesar de que la matriz contiene tres valores. ```typescript let myArray = ['A', 'B', 'C'] @@ -523,7 +557,7 @@ export function handleSomeEvent(event: SomeEvent): void { #### Registro de múltiples entradas de una matriz existente -Each entry in the arguments array requires its own placeholder `{}` in the log message string. The below example contains three placeholders `{}` in the log message. Because of this, all three values in `myArray` are logged. +Cada entrada del array de argumentos requiere su propio marcador de posición `{}` en el string del mensaje de registro. El siguiente ejemplo contiene tres marcadores de posición `{}` en el mensaje de registro. Debido a esto, los tres valores en `myArray` se registran. ```typescript let myArray = ['A', 'B', 'C'] @@ -536,7 +570,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### Registro de una entrada específica de una matriz existente -To display a specific value in the array, the indexed value must be provided. +Para mostrar un valor específico en el array, se debe proporcionar el valor indexado. ```typescript export function handleSomeEvent(event: SomeEvent): void { @@ -547,7 +581,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### Registro de información de eventos -The example below logs the block number, block hash and transaction hash from an event: +El ejemplo siguiente registra el número de bloque, el hash del bloque y el hash de la transacción de un evento: ```typescript import { log } from '@graphprotocol/graph-ts' @@ -567,9 +601,9 @@ export function handleSomeEvent(event: SomeEvent): void { import { ipfs } from '@graphprotocol/graph-ts' ``` -Smart contracts occasionally anchor IPFS files on chain. This allows mappings to obtain the IPFS hashes from the contract and read the corresponding files from IPFS. The file data will be returned as `Bytes`, which usually requires further processing, e.g. with the `json` API documented later on this page. +Los contratos inteligentes anclan ocasionalmente archivos IPFS en la cadena. Esto permite a los mapeos obtener los hashes de IPFS del contrato y leer los archivos correspondientes de IPFS. Los datos de los archivos se devolverán como `Bytes`, lo que normalmente requiere un procesamiento posterior, por ejemplo, con la API `json` documentada más adelante en esta página. -Given an IPFS hash or path, reading a file from IPFS is done as follows: +Dado un hash o ruta de IPFS, la lectura de un archivo desde IPFS se realiza de la siguiente manera: ```typescript // Colocar esto dentro del gestor de eventos del mapeo @@ -582,9 +616,9 @@ let path = 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile' let data = ipfs.cat(path) ``` -**Note:** `ipfs.cat` is not deterministic at the moment. If the file cannot be retrieved over the IPFS network before the request times out, it will return `null`. Due to this, it's always worth checking the result for `null`. To ensure that files can be retrieved, they have to be pinned to the IPFS node that Graph Node connects to. On the [hosted service](https://thegraph.com/hosted-service), this is [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs). See the [IPFS pinning](/developing/creating-a-subgraph#ipfs-pinning) section for more information. +**Nota:** `ipfs.cat` no es determinístico por el momento. Si el archivo no puede ser recuperado a través de la red IPFS antes de que se agote el tiempo de espera de la solicitud, devolverá `null`. Debido a esto, siempre vale la pena comprobar el resultado de `null`. -It is also possible to process larger files in a streaming fashion with `ipfs.map`. The function expects the hash or path for an IPFS file, the name of a callback, and flags to modify its behavior: +También es posible procesar archivos de mayor tamaño en forma de flujo con `ipfs.map`. La función espera el hash o la ruta de un archivo IPFS, el nombre de una callback y banderas para modificar su comportamiento: ```typescript import { JSONValue, Value } from '@graphprotocol/graph-ts' @@ -614,9 +648,9 @@ ipfs.map('Qm...', 'processItem', Value.fromString('parentId'), ['json']) ipfs.mapJSON('Qm...', 'processItem', Value.fromString('parentId')) ``` -The only flag currently supported is `json`, which must be passed to `ipfs.map`. With the `json` flag, the IPFS file must consist of a series of JSON values, one value per line. The call to `ipfs.map` will read each line in the file, deserialize it into a `JSONValue` and call the callback for each of them. The callback can then use entity operations to store data from the `JSONValue`. Entity changes are stored only when the handler that called `ipfs.map` finishes successfully; in the meantime, they are kept in memory, and the size of the file that `ipfs.map` can process is therefore limited. +La única bandera actualmente soportada es `json`, que debe ser pasada a `ipfs.map`. Con la bandera `json`, el archivo IPFS debe consistir en una serie de valores JSON, un valor por línea. La llamada a `ipfs.map` leerá cada línea del archivo, la deserializará en un `JSONValue` y llamará a la callback para cada una de ellas. La callback puede entonces utilizar operaciones de entidad para almacenar los datos del `JSONValue`. Los cambios de entidad se almacenan sólo cuando el handler que llamó a `ipfs.map` termina con éxito; mientras tanto, se mantienen en memoria, y el tamaño del archivo que `ipfs.map` puede procesar es, por tanto, limitado. -On success, `ipfs.map` returns `void`. If any invocation of the callback causes an error, the handler that invoked `ipfs.map` is aborted, and the subgraph is marked as failed. +En caso de éxito, `ipfs.map` devuelve `void`. Si alguna invocación de la callback causa un error, el handler que invocó `ipfs.map` es abortado, y el subgrafo es marcado como fallido. ### API Cripto @@ -624,7 +658,7 @@ On success, `ipfs.map` returns `void`. If any invocation of the callback causes import { crypto } from '@graphprotocol/graph-ts' ``` -The `crypto` API makes a cryptographic functions available for use in mappings. Right now, there is only one: +La API `crypto` pone a disposición una serie de funciones criptográficas para su uso en los mapeos. En este momento, sólo hay una: - `crypto.keccak256(input: ByteArray): ByteArray` @@ -634,14 +668,14 @@ The `crypto` API makes a cryptographic functions available for use in mappings. import { json, JSONValueKind } from '@graphprotocol/graph-ts' ``` -JSON data can be parsed using the `json` API: +Los datos JSON pueden ser analizados utilizando la API `json`: -- `json.fromBytes(data: Bytes): JSONValue` – parses JSON data from a `Bytes` array interpreted as a valid UTF-8 sequence -- `json.try_fromBytes(data: Bytes): Result` – safe version of `json.fromBytes`, it returns an error variant if the parsing failed -- `json.fromString(data: string): JSONValue` – parses JSON data from a valid UTF-8 `String` -- `json.try_fromString(data: string): Result` – safe version of `json.fromString`, it returns an error variant if the parsing failed +- `json.fromBytes(data: Bytes): JSONValue` - analiza los datos JSON a partir de una matriz `Bytes` interpretada como una secuencia UTF-8 válida +- `json.try_fromBytes(data: Bytes): Result` - versión segura de `json.fromBytes`, devuelve una variante de error si el análisis sintáctico falló +- `json.fromString(data: string): JSONValue` - analiza los datos JSON a partir de una `String` válida en UTF-8 +- `json.try_fromString(data: string): Result` - versión segura de `json.fromString`, devuelve una variante de error si el análisis sintáctico falló -The `JSONValue` class provides a way to pull values out of an arbitrary JSON document. Since JSON values can be booleans, numbers, arrays and more, `JSONValue` comes with a `kind` property to check the type of a value: +La clase `JSONValue` proporciona una forma de extraer valores de un documento JSON arbitrario. Como los valores JSON pueden ser booleans, números, matrices y más, `JSONValue` viene con una propiedad `kind` para comprobar el tipo de un valor: ```typescript let value = json.fromBytes(...) @@ -650,54 +684,55 @@ if (value.kind == JSONValueKind.BOOL) { } ``` -In addition, there is a method to check if the value is `null`: +Además, existe un método para comprobar si el valor es `null`: - `value.isNull(): boolean` -When the type of a value is certain, it can be converted to a [built-in type](#built-in-types) using one of the following methods: +Cuando el tipo de un valor es cierto, se puede convertir a un [built-in type](#built-in-types) utilizando uno de los siguientes métodos: - `value.toBool(): boolean` - `value.toI64(): i64` - `value.toF64(): f64` - `value.toBigInt(): BigInt` - `value.toString(): string` -- `value.toArray(): Array` - (and then convert `JSONValue` with one of the 5 methods above) +- `value.toArray(): Array` - (y luego convertir `JSONValue` con uno de los 5 métodos anteriores) ### Referencias de Tipo de Conversiones | Origen(es) | Destino | Funcion de Conversion | | -------------------- | -------------------- | ---------------------------- | -| Dirección | Bytes | none | +| Dirección | Bytes | ninguno | | Dirección | String | s.toHexString() | | BigDecimal | String | s.toString() | | BigInt | BigDecimal | s.toBigDecimal() | | BigInt | String (hexadecimal) | s.toHexString() or s.toHex() | | BigInt | String (unicode) | s.toString() | | BigInt | i32 | s.toI32() | -| Boolean | Boolean | none | -| Bytes (signed) | BigInt | BigInt.fromSignedBytes(s) | -| Bytes (unsigned) | BigInt | BigInt.fromUnsignedBytes(s) | +| Boolean | Boolean | ninguno | +| Bytes (firmado) | BigInt | BigInt.fromSignedBytes(s) | +| Bytes (sin firma) | BigInt | BigInt.fromUnsignedBytes(s) | | Bytes | String (hexadecimal) | s.toHexString() or s.toHex() | | Bytes | String (unicode) | s.toString() | | Bytes | String (base58) | s.toBase58() | | Bytes | i32 | s.toI32() | | Bytes | u32 | s.toU32() | | Bytes | JSON | json.fromBytes(s) | -| int8 | i32 | none | -| int32 | i32 | none | +| int8 | i32 | ninguno | +| int32 | i32 | ninguno | | int32 | BigInt | BigInt.fromI32(s) | -| uint24 | i32 | none | -| int64 - int256 | BigInt | none | -| uint32 - uint256 | BigInt | none | +| uint24 | i32 | ninguno | +| int64 - int256 | BigInt | ninguno | +| uint32 - uint256 | BigInt | ninguno | | JSON | boolean | s.toBool() | | JSON | i64 | s.toI64() | | JSON | u64 | s.toU64() | | JSON | f64 | s.toF64() | | JSON | BigInt | s.toBigInt() | | JSON | string | s.toString() | -| JSON | Array | s.toArray() | +| JSON | Matriz | s.toArray() | | JSON | Object | s.toObject() | | String | Dirección | Address.fromString(s) | +| Bytes | Dirección | Address.fromBytes(s) | | String | BigInt | BigInt.fromString(s) | | String | BigDecimal | BigDecimal.fromString(s) | | String (hexadecimal) | Bytes | ByteArray.fromHexString(s) | @@ -705,7 +740,7 @@ When the type of a value is certain, it can be converted to a [built-in type](#b ### Metadatos de la Fuente de Datos -You can inspect the contract address, network and context of the data source that invoked the handler through the `dataSource` namespace: +Puedes inspeccionar la dirección del contrato, la red y el contexto de la fuente de datos que invocó el handler a través del espacio de nombres `dataSource`: - `dataSource.address(): Address` - `dataSource.network(): string` @@ -713,7 +748,7 @@ You can inspect the contract address, network and context of the data source tha ### Entity y DataSourceContext -The base `Entity` class and the child `DataSourceContext` class have helpers to dynamically set and get fields: +La clase base `Entity` y la clase hija `DataSourceContext` tienen ayudantes para establecer y obtener campos de forma dinámica: - `setString(key: string, value: string): void` - `setI32(key: string, value: i32): void` @@ -727,3 +762,10 @@ The base `Entity` class and the child `DataSourceContext` class have helpers to - `getBytes(key: string): Bytes` - `getBoolean(key: string): boolean` - `getBigDecimal(key: string): BigDecimal` + +### Problemas comunes de AssemblyScript + +Hay ciertos problemas de [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) que son comunes durante el desarrollo de subgrafos. Varían en dificultad de depuración, sin embargo, ser consciente de ellos puede ayudar. La siguiente es una lista no exhaustiva de estos problemas: + +- Las variables de clase `Private` no se aplican en [AssembyScript](https://www.assemblyscript.org/status.html#language-features). No hay forma de proteger las variables de clase para que no se cambien directamente desde el objeto de clase. +- El alcance no se hereda en las [closure functions](https://www.assemblyscript.org/status.html#on-closures), es decir, las variables declaradas fuera de las closure functions no se pueden usar. Explicación en [Developer Highlights #3](https://www.youtube.com/watch?v=1-8AW-lVfrA&t=3243s). diff --git a/website/pages/es/developing/unit-testing-framework.mdx b/website/pages/es/developing/unit-testing-framework.mdx index 90c5ad120a96..82831004f984 100644 --- a/website/pages/es/developing/unit-testing-framework.mdx +++ b/website/pages/es/developing/unit-testing-framework.mdx @@ -2,74 +2,531 @@ title: Marco de Unit Testing --- -Matchstick es un marco de unit testing, desarrollado por [LimeChain](https://limechain.tech/), que permite a los desarrolladores de subgrafos probar su lógica de mapeo en un entorno sandbox y desplegar sus subgrafos con confianza! +¡Matchstick es un marco de unit testing, desarrollado por [LimeChain](https://limechain.tech/), que permite a los developers de subgrafos probar su lógica de mapeo en un entorno sandbox y deployar sus subgrafos con confianza! -## Getting Started +## Empezando -### Install dependencies +### Instalar dependencias -In order to use the test helper methods and run the tests, you will need to install the following dependencies: +Para utilizar los métodos auxiliares de prueba y ejecutar las pruebas, deberás instalar las siguientes dependencias: ```sh yarn add --dev matchstick-as ``` -❗ `graph-node` depends on PostgreSQL, so if you don't already have it, you will need to install it. We highly advise using the commands below as adding it in any other way may cause unexpected errors! +❗ `graph-node` depende de PostgreSQL, por lo que si aún no lo tienes, deberás instalarlo. ¡Recomendamos ampliamente usar los comandos a continuación, ya que agregarlos de otra manera puede causar errores inesperados! #### MacOS -Postgres installation command: +Comando de instalación de Postgres: ```sh brew install postgresql ``` +Crea un symlynk al último libpq.5.lib _Es posible que primero debas crear este directorio_ `/usr/local/opt/postgresql/lib/` + +```sh +ln -sf /usr/local/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib /usr/local/opt/postgresql/lib/libpq.5.dylib +``` + #### Linux -Postgres installation command (depends on your distro): +Comando de instalación de Postgres (depende de tu distribución): ```sh sudo apt install postgresql ``` -### OS-specific release binaries +### WSL (Subsistema de Windows para Linux) -The release binary comes in two flavours - for **МacOS** and **Linux**. To add **Matchstick** to your subgraph project just open up a terminal, navigate to the root folder of your project and simply run `graph test` - it downloads the latest **Matchstick** binary and runs the specified test or all tests in a test folder (or all existing tests if no datasource flag is specified). Example usage: `graph test gravity`. +Puedes usar Matchstick en WSL tanto con el enfoque de Docker como con el enfoque binario. Ya que WSL puede ser un poco complicado, aquí hay algunos consejos en caso de que encuentres problemas como -### Docker +``` +static BYTES = Symbol("Bytes") SyntaxError: Unexpected token = +``` + +o + +``` +/node_modules/gluegun/build/index.js:13 throw up; +``` + +Asegúrate de tener una versión más reciente de Node.js, graph-cli ya no es compatible con **v10.19.0**, y esa sigue siendo la versión predeterminada para las nuevas imágenes de Ubuntu en WSL. Por ejemplo, se ha confirmado que Matchstick funciona en WSL con **v18.1.0**, puedes cambiar a él a través de **nvm** o si actualizas su Node.js global. ¡No olvides eliminar `node_modules` y ejecutar `npm install` nuevamente después de actualizar sus nodejs! Luego, asegúrate de tener **libpq** instalado, puedes hacerlo ejecutando + +``` +sudo apt-get install libpq-dev +``` + +Y finalmente, no uses `graph test` (que usa tu instalación global de graph-cli y por alguna razón parece que no funciona en WSL actualmente), en su lugar usa `yarn test` o `npm run test` (que usará la instancia local a nivel de proyecto de graph-cli, que funciona de maravilla). Para eso, por supuesto, necesitarías tener un script `"test"` en tu archivo `package.json` que puede ser algo tan simple como + +```json +{ + "name": "demo-subgraph", + "version": "0.1.0", + "scripts": { + "test": "graph test", + ... + }, + "dependencies": { + "@graphprotocol/graph-cli": "^0.30.0", + "@graphprotocol/graph-ts": "^0.27.0", + "matchstick-as": "^0.5.0" + } +} +``` + +### Uso + +Para usar **Matchstick** en tu proyecto de subgrafo simplemente abre una terminal, navega a la carpeta raíz de tu proyecto y simplemente ejecuta `graph test [options] `: descarga el binario **Matchstick** más reciente y ejecuta la prueba especificada o todas las pruebas en una carpeta de prueba (o todas las pruebas existentes si no se especifica un indicador de fuente de datos). + +### Opciones CLI + +Esto ejecutará todas las pruebas en la carpeta de prueba: + +```sh +graph test +``` + +Esto ejecutará una prueba llamada gravity.test.ts y/o todas las pruebas dentro de una carpeta llamada gravity: -From `graph-cli 0.25.2`, the `graph test` command supports running `matchstick` in a docker container with the `-d` flag. The docker implementation uses [bind mount](https://docs.docker.com/storage/bind-mounts/) so it does not have to rebuild the docker image every time the `graph test -d` command is executed. Alternatively you can follow the instructions from the [matchstick](https://github.com/LimeChain/matchstick#docker-) repository to run docker manually. +```sh +graph test gravity +``` + +Esto ejecutará solo ese archivo de prueba específico: + +```sh +graph test path/to/file.test.ts +``` -❗ If you have previously ran `graph test` you may encounter the following error during docker build: +**Opciones:** +```sh +-c, --coverage Run the tests in coverage mode +-d, --docker Run the tests in a docker container (Note: Please execute from the root folder of the subgraph) +-f --force Binary: Redownloads the binary. Docker: Redownloads the Dockerfile and rebuilds the docker image. +-h, --help Show usage information +-l, --logs Logs to the console information about the OS, CPU model and download url (debugging purposes) +-r, --recompile Forces tests to be recompiled +-v, --version Choose the version of the rust binary that you want to be downloaded/used ``` + +### Docker + +Desde `graph-cli 0.25.2`, el comando `graph test` admite la ejecución de `matchstick` en un contenedor de Docker con la marca `-d`. La implementación de Docker utiliza [bind-mount](https://docs.docker.com/storage/bind-mounts/) para que no tenga que reconstruir la imagen del Docker cada vez que se ejecuta el comando ` graph test -d`. Como alternativa, puedes seguir las instrucciones del repositorio [matchstick](https://github.com/LimeChain/matchstick#docker-) para ejecutar docker manualmente. + +❗ Si ejecutaste previamente `graph test`, es posible que encuentres el siguiente error durante la compilación de docker: + +```sh error from sender: failed to xattr node_modules/binary-install-raw/bin/binary-: permission denied ``` -In this case create a `.dockerignore` in the root folder and add `node_modules/binary-install-raw/bin` +En este caso, crea un `.dockerignore` en la carpeta raíz y agrega `node_modules/binary-install-raw/bin` -### Configuration +### Configuración -Matchstick can be configured to use a custom tests and libs folder via `matchstick.yaml` config file: +Matchstick se puede configurar para usar pruebas personalizadas, bibliotecas y una ruta de manifesto personalizada a través del archivo de configuración `matchstick.yaml`: ```yaml -testsFolder: ./folderName +testsFolder: path/to/tests libsFolder: path/to/libs +manifestPath: path/to/subgraph.yaml +``` + +### Subgrafo de demostración + +Puedes probar y jugar con los ejemplos de esta guía clonando el [Demo Subgraph repo](https://github.com/LimeChain/demo-subgraph) + +### Tutoriales en vídeo + +También puedes ver la serie de videos en ["How to use Matchstick to write unit tests for your subgraphs"](https://www.youtube.com/playlist?list=PLTqyKgxaGF3SNakGQwczpSGVjS_xvOv3h) + +## Estructura de las pruebas (>=0.5.0) + +_**IMPORTANTE: Requiere matchstick-as >=0.5.0**_ + +### describe() + +`describe(name: String , () => {})` - Defines a test group. + +**_Notas:_** + +- _Las descripciones no son obligatorias. Todavía puedes usar test() a la antigua usanza, fuera de los bloques describe()_ + +Ejemplo: + +```typescript +import { describe, test } from "matchstick-as/assembly/index" +import { handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar()", () => { + test("Should create a new Gravatar entity", () => { + ... + }) +}) +``` + +Ejemplo anidado de `describe()`: + +```typescript +import { describe, test } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar } from "../../src/gravity" + +describe("handleUpdatedGravatar()", () => { + describe("When entity exists", () => { + test("updates the entity", () => { + ... + }) + }) + + describe("When entity does not exists", () => { + test("it creates a new entity", () => { + ... + }) + }) +}) +``` + +--- + +### test() + +`test(name: String, () =>, should_fail: bool)` - Define un caso de prueba. Puedes usar test() dentro de los bloques describe() o de forma independiente. + +Ejemplo: + +```typescript +import { describe, test } from "matchstick-as/assembly/index" +import { handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar()", () => { + test("Should create a new Entity", () => { + ... + }) +}) +``` + +o + +```typescript +test("handleNewGravatar() should create a new entity", () => { + ... +}) + + +``` + +--- + +### beforeAll() + +Ejecuta un bloque de código antes de cualquiera de las pruebas del archivo. Si `beforeAll` se declara dentro de un bloque `describe`, se ejecuta al principio de ese bloque `describe`. + +Ejemplos: + +El código dentro de `afterAll` se ejecutará una vez después de _todas_ las pruebas en el archivo. + +```typescript +import { describe, test, beforeAll } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" +import { Gravatar } from "../../generated/schema" + +beforeAll(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = “First Gravatar” + gravatar.save() + ... +}) + +describe("When the entity does not exist", () => { + test("it should create a new Gravatar with id 0x1", () => { + ... + }) +}) + +describe("When entity already exists", () => { + test("it should update the Gravatar with id 0x0", () => { + ... + }) +}) +``` + +El código dentro de `beforeAll` se ejecutará una vez antes de todas las pruebas en el primer bloque describe + +```typescript +import { describe, test, beforeAll } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" +import { Gravatar } from "../../generated/schema" + +describe("handleUpdatedGravatar()", () => { + beforeAll(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = “First Gravatar” + gravatar.save() + ... + }) + + test("updates Gravatar with id 0x0", () => { + ... + }) + + test("creates new Gravatar with id 0x1", () => { + ... + }) +}) +``` + +--- + +### afterAll() + +Ejecuta un bloque de código después de todas las pruebas del archivo. Si `afterAll` se declara dentro de un bloque `describe`, se ejecuta al final de ese bloque `describe`. + +Ejemplo: + +El código dentro de `afterAll` se ejecutará una vez después de _all_ las pruebas en el archivo. + +```typescript +import { describe, test, afterAll } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" +import { store } from "@graphprotocol/graph-ts" + +afterAll(() => { + store.remove("Gravatar", "0x0") + ... +}) + +describe("handleNewGravatar, () => { + test("creates Gravatar with id 0x0", () => { + ... + }) +}) + +describe("handleUpdatedGravatar", () => { + test("updates Gravatar with id 0x0", () => { + ... + }) +}) +``` + +El código dentro de `afterAll` se ejecutará una vez después de todas las pruebas en el primer bloque `describe` + +```typescript +import { describe, test, afterAll, clearStore } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar", () => { + afterAll(() => { + store.remove("Gravatar", "0x1") + ... + }) + + test("It creates a new entity with Id 0x0", () => { + ... + }) + + test("It creates a new entity with Id 0x1", () => { + ... + }) +}) + +describe("handleUpdatedGravatar", () => { + test("updates Gravatar with id 0x0", () => { + ... + }) +}) +``` + +--- + +### beforeEach() + +Ejecuta un bloque de código antes de cada prueba. Si `beforeEach` se declara dentro de un bloque `describe`, se ejecuta antes de cada prueba en ese bloque `describe`. + +Ejemplos: el código dentro de `beforeEach` se ejecutará antes de cada prueba. + +```typescript +import { describe, test, beforeEach, clearStore } from "matchstick-as/assembly/index" +import { handleNewGravatars } from "./utils" + +beforeEach(() => { + clearStore() // <-- clear the store before each test in the file +}) + +describe("handleNewGravatars, () => { + test("A test that requires a clean store", () => { + ... + }) + + test("Second that requires a clean store", () => { + ... + }) +}) + + ... +``` + +El código dentro de `beforeEach` se ejecutará solo antes de cada prueba en el describe + +```typescript +import { describe, test, beforeEach } from 'matchstick-as/assembly/index' +import { handleUpdatedGravatar, handleNewGravatar } from '../../src/gravity' + +describe('handleUpdatedGravatars', () => { + beforeEach(() => { + let gravatar = new Gravatar('0x0') + gravatar.displayName = 'First Gravatar' + gravatar.imageUrl = '' + gravatar.save() + }) + + test('Upates the displayName', () => { + assert.fieldEquals('Gravatar', '0x0', 'displayName', 'First Gravatar') + + // code that should update the displayName to 1st Gravatar + + assert.fieldEquals('Gravatar', '0x0', 'displayName', '1st Gravatar') + store.remove('Gravatar', '0x0') + }) + + test('Updates the imageUrl', () => { + assert.fieldEquals('Gravatar', '0x0', 'imageUrl', '') + + // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 + + assert.fieldEquals('Gravatar', '0x0', 'imageUrl', 'https://www.gravatar.com/avatar/0x0') + store.remove('Gravatar', '0x0') + }) +}) +``` + +--- + +### afterEach() + +Ejecuta un bloque de código después de cada prueba. Si `afterEach` se declara dentro de un bloque `describe`, se ejecuta después de cada prueba en ese bloque `describe`. + +Ejemplos: + +El código dentro de `afterEach` se ejecutará después de cada prueba. + +```typescript +import { describe, test, beforeEach, afterEach } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" + +beforeEach(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = “First Gravatar” + gravatar.save() +}) + +afterEach(() => { + store.remove("Gravatar", "0x0") +}) + +describe("handleNewGravatar", () => { + ... +}) + +describe("handleUpdatedGravatar", () => { + test("Upates the displayName", () => { + assert.fieldEquals("Gravatar", "0x0", "displayName", "First Gravatar") + + // code that should update the displayName to 1st Gravatar + + assert.fieldEquals("Gravatar", "0x0", "displayName", "1st Gravatar") + }) + + test("Updates the imageUrl", () => { + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "") + + // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 + + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "https://www.gravatar.com/avatar/0x0") + }) +}) +``` + +El código dentro de `afterEach` se ejecutará después de cada prueba en ese describe + +```typescript +import { describe, test, beforeEach, afterEach } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar", () => { + ... +}) + +describe("handleUpdatedGravatar", () => { + beforeEach(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = "First Gravatar" + gravatar.imageUrl = "" + gravatar.save() + }) + + afterEach(() => { + store.remove("Gravatar", "0x0") + }) + + test("Upates the displayName", () => { + assert.fieldEquals("Gravatar", "0x0", "displayName", "First Gravatar") + + // code that should update the displayName to 1st Gravatar + + assert.fieldEquals("Gravatar", "0x0", "displayName", "1st Gravatar") + }) + + test("Updates the imageUrl", () => { + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "") + + // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 + + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "https://www.gravatar.com/avatar/0x0") + }) +}) ``` -### Example Subgraph +## Asserts + +```typescript +fieldEquals(entityType: string, id: string, fieldName: string, expectedVal: string) + +equals(expected: ethereum.Value, actual: ethereum.Value) + +notInStore(entityType: string, id: string) -You can try out and play around with the examples from this guide by cloning the [Example Subgraph repo](https://github.com/graphprotocol/example-subgraph) +addressEquals(address1: Address, address2: Address) -### Video tutorials +bytesEquals(bytes1: Bytes, bytes2: Bytes) -Also you can check out the video series on ["How to use Matchstick to write unit tests for your subgraphs"](https://www.youtube.com/playlist?list=PLTqyKgxaGF3SNakGQwczpSGVjS_xvOv3h) +i32Equals(number1: i32, number2: i32) -## Write a Unit Test +bigIntEquals(bigInt1: BigInt, bigInt2: BigInt) -Let's see how a simple unit test would look like, using the Gravatar [Example Subgraph](https://github.com/graphprotocol/example-subgraph). +booleanEquals(bool1: boolean, bool2: boolean) -Assuming we have the following handler function (along with two helper functions to make our life easier): +stringEquals(string1: string, string2: string) + +arrayEquals(array1: Array, array2: Array) + +tupleEquals(tuple1: ethereum.Tuple, tuple2: ethereum.Tuple) + +assertTrue(value: boolean) + +assertNull(value: T) + +assertNotNull(value: T) + +entityCount(entityType: string, expectedCount: i32) +``` + +## Escribir un Unit Test + +Veamos cómo se vería un unit test simple usando los ejemplos de Gravatar en el [Demo Subgraph](https://github.com/LimeChain/demo-subgraph/blob/main/src/gravity.ts). + +Suponiendo que tenemos la siguiente función handler (junto con dos funciones auxiliares para hacernos la vida más fácil): ```typescript export function handleNewGravatar(event: NewGravatar): void { @@ -120,7 +577,7 @@ export function createNewGravatarEvent( } ``` -We first have to create a test file in our project. This is an example of how that might look like: +Primero tenemos que crear un archivo de prueba en nuestro proyecto. Este es un ejemplo de cómo podría verse: ```typescript import { clearStore, test, assert } from 'matchstick-as/assembly/index' @@ -154,38 +611,38 @@ test('Next test', () => { }) ``` -That's a lot to unpack! First off, an important thing to notice is that we're importing things from `matchstick-as`, our AssemblyScript helper library (distributed as an npm module). You can find the repository [here](https://github.com/LimeChain/matchstick-as). `matchstick-as` provides us with useful testing methods and also defines the `test()` function which we will use to build our test blocks. The rest of it is pretty straightforward - here's what happens: +¡Eso es mucho para desempacar! En primer lugar, algo importante a tener en cuenta es que estamos importando elementos de `matchstick-as`, nuestra biblioteca auxiliar de AssemblyScript (distribuida como un módulo npm). Puede encontrar el repositorio [aquí](https://github.com/LimeChain/matchstick-as). `matchstick-as` nos proporciona métodos de prueba útiles y también define la función `test()` que usaremos para construir nuestros bloques de prueba. El resto es bastante sencillo: esto es lo que sucede: -- Estamos configurando nuestro estado inicial y añadiendo una entidad Gravatar personalizada; -- Definimos dos objetos de evento `NewGravatar` junto con sus datos, utilizando la función `createNewGravatarEvent()`; -- Estamos llamando a los métodos handlers de esos eventos - `handleNewGravatars()` y pasando la lista de nuestros eventos personalizados; +- Estamos configurando nuestro estado inicial y agregando una entidad Gravatar personalizada; +- Definimos dos objetos de evento `NewGravatar` junto con sus datos, usando la función `createNewGravatarEvent()`; +- Estamos llamando a los métodos handler para esos eventos - `handleNewGravatars()` y pasando la lista de nuestros eventos personalizados; - Hacemos valer el estado del almacén. ¿Cómo funciona eso? - Pasamos una combinación única de tipo de Entidad e id. A continuación, comprobamos un campo específico de esa Entidad y afirmamos que tiene el valor que esperamos que tenga. Hacemos esto tanto para la Entidad Gravatar inicial que añadimos al almacén, como para las dos entidades Gravatar que se añaden cuando se llama a la función del handler; -- Y por último - estamos limpiando el almacén usando `clearStore()` para que nuestra próxima prueba pueda comenzar con un objeto almacén fresco y vacío. Podemos definir tantos bloques de prueba como queramos. +- Y, por último, estamos limpiando el store usando `clearStore()` para que nuestra próxima prueba pueda comenzar con un objeto store nuevo y vacío. Podemos definir tantos bloques de prueba como queramos. -There we go - we've created our first test! 👏 +Ahí vamos: ¡hemos creado nuestra primera prueba! 👏 -Now in order to run our tests you simply need to run the following in your subgraph root folder: +Ahora, para ejecutar nuestras pruebas, simplemente necesitas ejecutar lo siguiente en la carpeta raíz de tu subgrafo: -`graph test Gravity` +`prueba graph Gravity` -And if all goes well you should be greeted with the following: +Y si todo va bien, deberías ser recibido con lo siguiente: -![Matchstick saying “All tests passed!”](/img/matchstick-tests-passed.png) +![Matchstick diciendo "¡Todas las pruebas pasaron!"](/img/matchstick-tests-passed.png) -## Common test scenarios +## Escenarios de prueba comunes -### Hydrating the store with a certain state +### Abastecer la tienda con un cierto estado -Users are able to hydrate the store with a known set of entities. Here's an example to initialise the store with a Gravatar entity: +Los usuarios pueden abastecer la tienda con un conjunto conocido de entidades. Aquí hay un ejemplo para inicializar la tienda con una entidad Gravatar: ```typescript let gravatar = new Gravatar('entryId') gravatar.save() ``` -### Calling a mapping function with an event +### Llamar a una función de mapeo con un evento -A user can create a custom event and pass it to a mapping function that is bound to the store: +Un usuario puede crear un evento personalizado y pasarlo a una función de mapeo que está vinculada al store: ```typescript import { store } from 'matchstick-as/assembly/store' @@ -197,9 +654,9 @@ let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01 handleNewGravatar(newGravatarEvent) ``` -### Calling all of the mappings with event fixtures +### Llamar a todos los mapeos con fixtures de eventos -Users can call the mappings with test fixtures. +Los usuarios pueden llamar a los mapeos con fixtures de prueba. ```typescript import { NewGravatar } from '../../generated/Gravity/Gravity' @@ -221,9 +678,9 @@ export function handleNewGravatars(events: NewGravatar[]): void { } ``` -### Mocking contract calls +### Mocking de llamadas de contrato -Users can mock contract calls: +Los usuarios pueden mock llamadas de contrato: ```typescript import { addMetadata, assert, createMockedFunction, clearStore, test } from 'matchstick-as/assembly/index' @@ -243,9 +700,9 @@ let result = gravity.gravatarToOwner(bigIntParam) assert.equals(ethereum.Value.fromAddress(expectedResult), ethereum.Value.fromAddress(result)) ``` -As demonstrated, in order to mock a contract call and hardcore a return value, the user must provide a contract address, function name, function signature, an array of arguments, and of course - the return value. +Como se demostró, para hacer mock de una llamada de contrato y obtener un valor de retorno, el usuario debe proporcionar una dirección de contrato, un nombre de función, una firma de función, una serie de argumentos y, por supuesto, el valor de retorno. -Users can also mock function reverts: +Las usuarios también pueden hacer mock de reversiones de funciones: ```typescript let contractAddress = Address.fromString('0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7') @@ -254,13 +711,13 @@ createMockedFunction(contractAddress, 'getGravatar', 'getGravatar(address):(stri .reverts() ``` -### Mocking IPFS files (from matchstick 0.4.1) +### Mocking de archivos IPFS (desde matchstick 0.4.1) -Users can mock IPFS files by using `mockIpfsFile(hash, filePath)` function. The function accepts two arguments, the first one is the IPFS file hash/path and the second one is the path to a local file. +Los usuarios pueden mock archivos IPFS usando la función `mockIpfsFile(hash, filePath)`. La función acepta dos argumentos, el primero es el hash/ruta del archivo IPFS y el segundo es la ruta a un archivo local. -NOTE: When testing `ipfs.map/ipfs.mapJSON`, the callback function must be exported from the test file in order for matchstck to detect it, like the `processGravatar()` function in the test example bellow: +NOTA: Al probar `ipfs.map/ipfs.mapJSON`, la función callback debe exportarse desde el archivo de prueba para que matchstck la detecte, como la función `processGravatar()` en el siguiente ejemplo de prueba: -`.test.ts` file: +archivo `.test.ts`: ```typescript import { assert, test, mockIpfsFile } from 'matchstick-as/assembly/index' @@ -297,7 +754,7 @@ test('ipfs.map', () => { }) ``` -`utils.ts` file: +archivo `utils.ts`: ```typescript import { Address, ethereum, JSONValue, Value, ipfs, json, Bytes } from "@graphprotocol/graph-ts" @@ -345,9 +802,9 @@ export function gravatarFromIpfs(): void { } ``` -### Asserting the state of the store +### Afirmando el estado del almacenamiento -Users are able to assert the final (or midway) state of the store through asserting entities. In order to do this, the user has to supply an Entity type, the specific ID of an Entity, a name of a field on that Entity, and the expected value of the field. Here's a quick example: +Los usuarios pueden afirmar el estado final (o intermedio) del almacenamiento mediante la afirmación de entidades. Para hacerlo, el usuario debe proporcionar un tipo de entidad, el ID específico de una entidad, un nombre de campo en esa entidad y el valor esperado del campo. Aquí hay un ejemplo rápido: ```typescript import { assert } from 'matchstick-as/assembly/index' @@ -359,11 +816,11 @@ gravatar.save() assert.fieldEquals('Gravatar', 'gravatarId0', 'id', 'gravatarId0') ``` -Running the assert.fieldEquals() function will check for equality of the given field against the given expected value. The test will fail and an error message will be outputted if the values are **NOT** equal. Otherwise the test will pass successfully. +Ejecutar la función assert.fieldEquals() verificará la igualdad del campo dado contra el valor esperado dado. La prueba fallará y se generará un mensaje de error si los valores **NO** son iguales. De lo contrario, la prueba pasará con éxito. -### Interacting with Event metadata +### Interactuar con metadatos de eventos -Users can use default transaction metadata, which could be returned as an ethereum.Event by using the `newMockEvent()` function. The following example shows how you can read/write to those fields on the Event object: +Los usuarios pueden usar metadatos de transacción predeterminados, que podrían devolverse como un evento de ethereum mediante el uso de la función `newMockEvent()`. El siguiente ejemplo muestra cómo puedes leer/escribir en esos campos en el objeto Event: ```typescript // Read @@ -374,23 +831,23 @@ let UPDATED_ADDRESS = '0xB16081F360e3847006dB660bae1c6d1b2e17eC2A' newGravatarEvent.address = Address.fromString(UPDATED_ADDRESS) ``` -### Asserting variable equality +### Afirmar la igualdad de variables ```typescript assert.equals(ethereum.Value.fromString("hello"); ethereum.Value.fromString("hello")); ``` -### Asserting that an Entity is **not** in the store +### Afirmar que una Entidad **no** está en el almacenamiento -Users can assert that an entity does not exist in the store. The function takes an entity type and an id. If the entity is in fact in the store, the test will fail with a relevant error message. Here's a quick example of how to use this functionality: +Los usuarios pueden afirmar que una entidad no existe en el almacenamiento. La función toma un tipo de entidad y una identificación. Si la entidad está de hecho en el almacenamiento, la prueba fallará con un mensaje de error relevante. Aquí hay un ejemplo rápido de cómo usar esta funcionalidad: ```typescript assert.notInStore('Gravatar', '23') ``` -### Printing the whole store (for debug purposes) +### Impresión del almacenamiento entero (para fines de depuración) -You can print the whole store to the console using this helper function: +Puede imprimir todo el almacenamiento a la consola usando esta función de ayuda: ```typescript import { logStore } from 'matchstick-as/assembly/store' @@ -398,9 +855,9 @@ import { logStore } from 'matchstick-as/assembly/store' logStore() ``` -### Expected failure +### Fallo esperado -Users can have expected test failures, using the shouldFail flag on the test() functions: +Los usuarios pueden tener fallas de prueba esperadas, usando el indicador shouldFail en las funciones test(): ```typescript test( @@ -412,11 +869,11 @@ test( ) ``` -If the test is marked with shouldFail = true but DOES NOT fail, that will show up as an error in the logs and the test block will fail. Also, if it's marked with shouldFail = false (the default state), the test executor will crash. +Si la prueba está marcada con shouldFail = true pero NO falla, aparecerá como un error en los registros y el bloque de prueba fallará. Además, si está marcado con shouldFail = false (el estado predeterminado), el ejecutor de prueba fallará. ### Logging -Having custom logs in the unit tests is exactly the same as logging in the mappings. The difference is that the log object needs to be imported from matchstick-as rather than graph-ts. Here's a simple example with all non-critical log types: +Tener logs personalizados en los unit tests es exactamente lo mismo que hacer logging en los mapeos. La diferencia es que el objeto de registro debe importarse desde matchstick-as en lugar de graph-ts. Aquí hay un ejemplo simple con todos los tipos de log no críticos: ```typescript import { test } from "matchstick-as/assembly/index"; @@ -439,7 +896,7 @@ test("Warning", () => { }); ``` -Users can also simulate a critical failure, like so: +Los usuarios también pueden simular una falla crítica, así: ```typescript test('Blow everything up', () => { @@ -447,11 +904,11 @@ test('Blow everything up', () => { }) ``` -Logging critical errors will stop the execution of the tests and blow everything up. After all - we want to make sure you're code doesn't have critical logs in deployment, and you should notice right away if that were to happen. +El logging de errores críticos detendrá la ejecución de las pruebas y explotará todo. Después de todo, queremos asegurarnos de que tu código no tenga logs críticos en el deployment, y deberías darte cuenta de inmediato si eso sucediera. -### Testing derived fields +### Testing de campos derivados -Testing derived fields is a feature which (as the example below shows) allows the user to set a field in a certain entity and have another entity be updated automatically if it derives one of its fields from the first entity. Important thing to note is that the first entity needs to be reloaded as the automatic update happens in the store in rust of which the AS code is agnostic. +Testing de campos derivados es una función que (como muestra el siguiente ejemplo) permite al usuario establecer un campo en una determinada entidad y hacer que otra entidad se actualice automáticamente si deriva uno de sus campos de la primera entidad. Lo importante a tener en cuenta es que la primera entidad debe recargarse ya que la actualización automática ocurre en el store en rust de la cual el código AS es independiente. ```typescript test('Derived fields example test', () => { @@ -474,9 +931,13 @@ test('Derived fields example test', () => { }) ``` -### Testing dynamic data sources +### Probar fuentes de datos dinámicas + +La prueba de las fuentes de datos dinámicas se puede realizar simulando el valor de retorno de las funciones `context()`, `address()` y `network()` del dataSource namespace. Estas funciones actualmente devuelven lo siguiente: `context()` - devuelve una entidad vacía (DataSourceContext), `address()` - devuelve `0x00000000000000000000000000000000000000000`, ` network()` - devuelve `mainnet`. Las funciones `create(...)` y `createWithContext(...)` son mocked para no hacer nada, por lo que no es necesario llamarlas en las pruebas. Los cambios en los valores devueltos se pueden realizar a través de las funciones del espacio de nombres `dataSourceMock` en `matchstick-as` (versión 0.3.0+). + +Ejemplo a continuación: -Testing dynamic data sources can be be done by mocking the return value of the context(), address() and network() functions of the dataSource namespace. These functions currently return the following: context - returns an empty entity (DataSourceContext), address - returns "0x0000000000000000000000000000000000000000", network - returns "mainnet". The create(...) and createWithContext(...) functions are mocked to do nothing so they don't need to be called in the tests at all. Changes to the return values can be done through the functions of the dataSourceMock namespace in matchstick-as (version 0.3.0+). Example below: First we have the following event handler (which has been intentionally repurposed to showcase datasource mocking): +Primero, tenemos el siguiente handler de eventos (que se ha reutilizado intencionalmente para mostrar el mocking de datasource): ```typescript export function handleApproveTokenDestinations(event: ApproveTokenDestinations): void { @@ -492,7 +953,7 @@ export function handleApproveTokenDestinations(event: ApproveTokenDestinations): } ``` -And then we have the test using one of the methods in the dataSourceMock namespace to set a new return value for all of the dataSource functions: +Y luego tenemos la prueba usando uno de los métodos en el namespace dataSourceMock para establecer un nuevo valor de retorno para todas las funciones de dataSource: ```typescript import { assert, test, newMockEvent, dataSourceMock } from 'matchstick-as/assembly/index' @@ -525,50 +986,50 @@ test('Data source simple mocking example', () => { }) ``` -Notice that dataSourceMock.resetValues() is called at the end. That's because the values are remembered when they are changed and need to be reset if you want to go back to the default values. +Tenga en cuenta que dataSourceMock.resetValues() se llama al final. Esto se debe a que los valores se recuerdan cuando se modifican y deben restablecerse si desea volver a los valores predeterminados. -## Test Coverage +## Cobertura de prueba -Using **Matchstick**, subgraph developers are able to run a script that will calculate the test coverage of the written unit tests. The tool only works on **Linux** and **MacOS**, but when we add support for Docker (see progress on that [here](https://github.com/LimeChain/matchstick/issues/222)) users should be able to use it on any machine and almost any OS. +Usando **Matchstick**, los developers de subgrafos pueden ejecutar un script que calculará la cobertura de prueba de los unit tests escritos. La herramienta solo funciona en **Linux** y **MacOS**, pero cuando añadimos soporte para Docker (vea el progreso en eso [aquí](https://github.com/LimeChain/matchstick/issues/222)) los usuarios deberían poder usarlo en cualquier máquina y casi cualquier sistema operativo. -The test coverage tool is really simple - it takes the compiled test `wasm` binaries and converts them to `wat` files, which can then be easily inspected to see whether or not the handlers defined in `subgraph.yaml` have actually been called. Since code coverage (and testing as whole) is in very early stages in AssemblyScript and WebAssembly, **Matchstick** cannot check for branch coverage. Instead we rely on the assertion that if a given handler has been called, the event/function for it have been properly mocked. +La herramienta de cobertura de prueba es realmente simple: toma los archivos binarios `wasm` de prueba compilados y los convierte en archivos `wat`, que luego se pueden inspeccionar fácilmente para ver si los handlers están definidos o no. en `subgraph.yaml` en realidad han sido llamados. Dado que la cobertura del código (y las pruebas en general) se encuentra en etapas muy tempranas en AssemblyScript y WebAssembly, **Matchstick** no puede verificar la cobertura de la rama. En su lugar, confiamos en la afirmación de que si se ha llamado a un handler determinado, el evento/función para él se ha mocked correctamente. ### Prerrequisitos -To run the test coverage functionality provided in **Matchstick**, there are a few things you need to prepare beforehand: +Para ejecutar la funcionalidad de cobertura de prueba proporcionada en **Matchstick**, hay algunas cosas que debe preparar de antemano: -#### Export your handlers +#### Exporta tus handlers -In order for **Matchstick** to check which handlers are being run, those handlers need to be exported from the **test file**. So for instance in our example, in our gravity.test.ts file we have the following handler being imported: +Para que **Matchstick** verifique qué handlers se están ejecutando, esos handlers deben exportarse desde el **archivo de prueba**. Entonces, por ejemplo, en nuestro archivo gravity.test.ts tenemos el siguiente handler que se está importando: -```ts +```typescript import { handleNewGravatar } from '../../src/gravity' ``` -In order for that function to be visible (for it to be included in the `wat` file **by name**) we need to also export it, like this: +Para que esa función sea visible (para que se incluya en el archivo `wat` **por nombre**) también debemos exportarla, como este: -```ts +```typescript export { handleNewGravatar } ``` ### Uso -Once that's all set up, to run the test coverage tool, simply run: +Una vez que esté todo configurado, para ejecutar la herramienta de cobertura de prueba, simplemente ejecuta: ```sh graph test -- -c ``` -You could also add a custom `coverage` command to your `package.json` file, like so: +También puedes agregar un comando `coverage` personalizado a tu archivo `package.json`, así: -```ts +```typescript "scripts": { /.../ "coverage": "graph test -- -c" }, ``` -Hopefully that should execute the coverage tool without any issues. You should see something like this in the terminal: +Con suerte, eso debería ejecutar la herramienta de cobertura sin ningún problema. Debería ver algo como esto en la terminal: ```sh $ graph test -c @@ -607,17 +1068,17 @@ Test coverage: 0.0% (0/6 handlers). Global test coverage: 22.2% (2/9 handlers). ``` -### Test run time duration in the log output +### Duración del tiempo de ejecución de la prueba en la salida del log -The log output includes the test run duration. Here's an example: +La salida del log incluye la duración de la ejecución de la prueba. Aquí hay un ejemplo: -`[Thu, 31 Mar 2022 13:54:54 +0300] Program executed in: 42.270ms.` +`[Thu, 31 Mar 2022 13:54:54 +0300] Programa ejecutado en: 42.270ms.` -## Common compiler errors +## Errores comunes del compilador > Critical: Could not create WasmInstance from valid module with context: unknown import: wasi_snapshot_preview1::fd_write has not been defined -This means you have used `console.log` in your code, which is not supported by AssemblyScript. Please consider using the [Logging API](/developing/assemblyscript-api/#logging-api) +Esto significa que has utilizado `console.log` en tu código, que no es compatible con AssemblyScript. Considera usar la [API de registro](/developing/assemblyscript-api/#logging-api) > ERROR TS2554: Expected ? arguments, but got ?. > @@ -631,8 +1092,8 @@ This means you have used `console.log` in your code, which is not supported by A > > in ~lib/matchstick-as/assembly/defaults.ts(24,12) -The mismatch in arguments is caused by mismatch in `graph-ts` and `matchstick-as`. The best way to fix issues like this one is to update everything to the latest released version. +La falta de coincidencia en los argumentos se debe a la falta de coincidencia en `graph-ts` y `matchstick-as`. La mejor manera de solucionar problemas como este es actualizar todo a la última versión publicada. -## Feedback +## Comentario -If you have any questions, feedback, feature requests or just want to reach out, the best place would be The Graph Discord where we have a dedicated channel for Matchstick, called 🔥| unit-testing. +Si tiene preguntas, comentarios, solicitudes de funciones o simplemente deseas comunicarte, el mejor lugar sería The Graph Discord, donde tenemos un canal dedicado para Matchstick, llamado 🔥| unit-testing. diff --git a/website/pages/es/docsearch.json b/website/pages/es/docsearch.json index 8cfff967936d..80b8cc2de4e9 100644 --- a/website/pages/es/docsearch.json +++ b/website/pages/es/docsearch.json @@ -1,42 +1,42 @@ { "button": { - "buttonText": "Search", - "buttonAriaLabel": "Search" + "buttonText": "Buscar", + "buttonAriaLabel": "Buscar" }, "modal": { "searchBox": { - "resetButtonTitle": "Clear the query", - "resetButtonAriaLabel": "Clear the query", - "cancelButtonText": "Cancel", - "cancelButtonAriaLabel": "Cancel" + "resetButtonTitle": "Borrar la consulta", + "resetButtonAriaLabel": "Borrar la consulta", + "cancelButtonText": "Cancelar", + "cancelButtonAriaLabel": "Cancelar" }, "startScreen": { - "recentSearchesTitle": "Recent", - "noRecentSearchesText": "No recent searches", - "saveRecentSearchButtonTitle": "Save this search", - "removeRecentSearchButtonTitle": "Remove this search from history", - "favoriteSearchesTitle": "Favorite", - "removeFavoriteSearchButtonTitle": "Remove this search from favorites" + "recentSearchesTitle": "Reciente", + "noRecentSearchesText": "No hay búsquedas recientes", + "saveRecentSearchButtonTitle": "Guardar esta búsqueda", + "removeRecentSearchButtonTitle": "Eliminar esta búsqueda del historial", + "favoriteSearchesTitle": "Favorito", + "removeFavoriteSearchButtonTitle": "Eliminar esta búsqueda de los favoritos" }, "errorScreen": { - "titleText": "Unable to fetch results", - "helpText": "You might want to check your network connection." + "titleText": "No se puede obtener resultados", + "helpText": "Puede que quieras comprobar tu conexión de red." }, "footer": { - "selectText": "to select", - "selectKeyAriaLabel": "Enter key", - "navigateText": "to navigate", - "navigateUpKeyAriaLabel": "Arrow up", - "navigateDownKeyAriaLabel": "Arrow down", - "closeText": "to close", - "closeKeyAriaLabel": "Escape key", - "searchByText": "Search by" + "selectText": "para seleccionar", + "selectKeyAriaLabel": "Tecla enter", + "navigateText": "para navegar", + "navigateUpKeyAriaLabel": "Flecha arriba", + "navigateDownKeyAriaLabel": "Flecha abajo", + "closeText": "para cerrar", + "closeKeyAriaLabel": "Tecla escape", + "searchByText": "Buscar por" }, "noResultsScreen": { - "noResultsText": "No results for", - "suggestedQueryText": "Try searching for", - "reportMissingResultsText": "Believe this query should return results?", - "reportMissingResultsLinkText": "Let us know." + "noResultsText": "No hay resultados para", + "suggestedQueryText": "Intente buscar", + "reportMissingResultsText": "¿Cree que esta consulta debería devolver resultados?", + "reportMissingResultsLinkText": "Avísanos." } } } diff --git a/website/pages/es/firehose.mdx b/website/pages/es/firehose.mdx new file mode 100644 index 000000000000..feb830c2a907 --- /dev/null +++ b/website/pages/es/firehose.mdx @@ -0,0 +1,11 @@ +--- +title: Firehose +--- + +Firehose proporciona un enfoque basado en archivos y en streaming-first para procesar los datos de la blockchain. + +Se han creado integraciones de Firehose para Ethereum (y muchas cadenas EVM), NEAR, Solana, Cosmos y Arweave, y se está trabajando en otras más. + +Las integraciones de Graph Node se han creado para múltiples cadenas, por lo que los subgrafos pueden transmitir datos desde un Firehose para impulsar la indexación escalable y de alto rendimiento. Firehose también potencia [substreams](/substreams), una nueva tecnología de transformación creada por los core devs de The Graph. + +Visita la [firehose documentation](https://firehose.streamingfast.io/) para obtener más información. diff --git a/website/pages/es/global.json b/website/pages/es/global.json index b18fc35386aa..0e629b4eff1a 100644 --- a/website/pages/es/global.json +++ b/website/pages/es/global.json @@ -1,26 +1,26 @@ { "navigation": { "theGraphNetwork": "The Graph Network", - "subgraphs": "Subgraphs", - "developing": "Developing", - "deploying": "Deploying", - "publishing": "Publishing", - "managing": "Managing", - "querying": "Querying", - "cookbook": "Cookbook", - "indexing": "Indexing", - "releaseNotes": "Release Notes & Upgrade Guides" + "subgraphs": "Subgrafos", + "developing": "Desarrollando", + "deploying": "Deployando", + "publishing": "Publicando", + "managing": "Administrando", + "querying": "Consultando", + "cookbook": "Recetario", + "indexing": "Indexación", + "releaseNotes": "Notas de Publicación y Guías de Actualización" }, - "collapse": "Comprimir", + "collapse": "Colapsar", "expand": "Expandir", "previous": "Anterior", "next": "Siguiente", "editPage": "Editar página", "pageSections": "Sección de la página", - "linkToThisSection": "Enlace a está sección", + "linkToThisSection": "Enlace a esta sección", "technicalLevelRequired": "Nivel técnico requerido", - "notFoundTitle": "¡Oops! está página se perdió en el espacio...", - "notFoundSubtitle": "Verifica de que estés usando la dirección o explorador correcto en nuestro sitio web al hacer clic en el enlace de abajo.", + "notFoundTitle": "¡Ups! Esta página se ha perdido en el espacio...", + "notFoundSubtitle": "Verifica que estés usando la dirección correcta o visita nuestro sitio web haciendo clic en el enlace de abajo.", "goHome": "Ir a la página principal", "video": "Video" } diff --git a/website/pages/es/glossary.mdx b/website/pages/es/glossary.mdx new file mode 100644 index 000000000000..e890a6a91936 --- /dev/null +++ b/website/pages/es/glossary.mdx @@ -0,0 +1,79 @@ +--- +title: Glosario +--- + +- **The Graph**: Un protocolo descentralizado para indexar y consultar datos. + +- **Consulta (Query)**: Consulta de datos. En el caso de The Graph, una consulta es una solicitud de datos de un subgrafo que será respondida por un Indexador. + +- **GraphQL**: Un lenguaje de consulta para APIs y un tiempo de ejecución para cumplir esas consultas con datos existentes. The Graph utiliza GraphQL para consultar subgrafos. + +- **Subgrafo (Subgraph)**: Una API personalizada basada en datos de la blockchain que puede consultarse mediante [GraphQL](https://graphql.org/). Los developers pueden crear, deployar y publicar subgrafos en la red descentralizada de The Graph. Luego, los Indexadores pueden empezar a indexar los subgrafos para que los consumidores de subgrafos puedan consultarlos. + +- **Servicio Alojado (Hosted Service)**: Un servicio de plataforma temporal para construir y consultar subgrafos mientras la red descentralizada de The Graph madura su coste de servicio, calidad y experiencia del developer. + +- **Indexadores (Indexers)**: Participantes de la red que ejecutan nodos de indexación para indexar datos de la blockchain y servir consultas GraphQL. + +- **Flujos de ingresos de los indexadores (Indexer Revenue Streams)**: Los Indexadores son recompensados en GRT con dos componentes: reembolsos de tarifas de consulta y recompensas de indexación. + + 1. **Reembolsos de Tarifas de Consultas (Query Fee Rebates)**: Pagos de los consumidores de subgrafos por servir consultas en la red. + + 2. **Recompensas de Indexación (Indexing Rewards)**: Las recompensas que reciben los Indexadores por indexar subgrafos. Las recompensas de indexación se generan mediante una nueva emisión anual del 3% de GRT. + +- **Stake propio del Indexador (Indexer's Self Stake)**: La cantidad de GRT que los Indexadores depositan en stake para participar en la red descentralizada. El mínimo es de 100.000 GRT, y no hay límite superior. + +- **Delegadores (Delegators)**: Participantes de la red que poseen GRT y delegan su GRT en Indexadores. Esto permite a los Indexadores aumentar su stake en los subgrafos de la red. A cambio, los Delegadores reciben una parte de las recompensas de indexación que reciben los Indexadores por procesar los subgrafos. + +- **Impuesto a la Delegación (Delegation Tax)**: Una tasa del 0,5% que pagan los Delegadores cuando delegan GRT en los Indexadores. El GRT utilizado para pagar la tasa se quema. + +- **Curadores (Curators)**: Participantes de la red que identifican subgrafos de alta calidad y los "curan" (es decir, señalan GRT sobre ellos) a cambio de cuotas de curación. Cuando los Indexadores reclaman tarifas de consulta sobre un subgrafo, el 10% se distribuye entre los Curadores de ese subgrafo. Los Indexadores obtienen recompensas de indexación proporcionales a la señal en un subgrafo. Vemos una correlación entre la cantidad de GRT señalada y el número de Indexadores que indexan un subgrafo. + +- **Impuesto a la Curación (Curation Tax)**: Una tasa del 1% pagada por los Curadores cuando señalan GRT en los subgrafos. El GRT utilizado para pagar la tasa se quema. + +- **Consumidor de Subgrafos (Subgraph Consumer)**: Cualquier aplicación o usuario que consulte un subgrafo. + +- **Developer de subgrafos (Subgraph developer)**: Developer que construye y realiza el deploy de un subgrafo en la red descentralizada de The Graph. + +- **Manifiesto del subgrafo (Subgraph Manifest)**: Un archivo JSON que describe el esquema GraphQL del subgrafo, las fuentes de datos y otros metadatos. [Aquí](https://ipfs.io/ipfs/QmVQdzeGdPUiLiACeqXRpKAYpyj8Z1yfWLMUq7A7WundUf) tienes un ejemplo. + +- **Fondo de reembolso (Rebate Pool)**: Medida de seguridad económica que retiene las tarifas de consulta pagadas por los consumidores de subgrafos hasta que puedan ser reclamadas por los Indexadores como reembolsos de tarifas de consulta. El GRT residual se quema. + +- **Época (Epoch)**: Unidad de tiempo en red. Una época equivale actualmente a 6.646 bloques o aproximadamente 1 día. + +- **Asignación (Allocation)**: Un Indexador puede asignar su stake total de GRT (incluyendo el stake de los Delegadores) hacia subgrafos que hayan sido publicados en la red descentralizada de The Graph. Las allocations existen en una de cuatro fases. + + 1. **Activa (Active)**: Una allocation se considera activa cuando se crea on-chain. Esto se llama abrir una allocation, e indica a la red que el Indexador está indexando activamente y sirviendo consultas para un subgrafo en particular. Las allocations activas acumulan recompensas de indexación proporcionales a la señal del subgrafo y a la cantidad de GRT asignada. + + 2. **Cerrada (Closed)**: Un Indexador puede reclamar las recompensas de indexación acumuladas en un subgrafo determinado enviando una Prueba de Indexación (POI) reciente y válida. Esto se conoce como cerrar una allocation. Una allocation debe haber estado abierta durante un mínimo de una época antes de poder cerrarse. El periodo máximo de allocation es de 28 épocas. Si un Indexador deja una allocation abierta más de 28 épocas, se denomina allocation obsoleta. Cuando una asignación está en estado **Cerrado**, un Fisherman aún puede abrir una disputa para impugnar a un Indexador por servir datos falsos. + + 3. **Finalizada (Finalized)**: El período de disputa ha finalizado y los Indexadores pueden solicitar la devolución de las tarifas de consulta. + + 4. **Reclamada (Claimed)**: La fase final de una allocation, se han distribuido todas las recompensas elegibles y se han reclamado sus reembolsos de tarifas de consulta. + +- **Subgraph Studio**: Una potente aplicación para crear, deployar y publicar subgrafos. + +- **Percadores (Fishermen)**: Los participantes en la red pueden disputar las respuestas de consulta y los POI de los Indexadores. A esto se le llama ser un Fishermen (pescador). Una disputa resuelta a favor del Fishermen tiene como resultado una penalización económica para el Indexador, junto con un premio para el Fishermen, incentivando así la integridad del trabajo de indexación y consulta realizado por los Indexadores de la red. En la actualidad, la penalización (slashing) está fijada en el 2,5% del stake propio del Indexador, el 50% del GRT del slashing se destina al Fishermen y el otro 50% se quema. + +- **Árbitros (Arbitrators)**: Los Árbitros son participantes de la red establecidos a través de gobernanza. Su función es decidir el resultado de las disputas sobre indexación y consultas. Su objetivo es maximizar la utilidad y fiabilidad de The Graph Network. + +- **Recorte (Slashing)**: Los Indexadores pueden ver recortado su GRT en stake por proporcionar una prueba de indexación (POI) incorrecta o por servir datos inexactos. El porcentaje de slashing es un parámetro de protocolo fijado actualmente en el 2,5% del stake propia del Indexador. El 50% del GRT recortado va al Fishermen que disputó los datos inexactos o el POI incorrecto. El otro 50% se quema. + +- **Recompensas de Indexación (Indexing Rewards)**: Las recompensas que reciben los Indexadores por indexar subgrafos. Las recompensas de indexación se distribuyen en GRT. + +- **Recompensas de Delegación (Delegation Rewards)**: Las recompensas que reciben los Delegadores por delegar GRT en los Indexadores. Las recompensas por delegación se distribuyen en GRT. + +- **GRT**: El token de utilidad de trabajo de The Graph. GRT ofrece incentivos económicos a los participantes en la red por contribuir a ella. + +- **POI o Prueba de Indexación (Proof of Indexing)**: Cuando un Indexador cierra su allocation y quiere reclamar sus recompensas de Indexador acumuladas en un subgrafo dado, debe proporcionar una Prueba de Indexación (POI) válida y reciente. Los Fishermen pueden disputar la POI proporcionada por un Indexador. Una disputa resuelta a favor del Fishermen resultará en la eliminación del Indexador. + +- **Graph Node**: Graph Node es el componente que indexa los subgrafos, y hace que los datos resultantes estén disponibles para su consulta a través de una API GraphQL. Como tal, es fundamental para el stack del Indexador, y el correcto funcionamiento de Graph Node es crucial para ejecutar un Indexador con éxito. + +- **Agente indexador (Indexer Agent)**: El agente del Indexador forma parte del stack del Indexador. Facilita las interacciones on-chain del Indexador, incluido el registro en la red, la gestión de deploys de subgrafos en su(s) Graph Node y la gestión de allocations. + +- **Cliente The Graph (The Graph Client)**: Una biblioteca para construir dapps basadas en GraphQL de forma descentralizada. + +- **Explorador de Graph (Graph Explorer)**: Una aplicación diseñada para que los participantes en la red exploren subgrafos e interactúen con el protocolo. + +- **Graph CLI**: Una herramienta de interfaz de línea de comandos para construir y realizar deploys en The Graph. + +- **Período de enfriamiento (Cooldown Period)**: El tiempo restante hasta que un Indexador que cambió sus parámetros de delegación pueda volver a hacerlo. diff --git a/website/pages/es/index.json b/website/pages/es/index.json index 163cca14ff97..54eafbca6f71 100644 --- a/website/pages/es/index.json +++ b/website/pages/es/index.json @@ -1,6 +1,6 @@ { "title": "Comenzar", - "intro": "Conoce The Graph, un protocolo descentralizado para indexar y consultar datos de las blockchains.", + "intro": "Aprende más sobre The Graph, un protocolo descentralizado para indexar y consultar datos de las blockchains.", "shortcuts": { "aboutTheGraph": { "title": "Acerca de The Graph", @@ -32,12 +32,12 @@ "description": "Conoce las funciones de la red The Graph.", "roles": { "developer": { - "title": "Desarrollador", + "title": "Developer (desarrollador)", "description": "Crear un subgrafo o utilizar subgrafos existentes en una dapp" }, "indexer": { "title": "Indexador", - "description": "Operador de nodos encargado de indexar los datos y proveer consultas" + "description": "Opera un nodo para indexar los datos y proveer consultas" }, "curator": { "title": "Curador", @@ -45,7 +45,7 @@ }, "delegator": { "title": "Delegador", - "description": "Se encarga de proteger la red al delegar sus GRT a los Indexadores" + "description": "Proteja la red delegando GRT a los indexadores" } } }, diff --git a/website/pages/es/managing/transferring-subgraph-ownership.mdx b/website/pages/es/managing/transferring-subgraph-ownership.mdx index 38557171f52a..a951eb60d91a 100644 --- a/website/pages/es/managing/transferring-subgraph-ownership.mdx +++ b/website/pages/es/managing/transferring-subgraph-ownership.mdx @@ -4,7 +4,7 @@ title: Transferencia de la Propiedad del Subgrafo The Graph admite la transferencia de la propiedad de un subgrafo. -Cuando despliegas un subgrafo en mainnet, se acuñará un NFT a la dirección que desplegó el subgrafo. El NFT se basa en un ERC721 estándar, por lo que puede transferirse fácilmente a diferentes cuentas. +Cuando deployas un subgrafo en mainnet, se acuñará un NFT a la dirección que deployó el subgrafo. El NFT se basa en un ERC721 estándar, por lo que puede transferirse fácilmente a diferentes cuentas. El propietario de la NFT controla el subgrafo. Si el propietario decide vender el NFT, o transferirlo, ya no podrá realizar ediciones o actualizaciones de ese subgrafo en la red. @@ -12,7 +12,7 @@ Además de añadir más flexibilidad al ciclo de vida del desarrollo, esta funci ### Ver tu subgrafo como un NFT -Para ver tu subgrafo como una NFT, puedes visitar un mercado de NFT como OpenSea: +Para ver tu subgrafo como un NFT, puedes visitar un mercado de NFT como OpenSea: ``` https://opensea.io/your-wallet-address @@ -28,12 +28,12 @@ https://rainbow.me/your-wallet-addres Para transferir la propiedad de un subgrafo, puedes utilizar la interfaz de usuario integrada en Subgraph Studio: -![Traslado de la propiedad del subgrafo](/img/subgraph-ownership-transfer-1.png) +![Transferencia de propiedad de subgrafo](/img/subgraph-ownership-transfer-1.png) -Y luego elegir la dirección a la que se quiere transferir el subgrafo: +Y luego elije la dirección a la que te gustaría transferir el subgrafo: -![Traslado de la Propiedad del Subgrafo](/img/subgraph-ownership-transfer-2.png) +![Transferencia de propiedad de subgrafo](/img/subgraph-ownership-transfer-2.png) -También puedes utilizar la interfaz de usuario integrada de los mercados de NFT, como OpenSea: +También puedes usar la interfaz de usuario integrada de los mercados de NFT como OpenSea: ![Transferencia de la Propiedad del Subgrupo desde el Marketplace de NFT](/img/subgraph-ownership-transfer-nft-marketplace.png) diff --git a/website/pages/es/mips-faqs.mdx b/website/pages/es/mips-faqs.mdx new file mode 100644 index 000000000000..17729f6a4af1 --- /dev/null +++ b/website/pages/es/mips-faqs.mdx @@ -0,0 +1,125 @@ +--- +title: Preguntas Frecuentes sobre MIPs +--- + +## Introducción + +Es un momento emocionante para participar en el ecosistema de The Graph. Durante el [Graph Day 2022](https://thegraph.com/graph-day/2022/) Yaniv Tal anunció la [desaparición del Servicio Alojado](https://thegraph.com/blog/sunsetting-hosted-service/), un momento hacia el que el ecosistema de The Graph ha estado trabajando durante muchos años. + +Para apoyar el cese del Servicio Alojado y la migración de todas sus actividades a la red descentralizada, The Graph Foundation ha anunciado el programa de Proveedores de Infraestructura de Migración (MIPs, por sus siglas en inglés) (https://thegraph.com/blog/mips-multi-chain-indexing-incentivized-program). + +El programa MIPs es un programa de incentivos para Indexadores que les brinda recursos para indexar cadenas más allá de Ethereum mainnet y ayuda al protocolo The Graph a expandir la red descentralizada en una capa de infraestructura multi-chain. + +El programa MIPs ha asignado el 0,75% del suministro de GRT (75M de GRT), con el 0,5% para recompensar a los Indexadores que contribuyen al arranque de la red y el 0,25% asignado a grants de migración para desarrolladores de subgrafos que utilizan subgrafos multi-chain. + +### Recursos útiles + +- [Herramientas para Indexadores de Vincent (Victor) Taglia](https://indexer-2ools.vincenttaglia.com/#/) +- [Cómo convertirte en un Indexador eficaz en The Graph Network](https://thegraph.com/blog/how-to-become-indexer/) +- [Indexer Knowledge Hub](https://thegraph.academy/indexers/) +- [Allocation Optimiser](https://github.com/graphprotocol/allocationopt.jl) +- [Allocation Optimization Tooling](https://github.com/anyblockanalytics/thegraph-allocation-optimization/) + +### 1. ¿Es posible generar una prueba de indexación (POI) válida aunque haya fallado un subgrafo? + +Sí, así es. + +Para contextualizar, el estatuto de arbitraje, [obtenga más información sobre el estatuto aquí] \(https://hackmd.io/@4Ln8SAS4RX-505bIHZTeRw/BJcHzpHDu#Abstract), especifica la metodología para generar un POI para un subgrafo fallido. + +Un miembro de la comunidad, [SunTzu] \(https://github.com/suntzu93), ha creado un script para automatizar este proceso en cumplimiento de la metodología del estatuto de arbitraje. Consulte el repositorio [here] \(https://github.com/suntzu93/get_valid_poi_subgraph). + +### 2. ¿Qué cadena incentivará primero el programa MIP? + +¡La primera cadena que se admitirá en la red descentralizada es Gnosis Chain! Anteriormente conocida como xDAI, Gnosis Chain es una cadena basada en EVM. Gnosis Chain fue seleccionada como la primera debido a su facilidad de uso para ejecutar nodos, preparación de Indexadores, alineación con The Graph y adopción dentro de web3. + +### 3. ¿Cómo se añadirán nuevas cadenas al programa MIP? + +Se anunciarán nuevas cadenas durante el programa MIPs, según la preparación de los Indexadores, la demanda y el sentimiento de la comunidad. En primer lugar, las cadenas serán admitidas en la red de prueba y, posteriormente, se aprobará un GIP para admitir esa cadena en la mainnet. Los Indexadores que participen en el programa MIPs elegirán en qué cadenas están interesados en admitir y ganarán recompensas por cada cadena, además de ganar tarifas de consulta y recompensas de indexación en la red por servir subgrafos. Los participantes de MIPs serán evaluados según su desempeño, capacidad para satisfacer las necesidades de la red y el apoyo de la comunidad. + +### 4. ¿Cómo sabremos cuándo la red está preparada para una nueva cadena? + +The Graph Foundation supervisará las métricas de rendimiento de la calidad de servicio, el rendimiento de la red y los canales de la comunidad para evaluar mejor el grado de preparación. La prioridad es garantizar que la red satisfaga las necesidades de rendimiento para que las dapps multi-chain puedan migrar sus subgrafos. + +### 5. ¿Cómo se reparten las recompensas por cadena? + +Dado que las cadenas varían en sus requisitos de sincronización de nodos, y difieren en volumen de consultas y adopción, las recompensas por cadena se decidirán al final del ciclo de esa cadena para garantizar que se recogen todos los comentarios y aprendizajes. Sin embargo, en todo momento, los Indexadores también podrán ganar tarifas de consulta y recompensas por indexación una vez que la cadena sea compatible con la red. + +### 6. ¿Necesitamos indexar todas las cadenas en el programa MIPs o podemos elegir solo una cadena e indexarla? + +Puedes indexar cualquier cadena que desees. El objetivo del programa MIPs es dotar a los Indexadores de las herramientas y conocimientos necesarios para indexar las cadenas que deseen y apoyar los ecosistemas web3 que les interesen. Sin embargo, para cada cadena, hay fases desde la testnet hasta la mainnet. Asegúrate de completar todas las fases para las cadenas que está indexando. Consulta [The MIPs notion page](https://thegraphfoundation.notion.site/MIPs-Home-911e1187f1d94d12b247317265f81059) para saber más sobre las fases. + +### 7. ¿Cuándo se distribuirán las recompensas? + +Las recompensas de los MIPs se distribuirán por cadena una vez que se cumplan las métricas de rendimiento y los subgrafos migrados sean compatibles con esos Indexadores. Presta atención a la información sobre las recompensas totales por cadena a mitad del ciclo de esa cadena. + +### 8. ¿Cómo funciona la puntuación? + +Los Indexadores competirán por recompensas basadas en la puntuación obtenida a lo largo del programa en la tabla de clasificación. La puntuación del programa se basará en: + +**Cobertura del subgrafo** + +- ¿Proporciona un soporte máximo de subgrafos por cadena? + +- Durante los MIPs, se espera que los grandes Indexadores realicen stake en más del 50% de los subgrafos por cadena que soportan. + +**Calidad del servicio** + +- ¿Sirve el Indexador la cadena con una buena calidad de servicio (latencia, datos actuales, tiempo de actividad, etc.)? + +- ¿Apoya el Indexador a los desarrolladores de dapps siendo reactivo a sus necesidades? + +¿Está el Indexador asignando eficientemente, contribuyendo a la salud general de la red? + +**Apoyo comunitario** + +- ¿Está colaborando el Indexador con otros Indexadores para ayudarles a prepararse para ser multi-chain? + +- ¿Está el Indexador proporcionando información a los core devs a través del programa o compartiendo información con los Indexadores en el Foro? + +### 9. ¿Cómo se asignará el rol en Discord? + +Los moderadores asignarán los roles en los próximos días. + +### 10. ¿Está bien iniciar el programa en una red de prueba y luego pasar a la mainnet? ¿Podrán identificar mi nodo y tenerlo en cuenta a la hora de distribuir las recompensas? + +Sí, de hecho se espera que lo hagas. Hay varias fases en Göerli y una en la mainnet. + +### 11. ¿En qué momento espera que los participantes añadan un deploy en la mainnet? + +Durante la fase 3 será necesario disponer de un indexador de la mainnet. Próximamente se publicará más información al respecto en esta página de notion (https://thegraphfoundation.notion.site/MIPs-Home-911e1187f1d94d12b247317265f81059) + +### 12. ¿Las recompensas estarán sujetas a vesting? + +El porcentaje que se distribuirá al final del programa estará sujeto a vesting. Para más información, consulta el Acuerdo de Indexación. + +### 13. Para los equipos con más de un miembro, ¿todos los miembros del equipo recibirán un rol de Discord de MIPs? + +Si + +### 14. ¿Es posible utilizar los tokens bloqueados del programa graph curator para participar en la red de pruebas de los MIPs? + +Si + +### 15. Durante el programa MIPs, ¿habrá un plazo para disputar los POI no válidos? + +Por decidirse. Vuelve periódicamente a esta página para obtener más detalles al respecto o, si tu solicitud es urgente, envía un correo electrónico a info@thegraph.foundation + +### 17. ¿Podemos combinar dos contratos de vesting? + +No. Las opciones son: puedes delegar uno en el otro o ejecutar dos indexadores distintos. + +### 18. ¿Preguntas sobre KYC? + +Envía un correo electrónico a info@thegraph.foundation + +### 19. No estoy preparado para indexar Gnosis Chain, ¿puedo saltar y empezar a indexar desde otra cadena cuando esté listo? + +Si + +### 20. ¿Existen regiones recomendadas para instalar los servidores? + +No damos recomendaciones sobre regiones. A la hora de elegir ubicaciones, quizá quieras pensar dónde están los principales mercados de criptomonedas. + +### 21. ¿Qué es el "coste del gas de handler"? + +Es la medida determinista del coste de ejecución de un handler. Contrariamente a lo que podría sugerir su nombre, no está relacionado con el coste de gas en blockchains. diff --git a/website/pages/es/network/curating.mdx b/website/pages/es/network/curating.mdx index f7f01588d9f1..5c39b9e68054 100644 --- a/website/pages/es/network/curating.mdx +++ b/website/pages/es/network/curating.mdx @@ -1,55 +1,55 @@ --- -title: curación +title: Curación --- -Los curadores son vitales para la economía descentralizada que conforma a The Graph. Ellos utilizan su conocimiento sobre el ecosistema Web3 para calificar y señalar los subgrafos que deben ser indexados en la red de The Graph. A través del explorador, los curadores pueden ver los datos de la red y tomar decisiones sobre la señalización. The Graph Network recompensa a los curadores que señalan subgrafos valiosos para la red ya que ganan una parte de las tarifas de consulta que generan los subgrafos. Los curadores están motivados económicamente a través de la señalización rápida de dichos subgrafos. Estas señales de los curadores son importantes para los Indexadores, quienes luego pueden procesar o indexar los datos de estos subgrafos señalados. +Los Curadores son fundamentales para la economía descentralizada de The Graph. Utilizan su conocimiento del ecosistema web3 para evaluar y señalar los subgrafos que deben ser indexados por The Graph Network. A través de Explorer, los Curadores pueden ver los datos de la red para tomar decisiones de señalización. The Graph Network recompensa a los Curadores que señalan subgrafos de buena calidad con una parte de las tarifas de consulta que generan los subgrafos. Los Curadores están incentivados económicamente para señalar pronto. Estas señales de los Curadores son importantes para los Indexadores, que pueden procesar o indexar los datos de estos subgrafos señalados. Al señalar, los curadores pueden decidir entre señalar en una versión específica del subgrafo o hacerlo usando la opción de auto migración. Cuando se señala mediante la auto migración, las acciones de un curador siempre se actualizarán a la última versión publicada por el desarrollador. Si, en cambio, decides señalar una versión específica, las acciones siempre permanecerán en esa versión específica. -Recuerda que la curación es riesgosa. Por favor, haz una investigación rigurosa para asegurarte de seleccionar los subgrafos en los que confiar. Crear un subgrafo no requiere permiso, por lo que las personas pueden crear subgrafos y llamarlos con el nombre que deseen. Para obtener más orientación sobre los riesgos de la curación, consulta la +Recuerda que la curación es riesgosa. Por favor, haz una investigación rigurosa para asegurarte de seleccionar los subgrafos en los que confie. Crear un subgrafo no requiere permiso, por lo que las personas pueden crear subgrafos y llamarlos con el nombre que deseen. Para obtener más orientación sobre los riesgos de la curación, consulte [The Graph Academy's Curation Guide.](https://thegraph.academy/curators/) -## Curva de vinculación 101 +## Bonding Curve 101 -Primero, demos un paso atrás. Cada subgrafo tiene una curva de vinculación en la que se acuñan las acciones de curación, cuando un usuario agrega una señal ** a ** a la curva. La curva de vinculación de cada subgrafo es única. Las curvas de vinculación están diseñadas para que el precio tras acuñar (mintear) una participación dentro de la curación de un subgrafo aumente linealmente, sobre el número de participaciones acuñadas. +En primer lugar, damos un paso atrás. Cada subgrafo tiene una bonding curve en la que se acuñan las acciones de curación cuando un usuario añade una señal **en la** curva. La bonding curve de cada subgrafo es única. Las bonding curve están diseñadas para que el precio de acuñar una acción de curación en un subgrafo aumente linealmente, sobre el número de acciones acuñadas. ![Precio por acciones](/img/price-per-share.png) -Como resultado, el precio aumenta linealmente, lo que significa que con el tiempo resultará más caro comprar una participación. A continuación, se muestra un ejemplo de lo que queremos decir; consulta la curva de vinculación a continuación: +Como resultado, el precio aumenta linealmente, lo que significa que con el tiempo resultará más caro comprar una participación. A continuación, se muestra un ejemplo de lo que queremos decir; consulta la bonding curve a continuación: -![Curva de vinculación](/img/bonding-curve.png) +![Bonding curve](/img/bonding-curve.png) -Imagina que tenemos dos curadores que anclan participaciones dentro de un subgrafo: +Imagina que tenemos dos curadores que acuñan acciones para un subgrafo: -- El Curador A es el primero en señalar dentro del subgrafo. Al agregar 120.000 GRT en la curva, pueden acuñar 2000 participaciones. -- La señal del Curador B está en el subgrafo en algún momento posterior al primero. Para recibir la misma cantidad participativa que el Curador A, este deberá agregar 360.000 GRT en la curva. +- El Curador A es el primero en señalar en el subgrafo. Al agregar 120.000 GRT en la curva, puede acuñar 2000 participaciones. +- El Curador B señala el subgrafo en algún momento posterior. Para recibir la misma cantidad participativa que el Curador A, este deberá agregar 360.000 GRT en la curva. - Dado que ambos curadores poseen la mitad participativa de dicha curación, recibirían una cantidad igual en las recompensas por ser curador. -- Si alguno de los curadores quemara sus 2000 participaciones, recibirían 360.000 GRT. +- Si alguno de los curadores quemara sus 2000 participaciones de curaduría, recibirían 360.000 GRT. - El curador restante recibiría todas las recompensas en ese subgrafo. Si quemaran sus participaciones a fin de retirar sus GRT, recibirían 120.000 GRT. -- **TLDR:** El valor de las participaciones en GRT son determinadas por la curva de vinculación y suelen ser volátiles. Existe la posibilidad de incurrir en grandes pérdidas. La señalización temprana significa que ingresas menos GRT por cada acción. Profundizando un poco, esto significa que ganarás mas recompensas en GRT siendo el primer curador en ese subgrafo que los posteriores en llegar. +- **TLDR (en resumen):** La valoración de GRT de las acciones de curación viene determinada por la bonding curva y puede ser volátil. Existe la posibilidad de incurrir grandes pérdidas. Señalar temprano significa que pones menos GRT por cada acción. Por extensión, esto significa que se ganan más derechos de curador por GRT que los curadores posteriores por el mismo subgrafo. -En general, una curva de vinculación es una curva matemática que define la relación entre la oferta de tokens y el precio de los activos. Siendo específicos en la curación de subgrafos, **el precio de cada participación del subgrafo aumenta con cada token invertido** y el **precio de cada participación disminuye con cada token vendido.** +En general, una bonding curva es una curva matemática que define la relación entre la oferta de tokens y el precio de los activos. Siendo específicos en la curación de subgrafos, **el precio de cada participación del subgrafo aumenta con cada token invertido** y el **precio de cada participación disminuye con cada token vendido.** -En el caso de The Graph, se aprovecha [la implementación de una fórmula por parte de Bancor para la curva de vinculación](https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA). +En el caso de The Graph, se aprovecha [la implementación de una fórmula por parte de Bancor para la bonding curve](https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA). -## ¿Cómo señalar? +## Cómo señalar -Ahora que hemos abarcado los conceptos básicos sobre cómo funciona la curva de vinculación, vamos a enseñarte como señalar un subgrafo. Dentro de la pestaña Curador en el explorador de The Graph, los curadores podrán señalar y anular la señal en ciertos subgrafos basados en las estadísticas de la red. Para una descripción general paso a paso de cómo hacer esto en el explorador, [haz click aquí.](/network/explorer) +Ahora que hemos cubierto lo básico sobre cómo funciona la bonding curve, así es como se procederá a señalar en un subgrafo. Dentro de la pestaña Curador en el Graph Explorer, los Curadores podrán señalar y dejar de señalar en ciertos subgrafos basados en las estadísticas de la red. Para ver un resumen paso a paso de cómo hacer esto en el Explorer, [haz click aqui.](/network/explorer) Un curador puede optar por señalar una versión especifica de un subgrafo, o puede optar por que su señal migre automáticamente a la versión de producción mas reciente de ese subgrafo. Ambas son estrategias válidas y tienen sus pros y sus contras. -Señalar una versión específica es esencialmente útil cuando un subgrafo es usado por múltiples dApps. Una dApp podría necesitar una actualización periódica a fin de que el subgrafo tenga nuevas funciones. Otra dApp podría necesitar una versión de subgrafo mas antigua y bien probada. Luego de la curación inicial, se incurre en una tarifa estándar del 1%. +Señalar una versión específica es especialmente útil cuando un subgrafo es utilizado por múltiples dApps. Una dApp puede necesitar actualizar regularmente el subgrafo con nuevas características. Otra dApp puede preferir utilizar una versión del subgrafo más antigua y probada. Tras la curación inicial, se incurre en un impuesto estándar del 1%. -Hacer que tu señal migre automáticamente a la versión más reciente, puede ser muy bueno si buscas asegurar la mayor cantidad de tarifas por consultas. Cada vez que curas, se incurre en un impuesto de curación del 1%. Además, pagaras un impuesto de curación del 0.5% en cada migración. Se aconseja a los desarrolladores de subgrafos a qué no publiquen nuevas versiones con frecuencia; puesto que deberán pagar una tarifa de curación del 0.5% en todas las acciones de curación migradas automáticamente. +Hacer que tu señal migre automáticamente a la más reciente compilación de producción puede ser valioso para asegurarse de seguir acumulando tarifas de consulta. Cada vez que curas, se incurre en un impuesto de curación del 1%. También pagarás un impuesto de curación del 0,5% en cada migración. Se desaconseja a los desarrolladores de Subgrafos que publiquen con frecuencia nuevas versiones - tienen que pagar un impuesto de curación del 0,5% en todas las acciones de curación auto-migradas. -> **Nota**: La primer dirección en señalar un subgrafo específico, se considera el primer curador, y éste tendrá que hacer un trabajo mucho más intenso en cuánto al gas, a diferencia del resto de los curadores que vengan después de él, esto debido a que el primer curador comienza los tokens participativos de la curación, inicia la curva de vinculación y también transfiere los tokens dentro del proxy de The Graph. +> **Nota**: La primer dirección en señalar un subgrafo específico, se considera el primer curador, y éste tendrá que hacer un trabajo mucho más intenso en cuánto al gas, a diferencia del resto de los curadores que vengan después de él, esto debido a que el primer curador comienza los tokens participativos de la curación, inicia la bonding curve y también transfiere los tokens dentro del proxy de The Graph. ## ¿Qué significa Señalar para The Graph Network? Para que los consumidores finales puedan consultar un subgrafo, primero se debe indexar el subgrafo. La indexación es un proceso en el que los archivos, los datos y los metadatos se examinan, catalogan y luego se indexan para que los resultados se puedan encontrar más rápido. Para que se puedan buscar los datos de un subgrafo, es necesario que esté organizado. -Por lo tanto, si los Indexadores tuvieran que adivinar qué subgrafos deberían indexar, habría pocas posibilidades de que obtengan tarifas de consulta sólidas porque no tendrían forma de validar qué subgrafos son de buena calidad. Ingrese a la curación. +Por lo tanto, si los Indexadores tuvieran que adivinar qué subgrafos deberían indexar, habría pocas posibilidades de que obtengan tarifas de consulta sólidas porque no tendrían forma de validar qué subgrafos son de buena calidad. Ingresa a la curación. -Los curadores hacen que la red The Graph sea eficiente y la señalización es el proceso que utilizan los curadores para que los Indexadores sepan que un subgrafo es bueno para indexar, donde los GRT son agregados a la curva de vinculación de un subgrafo. Los Indexadores pueden confiar intrínsecamente en la señal de un curador porque, al señalar, los curadores acuñan una acción de curación para el subgrafo, lo que les da derecho a una parte de las tarifas de consulta futuras que impulsa el subgrafo. La señal del curador se representa como un token ERC20 llamado Graph Curation Shares (GCS). Los curadores que quieran ganar más tarifas por consulta deberán anclar sus GRT a los subgrafos que predicen que generarán un fuerte flujo de tarifas dentro de la red. Los curadores también pueden ganar menos tarifas por consulta si eligen curar o señalar un subgrafo de baja calidad, ya que habrá menos consultas que procesar o menos Indexadores para procesar esas consultas. ¡Mira el siguiente diagrama! +Los Curadores hacen que la red The Graph sea eficiente y la señalización es el proceso que utilizan los curadores para hacer saber a los Indexadores que un subgrafo es bueno para indexar, donde los GRT se añaden a una bonding curve para un subgrafo. Los Indexadores pueden confiar intrínsecamente en la señal de un curador porque al señalizar, los curadores acuñan una cuota de curación para el subgrafo, lo que les da derecho a una parte de las futuras tarifas de consulta que el subgrafo genere. La señal del curador se representa como tokens ERC20 llamados Graph Curation Shares (GCS). Los Curadores que quieran ganar más tarifas de consulta deben señalar con sus GRT a los subgrafos que prevean que generarán un fuerte flujo de tarifas a la red. Los Curadores no pueden ser recortados por su mal comportamiento, pero existe un impuesto de depósito sobre los Curadores para desincentivar la toma de malas decisiones que puedan dañar la integridad de la red. Los Curadores también ganan menos tarifas de consulta si deciden curar en un subgrafo de baja calidad, ya que habrá menos consultas que procesar o menos indexadores que procesen esas consultas. Mira el siguiente diagrama! ![Diagrama de Señalización](/img/curator-signaling.png) @@ -60,17 +60,17 @@ Los Indexadores pueden encontrar subgrafos para indexar en función de las seña ## Riesgos 1. El mercado de consultas es inherentemente joven en The Graph y existe el riesgo de que su APY (Rentabilidad anualizada) sea más bajo de lo esperado debido a la dinámica del mercado que recién está empezando. -2. Cuando un curador ancla sus GRT en un subgrafo, deberá pagar un impuesto de curación equivalente al 1%. Esta tarifa se quema y el resto se deposita en el suministro de reserva de la curva de vinculación. -3. Cuando los curadores queman sus acciones para retirar los GRT, se reducirá la participación de GRT de las acciones restantes. Ten en cuenta que, en algunos casos, los curadores pueden decidir quemar sus acciones, **todas al mismo tiempo**. Esta situación puede ser común si un desarrollador de dApp deja de actualizar la aplicación, no sigue consultando su subgrafo o si falla el mismo. Como resultado, es posible que los curadores solo puedan retirar una fracción de sus GRT iniciales. Si buscas un rol dentro red que conlleve menos riesgos, consulta \[Delegators\](/delegating). +2. Cuando un curador señala sus GRT en un subgrafo, deberá pagar un impuesto de curación equivalente al 1%. Esta tarifa se quema y el resto se deposita en el suministro de reserva de la bonding curve. +3. Cuando los Curadores queman sus acciones para retirar los GRT, se reducirá la participación de GRT de las acciones restantes. Ten en cuenta que, en algunos casos, los Curadores pueden decidir quemar sus acciones, **todas al mismo tiempo**. Esta situación puede ser común si un desarrollador de dApps deja de actualizar la aplicación, no sigue versionando o mejorandoo su subgrafo o si falla el mismo. Como resultado, es posible que los Curadores solo puedan retirar una fracción de sus GRT iniciales. Si buscas un rol dentro de la red que conlleve menos riesgos, consulta [Delegators](/network/delegating). 4. Un subgrafo puede fallar debido a un error. Un subgrafo fallido no acumula tarifas de consulta. Como resultado, tendrás que esperar hasta que el desarrollador corrija el error e implemente una nueva versión. - - Si estás suscrito a la versión más reciente de un subgrafo, tus acciones se migrarán automáticamente a esa nueva versión. Esto incurrirá en una tarifa de curación del 0.5%. - - Si has señalado en una versión de subgrafo específica y falla, tendrás que quemar manualmente tus acciones de curación. Ten en cuenta que puedes recibir más o menos GRT de los que depositaste inicialmente en la curva de curación, y esto es un riesgo que todo curador acepta al empezar. Luego podrás firmar la nueva versión del subgrafo, incurriendo así en un impuesto de curación equivalente al 1%. + - Si estás suscrito a la versión más reciente de un subgrafo, tus acciones se migrarán automáticamente a esa nueva versión. Esto incurrirá un impuesto de curación del 0.5%. + - Si has señalado en una versión de subgrafo específica y esta falla, tendrás que quemar manualmente tus acciones de curación. Ten en cuenta que puedes recibir más o menos GRT de los que depositaste inicialmente en la curva de curación, y esto es un riesgo que todo Curador acepta al empezar. Luego podrás firmar la nueva versión del subgrafo, incurriendo así un impuesto de curación del 1%. ## Preguntas frecuentes sobre Curación -### 1. ¿Qué porcentaje obtienen los curadores de las comisiones por consulta? +### 1. ¿Qué porcentaje de las tasas de consulta ganan los curadores? -Al señalar un subgrafo, ganarás parte de todas las tarifas de consulta que genera dicho subgrafo. El 10% de todas las tarifas de consulta va destinado a los Curadores y se distribuye proporcionalmente en base a la participación de cada uno. Este 10% está sujeto a gobernanza. +Al señalar un subgrafo, ganarás parte de todas las tarifas de consulta que genera dicho subgrafo. El 10% de todas las tarifas de consulta va destinado a los Curadores y se distribuye en proporción a sus cuotas de curación. Este 10% está sujeto a gobernanza. ### 2. ¿Cómo decido qué subgrafos son de alta calidad para señalar? @@ -81,7 +81,7 @@ Encontrar subgrafos de alta calidad es una tarea compleja, pero se puede abordar ### 3. ¿Cuál es el costo de actualizar un subgrafo? -La migración de tus acciones de curación a una nueva versión de subgrafo incurre en un impuesto de curación del 1%. Los Curadores pueden optar por suscribirse a la versión más reciente de un subgrafo. Cuando las acciones de los curadores se migran automáticamente a una nueva versión, los curadores también pagarán la mitad del impuesto de curación, es decir el 0.5%, porque la mejora de los subgrafos es una acción on-chain que requiere cubrir los costos del gas. +La migración de tus cuotas de curación a una nueva versión de subgrafo incurre un impuesto de curación del 1%. Los Curadores pueden optar por suscribirse a la versión más reciente de un subgrafo. Cuando las cuotas de los Curadores se migran automáticamente a una nueva versión, los Curadores también pagarán la mitad del impuesto de curación, es decir el 0.5%, porque la mejora de los subgrafos es una acción on-chain que requiere cubrir los costos del gas. ### 4. ¿Con qué frecuencia puedo actualizar mi subgrafo? @@ -89,7 +89,7 @@ Se sugiere que no actualices tus subgrafos con demasiada frecuencia. Consulta la ### 5. ¿Puedo vender mis acciones de curación? -Las participaciones de un curador no se pueden "comprar" o "vender" como otros tokens ERC20 con los que seguramente estás familiarizado. Solo pueden anclar (crearse) o quemarse (destruirse) a lo largo de la curva de vinculación de un subgrafo en particular. La cantidad de GRT necesaria para generar una nueva señal y la cantidad de GRT que recibes cuando quemas tu señal existente, está determinada por esa curva de vinculación. Como curador, debes saber que cuando quemas tus acciones de curación para retirar GRT, puedes terminar con más o incluso con menos GRT de los que depositaste en un inicio. +Las cuotas de un Curador no se pueden "comprar" o "vender" como otros tokens ERC20 con los que seguramente estás familiarizado. Solo pueden acuñarse o quemarse a lo largo de la bonding curve de un subgrafo en particular. La cantidad de GRT necesaria para acuñar una nueva señal y la cantidad de GRT que recibes cuando quemas tu señal existente, está determinada por esa bonding curve. Como Curador, debes saber que cuando quemas tus cuotas de curación para retirar GRT, puedes terminar con más o incluso con menos GRT de los que depositaste en un inicio. ¿Sigues confundido? Te invitamos a echarle un vistazo a nuestra guía en un vídeo que aborda todo sobre la curación: diff --git a/website/pages/es/querying/distributed-systems.mdx b/website/pages/es/querying/distributed-systems.mdx index 7f64b52c66a8..26f8ce09bcb3 100644 --- a/website/pages/es/querying/distributed-systems.mdx +++ b/website/pages/es/querying/distributed-systems.mdx @@ -13,21 +13,21 @@ Considera este ejemplo de lo que puede ocurrir si un cliente pregunta a un Index 3. El indexador ingiere el bloque 9 4. El indexador ingiere el bloque 10A 5. Solicitud servida al cliente para el bloque 10A -6. El indexador detecta la reorganización a 10B y retrocede a 10A +6. El indexador detecta la reorganización a 10B y revierte 10A 7. Solicitud servida al cliente para el bloque 9 8. El indexador ingiere el bloque 10B 9. El indexador ingiere el bloque 11 10. Solicitud servida al cliente para el bloque 11 -Desde el punto de vista del indexador, las cosas avanzan lógicamente. El tiempo avanza, aunque tuvimos que hacer retroceder un uncle bloque y jugar el bloque bajo el consenso hacia adelante en la parte superior. En el camino, el Indexador sirve las peticiones utilizando el último estado que conoce en ese momento. +Desde el punto de vista del indexador, las cosas avanzan lógicamente. El tiempo avanza, aunque tuvimos que revertir un bloque uncle y jugar el bloque bajo consenso hacia adelante encima de él. En el camino, el Indexador sirve las peticiones utilizando el último estado que conoce en ese momento. Sin embargo, desde el punto de vista del cliente, las cosas parecen caóticas. El cliente observa que las respuestas fueron para los bloques 8, 10, 9 y 11 en ese orden. Lo llamamos el problema del "block wobble" (bamboleo del bloque). Cuando un cliente experimenta un bamboleo de bloques, los datos pueden parecer contradecirse a lo largo del tiempo. La situación se agrava si tenemos en cuenta que no todos los indexadores ingieren los últimos bloques de forma simultánea, y tus peticiones pueden ser dirigidas a varios indexadores. -Es responsabilidad del cliente y del servidor trabajar juntos para proporcionar datos coherentes al usuario. Hay que utilizar diferentes enfoques en función de la coherencia deseada, ya que no existe un programa adecuado para todos los problemas. +Es responsabilidad del cliente y del servidor trabajar juntos para proporcionar datos coherentes al usuario. Hay que utilizar diferentes enfoques en función de la consistencia deseada, ya que no existe un programa adecuado para todos los problemas. -Razonar las implicancias de los sistemas distribuidos es difícil, pero la solución puede no serlo! Hemos establecido APIs y patrones para ayudarte a navegar por algunos casos de uso comunes. Los siguientes ejemplos ilustran estos patrones pero eluden los detalles requeridos por el código de producción (como el manejo de errores y la cancelación) para no ofuscar las ideas principales. +Razonar las implicaciones de los sistemas distribuidos es difícil, pero la solución puede no serlo! Hemos establecido APIs y patrones para ayudarte a navegar por algunos casos de uso comunes. Los siguientes ejemplos ilustran estos patrones pero eluden los detalles requeridos por el código de producción (como el manejo de errores y la cancelación) para no ofuscar las ideas principales. -## Sondeo para obtener datos actualizados +## Sondeo de datos actualizados The Graph proporciona la API `block: { number_gte: $minBlock }`, que asegura que la respuesta es para un solo bloque igual o superior a `$minBlock`. Si la petición se realiza a una instancia de `graph-node` y el bloque mínimo no está aún sincronizado, `graph-node` devolverá un error. Si `graph-node` ha sincronizado el bloque mínimo, ejecutará la respuesta para el último bloque. Si la solicitud se hace a un Edge & Node Gateway, el Gateway filtrará los Indexadores que aún no hayan sincronizado el bloque mínimo y hará la solicitud para el último bloque que el Indexador haya sincronizado. @@ -76,7 +76,7 @@ async function updateProtocolPaused() { ## Obtención de un conjunto de elementos relacionados -Otro caso de uso es la recuperación de un conjunto grande o, más generalmente, la recuperación de elementos relacionados a través de múltiples solicitudes. A diferencia del caso del sondeo (en el que la coherencia deseada era avanzar en el tiempo), la coherencia deseada es para un único punto en el tiempo. +Otro caso de uso es la recuperación de un conjunto grande o, más generalmente, la recuperación de elementos relacionados a través de múltiples solicitudes. A diferencia del caso del sondeo (en el que la consistencia deseada era avanzar en el tiempo), la consistencia deseada es para un único punto en el tiempo. Aquí utilizaremos el argumento `block: { hash: $blockHash }` para anclar todos nuestros resultados al mismo bloque. @@ -131,4 +131,4 @@ async function getDomainNames() { } ``` -Ten en cuenta que en caso de reorganización, el cliente tendrá que reintentar desde la primera solicitud para actualizar el hash del bloque a un non-uncle bloque. +Ten en cuenta que en caso de reorganización, el cliente tendrá que reintentar desde la primera solicitud para actualizar el hash del bloque a un bloque no-uncle. diff --git a/website/pages/es/querying/managing-api-keys.mdx b/website/pages/es/querying/managing-api-keys.mdx index ee7c274bca10..fe4b6c3afa6e 100644 --- a/website/pages/es/querying/managing-api-keys.mdx +++ b/website/pages/es/querying/managing-api-keys.mdx @@ -1,26 +1,26 @@ --- -title: Managing your API keys +title: Administración de tus claves API --- -Regardless of whether you’re a dapp developer or a subgraph developer, you’ll need to manage your API keys. This is important for you to be able to query subgraphs because API keys make sure the connections between application services are valid and authorized. This includes authenticating the end user and the device using the application. +Independientemente de si eres un developer de aplicaciones descentralizadas (apps) o un developer de subgrafos, necesitarás administrar tus claves de API. Esto es importante para que puedas consultar los subgrafos porque las claves API aseguran que las conexiones entre los servicios de la aplicación sean válidas y están autorizadas. Esto incluye la autenticación del usuario final y del dispositivo que utiliza la aplicación. -The Studio will list out existing API keys, which will give you the ability to manage or delete them. +El Studio mostrará las claves API existentes, lo que te permitirá administrarlas o eliminarlas. -1. The **Overview** section will allow you to: - - Edit your key name - - Regenerate API keys - - View the current usage of the API key with stats: - - Number of queries - - Amount of GRT spent -2. Under **Security**, you’ll be able to opt into security settings depending on the level of control you’d like to have over your API keys. In this section, you can: - - View and manage the domain names authorized to use your API key - - Assign subgraphs that can be queried with your API key -3. Under **Indexer Preference**, you’ll be able to set different preferences for Indexers who are indexing subgraphs that your API key is used for. You can assign up to 5 points for each of these: - - **Fastest Speed**: Time between the query and the response from an indexer. If you mark this as important we will optimize for fast indexers. - - **Lowest Price**: The amount paid per query. If you mark this as important we will optimize for the less expensive indexers. - - **Data Freshness**: How recent the latest block an indexer has processed for the subgraph you are querying. If you mark this as important we will optimize to find the indexers with the freshest data. - - **Economic Security**: The amount of GRT an indexer can lose if they respond incorrectly to your query. If you mark this as important we will optimize for indexers with a large stake. -4. Under **Budget**, you’ll be able to update the maximum price per query. Note that we have a dynamic setting for that that's based on a volume discounting algorithm. **We strongly recommend using the default settings unless you are experiencing a specific problem.** Otherwise, you can update it under "Set a custom maximum budget". On this page you can also view different KPIs (in GRT and USD): - - Average cost per query - - Failed queries over max price - - Most expensive query +1. La sección ** Visión General ** te permitirá: + - Editar el nombre de tu clave + - Regenerar las claves API + - Ver el uso actual de la clave API con estadísticas: + - Número de consultas + - Cantidad de GRT gastado +2. En **Seguridad**, podrás optar por la configuración de seguridad en función del nivel de control que quieras tener sobre tus claves API. En esta sección, puedes: + - Ver y administrar los nombres de dominio autorizados a utilizar tu clave API + - Asignar subgrafos que puedan ser consultados con tu clave API +3. En **Preferencias de los Indexadores**, podrás establecer diferentes preferencias para los Indexadores que indexan los subgrafos para los que se utiliza tu clave API. Puedes asignar hasta 5 puntos para cada uno de ellos: + - **Velocidad Más Rápida**: Tiempo entre la consulta y la respuesta de un Indexador. Si marcas esto como importante, optimizaremos para que los Indexadores sean rápidos. + - **Precio Más Bajo**: La cantidad pagada por consulta. Si marcas esto como importante, optimizaremos para los Indexadores menos costosos. + - **Frescura de los Datos**: que tan reciente es el último bloque que un Indexador ha procesado para el subgrafo que estás consultando. Si marcas esto como importante, optimizaremos para encontrar los Indexadores con los datos más frescos. + - **Seguridad Económica**: La cantidad de GRT que un Indexador puede perder si responde incorrectamente a tu consulta. Si marcas esto como importante, optimizaremos para los Indexadores con un gran stake. +4. En ** Presupuesto**, podrás actualizar el precio máximo por consulta. Ten en cuenta que tenemos una configuración dinámica para eso que se basa en un algoritmo de descuento por volumen. **Te recomendamos encarecidamente que utilices la configuración por defecto a menos que tengas un problema específico.** De lo contrario, puedes actualizarla en "Establecer un presupuesto máximo personalizado". En esta página también puedes ver diferentes KPIs (en GRT y USD): + - Costo promedio por consulta + - Consultas fallidas sobre el precio máximo + - Consulta más cara diff --git a/website/pages/es/querying/querying-best-practices.mdx b/website/pages/es/querying/querying-best-practices.mdx index 237316ef494f..96a131e6a35f 100644 --- a/website/pages/es/querying/querying-best-practices.mdx +++ b/website/pages/es/querying/querying-best-practices.mdx @@ -1,22 +1,22 @@ --- -title: Querying Best Practices +title: Mejores Prácticas para Consultas --- -The Graph provides a decentralized way to query data from blockchains. +The Graph proporciona una forma descentralizada de consultar datos de la blockchain. -The Graph network's data is exposed through a GraphQL API, making it easier to query data with the GraphQL language. +Los datos de The Graph Network se exponen a través de una API GraphQL, lo que facilita la consulta de datos con el lenguaje GraphQL. -This page will guide you through the essential GraphQL language rules and GraphQL queries best practices. +Esta página te guiará a través de las reglas esenciales del lenguaje GraphQL y las mejores prácticas de consulta GraphQL. --- -## Querying a GraphQL API +## Consulta de una API GraphQL -### The anatomy of a GraphQL query +### Anatomía de una consulta GraphQL -Unlike REST API, a GraphQL API is built upon a Schema that defines which queries can be performed. +A diferencia de la API REST, una API GraphQL se basa en un esquema que define las consultas que se pueden realizar. -For example, a query to get a token using the `token` query will look as follows: +Por ejemplo, una consulta para obtener un token utilizando la consulta de `token` tendrá el siguiente aspecto: ```graphql query GetToken($id: ID!) { @@ -27,7 +27,7 @@ query GetToken($id: ID!) { } ``` -which will return the following predictable JSON response (_when passing the proper `$id` variable value_): +que devolverá la siguiente respuesta JSON predecible (_al pasar el valor adecuado de la variable `$id`_): ```json { @@ -38,9 +38,9 @@ which will return the following predictable JSON response (_when passing the pro } ``` -GraphQL queries use the GraphQL language, which is defined upon [a specification](https://spec.graphql.org/). +Las consultas GraphQL utilizan el lenguaje GraphQL, que se define a partir de [una especificación](https://spec.graphql.org/). -The above `GetToken` query is composed of multiple language parts (replaced below with `[...]` placeholders): +La consulta `GetToken` anterior se compone de varias partes lingüísticas (sustituidas a continuación por marcadores de posición `[...]`): ```graphql query [operationName]([variableName]: [variableType]) { @@ -52,28 +52,41 @@ query [operationName]([variableName]: [variableType]) { } ``` -While the list of syntactic do's and don'ts is long, here are the essential rules to keep in mind when it comes to writing GraphQL queries: +Aunque la lista de lo que se debe y no se debe hacer sintácticamente es larga, estas son las reglas esenciales que hay que tener en cuenta a la hora de escribir consultas GraphQL: -- Each `queryName` must only be used once per operation. -- Each `field` must be used only once in a selection (we cannot query `id` twice under `token`) -- Some `field`s or queries (like `tokens`) return complex types that require a selection of sub-field. Not providing a selection when expected (or providing one when not expected - for example, on `id`) will raise an error. To know a field type, please refer to [The Graph Explorer](/network/explorer). -- Any variable assigned to an argument must match its type. -- In a given list of variables, each of them must be unique. -- All defined variables must be used. +- Cada `queryName` sólo debe utilizarse una vez por operación. +- Cada `field` debe utilizarse una sola vez en una selección (no podemos consultar el `id` dos veces bajo `token`) +- Algunos `field` o consultas (como los `tokens`) devuelven tipos complejos que requieren una selección de sub-field. No proporcionar una selección cuando se espera (o proporcionarla cuando no se espera - por ejemplo, en `id`) generará un error. Para conocer un tipo de campo, consulta [The Graph Explorer](/network/explorer). +- Cualquier variable asignada a un argumento debe coincidir con su tipo. +- En una lista dada de variables, cada una de ellas debe ser única. +- Deben utilizarse todas las variables definidas. -Failing to follow the above rules will end with an error from the Graph API. +Si no se siguen las reglas anteriores, se producirá un error de la API Graph. -For a complete list of rules with code examples, please look at our GraphQL Validations guide. +Para obtener una lista completa de reglas con ejemplos de código, consulta nuestra guía de Validaciones GraphQL.
-### Sending a query to a GraphQL API +### Envío de una consulta a una API GraphQL -GraphQL is a language and set of conventions that transport over HTTP. +GraphQL es un lenguaje y un conjunto de convenciones que transportan sobre HTTP. -It means that you can query a GraphQL API using standard `fetch` (natively or via `cross-undici-fetch` or `isomorphic-fetch`) as follows: +Significa que puede consultar una API GraphQL utilizando `fetch` estándar (de forma nativa o a través de `@whatwg-node/fetch` o `isomorphic-fetch`). + +Sin embargo, como se indica en ["Querying from an Application"](/querying/querying-from-an-application), te recomendamos que utilices nuestro `graph-client`, que admite features exclusivos como: + +- Manejo de subgrafos cross-chain: Consulta de varios subgrafos en una sola consulta +- [Automatic Block Tracking](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md) +- [Automatic Pagination](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md) +- Resultado completamente tipificado + +
+ +He aquí cómo consultar The Graph con `graph-client`: ```tsx +import { execute } from '../.graphclient' + const query = ` query GetToken($id: ID!) { token(id: $id) { @@ -84,67 +97,28 @@ query GetToken($id: ID!) { ` const variables = { id: '1' } -const fetchResult = await fetch('http://example.com/graphql', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, variables }), -}) -const result = await fetchResult.json() -``` - -Another lightweight alternative, best for back-end use-cases, is the famous [`graphql-request` library](https://github.com/prisma-labs/graphql-request). - -This lightweight GraphQL client comes with the essential features to query a GraphQL API: - -- Mutations validation -- Support for file upload -- Batching -- Promise-based API -- TypeScript support - -
- -A complete GraphQL client is [URQL](https://formidable.com/open-source/urql/) which is available within Node.js, React/Preact, Vue, Svelte environments, with more advanced features: - -- Flexible cache system -- Extensible design (easing adding new capabilities on top of it) -- Lightweight bundle (~5x lighter than Apollo Client) -- Support for file uploads and offline mode - -
- -In the React ecosystem, [React Query](https://react-query.tanstack.com/graphql) brings a lightweight and agnostic solution for GraphQL. - -React Query is a great candidate if you are looking for an easy-to-use and lightweight multipurpose client (GraphQL-capable) that provides essential features such as: - -- Powerful cache (background refresh, window-focus refreshing) -- Advanced querying pattern (parallel queries, dependent queries, prefetching) -- UX patterns: optimistic updates, scroll restoration -- Great dev tools - -
- -Finally, Apollo Client is the ubiquitous GraphQL client on the front-end ecosystem. +async function main() { + const result = await execute(query, variables) + // `result` is fully typed! + console.log(result) +} -Available for React, Angular, Vue, Ember, iOS, and Android, Apollo Client, although the heaviest clients, brings many features to build advanced UI on-top of GraphQL: +main() +``` -- advanced error handling -- pagination -- data prefetching -- optimistic UI -- local state management +En ["Querying from an Application"](/querying/querying-from-an-application) se tratan más alternativas de cliente GraphQL.
-Now that we covered the basic rules of GraphQL queries syntax, let's now look at the best practices of GraphQL query writing. +Ahora que hemos cubierto las reglas básicas de la sintaxis de las consultas GraphQL, veamos las mejores prácticas de escritura de consultas GraphQL. --- -## Writing GraphQL queries +## Escribir consultas GraphQL -### Always write static queries +### Escribe siempre consultas estáticas -A common (bad) practice is to dynamically build query strings as follows: +Una práctica común (mala) es construir dinámicamente las strings de consulta de la siguiente manera: ```tsx const id = params.id @@ -160,14 +134,14 @@ query GetToken { // Execute query... ``` -While the above snippet produces a valid GraphQL query, **it has many drawbacks**: +Aunque el fragmento anterior produce una consulta GraphQL válida, **tiene muchos inconvenientes**: -- it makes it **harder to understand** the query as a whole -- developers are **responsible for safely sanitizing the string interpolation** -- not sending the values of the variables as part of the request parameters **prevent possible caching on server-side** -- it **prevents tools from statically analyzing the query** (ex: Linter, or type generations tools) +- **Dificulta la comprensión** de la consulta en su conjunto +- Los desarrolladores son **responsables de sanear de forma segura la interpolación de strings** +- No enviar los valores de las variables como parte de los parámetros de la solicitud para evitar un posible almacenamiento en caché en el servidor +- **Impide que las herramientas analicen estáticamente la consulta** (por ejemplo, Linter o las herramientas de generación de tipos) -For this reason, it is recommended to always write queries as static strings: +Por este motivo, se recomienda escribir siempre las consultas como strings estáticas: ```tsx import { execute } from 'your-favorite-graphql-client' @@ -189,18 +163,18 @@ const result = await execute(query, { }) ``` -Doing so brings **many advantages**: +Hacerlo así conlleva **muchas ventajas**: -- **Easy to read and maintain** queries -- The GraphQL **server handles variables sanitization** -- **Variables can be cached** at server-level -- **Queries can be statically analyzed by tools** (more on this in the following sections) +- Consultas **fáciles de leer y mantener** +- El servidor GraphQL se **encarga de la limpieza de las variables** +- **Las variables pueden almacenarse en caché** a nivel de servidor +- **Las consultas pueden ser analizadas estáticamente por herramientas** (más información al respecto en las secciones siguientes) -**Note: How to include fields conditionally in static queries** +**Nota: Cómo incluir campos condicionalmente en consultas estáticas** -We might want to include the `owner` field only on a particular condition. +Es posible que queramos incluir el campo `owner` solo en una condición concreta. -For this, we can leverage the `@include(if:...)` directive as follows: +Para ello, podemos aprovechar la directiva `@include(if:...)` de la siguiente manera: ```tsx import { execute } from 'your-favorite-graphql-client' @@ -223,23 +197,23 @@ const result = await execute(query, { }) ``` -Note: The opposite directive is `@skip(if: ...)`. +Nota: La directiva opuesta es `@skip(if: ...)`.
-### Performance tips +### Consejos de rendimiento -**"Ask for what you want"** +**"Pide lo que quieras"** -GraphQL became famous for its "Ask for what you want" tagline. +GraphQL se hizo famoso por su lema "Pide lo que quieras". -For this reason, there is no way, in GraphQL, to get all available fields without having to list them individually. +Por esta razón, no hay forma, en GraphQL, de obtener todos los campos disponibles sin tener que listarlos individualmente. -When querying GraphQL APIs, always think of querying only the fields that will be actually used. +Cuando consultes las API GraphQL, piensa siempre en consultar solo los campos que se utilizarán realmente. -A common cause of over-fetching is collections of entities. By default, queries will fetch 100 entities in a collection, which is usually much more than what will actually be used, e.g., for display to the user. Queries should therefore almost always set first explicitly, and make sure they only fetch as many entities as they actually need. This applies not just to top-level collections in a query, but even more so to nested collections of entities. +Una causa común de sobrecarga son las colecciones de entidades. Por defecto, las consultas obtienen 100 entidades de una colección, lo que suele ser mucho más de lo que realmente se utilizará, por ejemplo, para mostrarlas al usuario. Por lo tanto, las consultas casi siempre deben establecerse explícitamente en primer lugar, y asegurarse de que sólo obtienen tantas entidades como las que realmente necesitan. Esto se aplica no sólo a las colecciones de primer nivel de una consulta, sino también a las colecciones anidadas de entidades. -For example, in the following query: +Por ejemplo, en la siguiente consulta: ```graphql query listTokens { @@ -254,13 +228,13 @@ query listTokens { } ``` -The response could contain 100 transactions for each of the 100 tokens. +La respuesta podría contener 100 transacciones para cada uno de los 100 tokens. -If the application only needs 10 transactions, the query should explicitly set `first: 10` on the transactions field. +Si la aplicación solo necesita 10 transacciones, la consulta debe establecer explícitamente `first: 10` en el campo transacciones. -**Combining multiple queries** +**Combinar varias consultas** -Your application might require querying multiple types of data as follows: +Su aplicación puede requerir la consulta de varios tipos de datos, como se indica a continuación: ```graphql import { execute } from "your-favorite-graphql-client" @@ -290,9 +264,9 @@ const [tokens, counters] = Promise.all( ) ``` -While this implementation is totally valid, it will require two round trips with the GraphQL API. +Aunque esta implementación es totalmente válida, requerirá dos viajes de ida y vuelta con la API GraphQL. -Fortunately, it is also valid to send multiple queries in the same GraphQL request as follows: +Afortunadamente, también es válido enviar múltiples consultas en la misma petición GraphQL de la siguiente manera: ```graphql import { execute } from "your-favorite-graphql-client" @@ -313,15 +287,15 @@ query GetTokensandCounters { const { result: { tokens, counters } } = execute(query) ``` -This approach will **improve the overall performance** by reducing the time spent on the network (saves you a round trip to the API) and will provide a **more concise implementation**. +Este enfoque **mejorará el rendimiento general** al reducir el tiempo empleado en la red (le ahorrará un viaje de ida y vuelta a la API) y proporcionará **una implementación más concisa**.
-### Leverage GraphQL Fragments +### Aprovechar los GraphQL Fragments -A helpful feature to write GraphQL queries is GraphQL Fragment. +Una función útil para escribir consultas GraphQL es GraphQL Fragment. -Looking at the following query, you will notice that some fields are repeated across multiple Selection-Sets (`{ ... }`): +Si observas la siguiente consulta, te darás cuenta de que algunos campos se repiten en varios conjuntos de selección (`{ ... }`): ```graphql query { @@ -341,12 +315,12 @@ query { } ``` -Such repeated fields (`id`, `active`, `status`) bring many issues: +Estos campos repetidos (`id`, `active`, `status`) plantean muchos problemas: -- harder to read for more extensive queries -- when using tools that generate TypeScript types based on queries (_more on that in the last section_), `newDelegate` and `oldDelegate` will result in two distinct inline interfaces. +- más difícil de leer para consultas más extensas +- cuando se utilizan herramientas que generan tipos TypeScript basados en consultas (_más sobre esto en la última sección_), `newDelegate` y `oldDelegate` darán como resultado dos interfaces en línea distintas. -A refactored version of the query would be the following: +Una versión refactorizada de la consulta sería la siguiente: ```graphql query { @@ -370,17 +344,17 @@ fragment DelegateItem on Transcoder { } ``` -Using GraphQL `fragment` will improve readability (especially at scale) but also will result in better TypeScript types generation. +Usar el `fragment` GraphQL mejorará la legibilidad (especialmente a escala) pero también resultará en una mejor generación de tipos TypeScript. -When using the types generation tool, the above query will generate a proper `DelegateItemFragment` type (_see last "Tools" section_). +Al utilizar la herramienta de generación de tipos, la consulta anterior generará un tipo `DelegateItemFragment` adecuado (_véase la última sección "Herramientas"_).
-### GraphQL Fragment do's and don'ts +### Qué hacer y qué no hacer con los GraphQL Fragments -**Fragment base must be a type** +**La base del Fragment debe ser de tipo** -A Fragment cannot be based on a non-applicable type, in short, **on type not having fields**: +Un Fragment no puede basarse en un tipo no aplicable, en pocas palabras, **en un tipo que no tenga campos**: ```graphql fragment MyFragment on BigInt { @@ -388,13 +362,13 @@ fragment MyFragment on BigInt { } ``` -`BigInt` is a **scalar** (native "plain" type) that cannot be used as a fragment's base. +`BigInt` es un **scalar** (tipo "plano" nativo) que no puede utilizarse como base de un fragmento. -**How to spread a Fragment** +**Cómo difundir un Fragment** -Fragments are defined on specific types and should be used accordingly in queries. +Los Fragments se definen en tipos específicos y deben utilizarse en consecuencia en las consultas. -Example: +Ejemplo: ```graphql query { @@ -415,20 +389,20 @@ fragment VoteItem on Vote { } ``` -`newDelegate` and `oldDelegate` are of type `Transcoder`. +`newDelegate` y `oldDelegate` son de tipo `Transcoder`. -It is not possible to spread a fragment of type `Vote` here. +No es posible difundir aquí un Fragment de tipo `Vote`. -**Define Fragment as an atomic business unit of data** +**Definir el Fragment como una unidad de negocio atómica de datos** -GraphQL Fragment must be defined based on their usage. +Los GraphQL Fragment deben definirse en función de su uso. -For most use-case, defining one fragment per type (in the case of repeated fields usage or type generation) is sufficient. +Para la mayoría de los casos de uso, basta con definir un Fragment por tipo (en caso de uso repetido de campos o generación de tipos). -Here is a rule of thumb for using Fragment: +He aquí una regla general para utilizar Fragment: -- when fields of the same type are repeated in a query, group them in a Fragment -- when similar but not the same fields are repeated, create multiple fragments, ex: +- cuando se repiten campos del mismo tipo en una consulta, agruparlos en un Fragment +- cuando se repiten campos similares pero no iguales, crear varios Fragments, ej: ```graphql # base fragment (mostly used in listing) @@ -451,121 +425,55 @@ fragment VoteWithPoll on Vote { --- -## The essential tools +## Las herramientas esenciales -### GraphQL web-based explorers +### Exploradores web GraphQL -Iterating over queries by running them in your application can be cumbersome. For this reason, don't hesitate to use [The Graph Explorer](https://thegraph.com/explorer) to test your queries before adding them to your application. The Graph Explorer will provide you a preconfigured GraphQL playground to test your queries. +Iterar sobre las consultas ejecutándolas en su aplicación puede ser engorroso. Por esta razón, no dudes en utilizar [The Graph Explorer](https://thegraph.com/explorer) para probar tus consultas antes de añadirlas a tu aplicación. El Graph Explorer le proporcionará un playgrpuns GraphQL preconfigurado para probar tus consultas. -If you are looking for a more flexible way to debug/test your queries, other similar web-based tools are available such as [Altair](https://altair.sirmuel.design/) and [GraphiQL](https://graphiql-online.com/graphiql). +Si buscas una forma más flexible de depurar/probar tus consultas, existen otras herramientas similares basadas en web, como [Altair](https://altair.sirmuel.design/) y [GraphiQL](https://graphiql-online.com/graphiql).
### GraphQL Linting -In order to keep up with the mentioned above best practices and syntactic rules, it is highly recommended to use the following workflow and IDE tools. +Con el fin de mantenerse al día con las mejores prácticas y reglas sintácticas mencionadas anteriormente, es muy recomendable utilizar las siguientes herramientas de flujo de trabajo e IDE. **GraphQL ESLint** -[GraphQL ESLint](https://github.com/dotansimha/graphql-eslint) will help you stay on top of GraphQL best practices with zero effort. +[GraphQL ESLint](https://github.com/dotansimha/graphql-eslint) te ayudará a mantenerte al tanto de las mejores prácticas de GraphQL con cero esfuerzo. -[Setup the "operations-recommended"](https://github.com/dotansimha/graphql-eslint#available-configs) config will enforce essential rules such as: +La configuración [Setup the "operations-recomended"](https://github.com/dotansimha/graphql-eslint#available-configs) hará cumplir reglas esenciales como: -- `@graphql-eslint/fields-on-correct-type`: is a field used on a proper type? -- `@graphql-eslint/no-unused variables`: should a given variable stay unused? -- and more! +- `@graphql-eslint/fields-on-correct-type:` ¿se utiliza un campo en un tipo correcto? +- `@graphql-eslint/no-unused variables`: ¿debe una variable determinada permanecer sin usar? +- ¡y mucho más! -This will allow you to **catch errors without even testing queries** on the playground or running them in production! +Esto te permitirá **detectar errores sin ni siquiera probar las consultas** en el playground o ejecutarlas en producción!
-### IDE plugins +### Plugins IDE -**VSCode and GraphQL** +**VSCode y GraphQL** -The [GraphQL VSCode extension](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) is an excellent addition to your development workflow to get: +La [GraphQL VSCode extension](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) es una excelente adición a su flujo de trabajo de desarrollo para obtener: -- syntax highlighting -- autocomplete suggestions -- validation against schema -- snippets -- go to definition for fragments and input types +- resaltado de sintaxis +- sugerencias de autocompletar +- validación según el esquema +- fragmentos +- ir a la definición de fragments y tipos de entrada -If you are using `graphql-eslint`, the [ESLint VSCode extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) is a must-have to visualize errors and warnings inlined in your code correctly. +Si utilizas `graphql-eslint`, la [ESLint VSCode extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) es imprescindible para visualizar correctamente los errores y advertencias que aparecen en el código. -**WebStorm/Intellij and GraphQL** +**WebStorm/Intellij y GraphQL** -The [JS GraphQL plugin](https://plugins.jetbrains.com/plugin/8097-graphql/) will significantly improve your experience while working with GraphQL by providing: - -- syntax highlighting -- autocomplete suggestions -- validation against schema -- snippets - -More information on this [WebStorm article](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/) that showcases all the plugin's main features. - -
- -### TypeScript types generation - -Finally, the best GraphQL experience is reached when the TypeScript data types are generated from the defined GraphQL queries, as follows: - -```tsx -import { execute } from 'your-favorite-graphql-client' -import { GetTokenQuery } from './generated.' - -const id = params.id -const query = ` -query GetToken($id: ID!) { - token(id: $id) { - id - owner - } -} -` - -const result: GetTokenQuery = await execute(query, { - variables: { - id, - }, -}) - -// `result` is typed! -``` - -Such a setup can be easily achieved by installing and configuring [GraphQL Code Generator](https://www.graphql-code-generator.com/docs/getting-started) as follows: - -```bash -yarn add graphql @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations -``` - -Then update your `package.json` (or similar script configuration setup) as follows: - -```tsx -{ - // ... - "scripts": { - // ... - "generate": "graphql-codegen", - // ... - } - // ... -} -``` - -Add the following configuration file to your project: - -```tsx -schema: "" -documents: './src/**/*.ts' -generates: - ./generated.ts: - plugins: - - typescript - - typescript-operations -``` +El [JS GraphQL plugin](https://plugins.jetbrains.com/plugin/8097-graphql/) mejorará significativamente tu experiencia mientras trabajas con GraphQL proporcionando: -Finally, by simply running the configured script (`yarn generate`), GraphQL Code Generator will generate the proper TypeScript types in the `generated.ts` file: +- resaltado de sintaxis +- sugerencias de autocompletar +- validación según el esquema +- fragmentos -- Each query will get a corresponding `[QueryName]Query` type (ex: `GetToken` → `GetTokenQuery` type -- Each fragment will get a corresponding `[FragmentName]Fragment` type (ex: `DelegateItem` → `DelegateItemFragment` type +Más información en [WebStorm article](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/) que muestra las principales características del plugin. diff --git a/website/pages/es/querying/querying-the-hosted-service.mdx b/website/pages/es/querying/querying-the-hosted-service.mdx index 12c254821851..dd8a5be2373f 100644 --- a/website/pages/es/querying/querying-the-hosted-service.mdx +++ b/website/pages/es/querying/querying-the-hosted-service.mdx @@ -1,14 +1,14 @@ --- -title: Consultas en el Sistema Alojado +title: Consultar el Servicio Alojado --- -Con el subgrafo desplegado, visita el [Servicio alojado](https://thegraph.com/hosted-service/) para abrir una interfaz [GraphiQL](https://github.com/graphql/graphiql) donde puedes explorar la API GraphQL desplegada para el subgrafo emitiendo consultas y viendo el esquema. +Con el subgrafo deployado, visita el [Servicio alojado](https://thegraph.com/hosted-service/) para abrir una interfaz [GraphiQL](https://github.com/graphql/graphiql) donde puedes explorar la API GraphQL deployada para el subgrafo emitiendo consultas y viendo el esquema. -A continuación se proporciona un ejemplo, pero por favor, consulta la [Query API](/querying/graphql-api) para obtener una referencia completa sobre cómo consultar las entidades del subgrafo. +A continuación se proporciona un ejemplo, pero consulta la [Query API](/querying/graphql-api) para obtener una referencia completa sobre cómo consultar las entidades del subgrafo. #### Ejemplo -Estas listas de consultas muestran todos los contadores que nuestro mapeo ha creado. Como sólo creamos uno, el resultado sólo contendrá nuestro único `default-counter`: +Estas listas de consultas muestran todos los contadores que nuestro mapping ha creado. Como sólo creamos uno, el resultado sólo contendrá nuestro único `default-counter`: ```graphql { @@ -21,7 +21,7 @@ Estas listas de consultas muestran todos los contadores que nuestro mapeo ha cre ## Utilización del Servicio Alojado -The Graph Explorer y su playground GraphQL es una forma útil de explorar y consultar los subgrafos desplegados en el Servicio Alojado. +The Graph Explorer y su playground GraphQL es una forma útil de explorar y consultar los subgrafos deployados en el Servicio Alojado. A continuación se detallan algunas de las principales características: diff --git a/website/pages/es/release-notes/assemblyscript-migration-guide.mdx b/website/pages/es/release-notes/assemblyscript-migration-guide.mdx index 8ea44ca600ff..bfc973f982dd 100644 --- a/website/pages/es/release-notes/assemblyscript-migration-guide.mdx +++ b/website/pages/es/release-notes/assemblyscript-migration-guide.mdx @@ -1,50 +1,50 @@ --- -title: Guia de Migracion de AssemblyScript +title: Guía de Migración de AssemblyScript --- -Hasta ahora, los subgrafos han utilizado una de las [first versions of AssemblyScript](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). Finalmente, hemos añadido soporte para la [newest one available](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉! 🎉 +Hasta ahora, los subgrafos han utilizado una de las [first versions of AssemblyScript](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). Finalmente, hemos añadido soporte para la [el más nuevo disponible](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉! 🎉 -Esto permitirá a los desarrolladores de subgrafos utilizar las nuevas características del lenguaje AS y la libreria estándar. +Esto permitirá a los desarrolladores de subgrafos utilizar las nuevas características del lenguaje AS y la librería estándar. -Esta guia es aplicable para cualquiera que use `graph-cli`/`graph-ts` bajo la version `0.22.0`. Si ya estás en una versión superior (o igual) a esa, ya has estado usando la versión `0.19.10` de AssemblyScript 🙂 +Esta guía es aplicable para cualquiera que use `graph-cli`/`graph-ts` bajo la versión `0.22.0`. Si ya estás en una versión superior (o igual) a esa, has estado usando la versión `0.19.10` de AssemblyScript 🙂 > Nota: A partir de `0.24.0`, `graph-node` puede soportar ambas versiones, dependiendo del `apiVersion` especificado en el manifiesto del subgrafo. -## Caracteristicas +## Características ### Nueva Funcionalidad -- `TypedArray`s ahora puede construirse desde `ArrayBuffer`s usando el [nuevo `wrap` metodo estatico](https://www.assemblyscript.org/stdlib/typedarray.html#static-members) ([v0.8.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.8.1)) +- `TypedArray`s ahora puede construirse desde `ArrayBuffer`s usando el [nuevo `wrap` método estático](https://www.assemblyscript.org/stdlib/typedarray.html#static-members) ([v0.8.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.8.1)) - Nuevas funciones de la biblioteca estándar: `String#toUpperCase`, `String#toLowerCase`, `String#localeCompare`and `TypedArray#set` ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Se agrego soporte para x instanceof GenericClass ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) -- Se agrego `StaticArray`, una mas eficiente variante de array ([v0.9.3](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.3)) -- Se agrego `Array#flat` ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -- Se implemento el argumento `radix` en `Number#toString` ([v0.10.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.1)) -- Se agrego soporte para los separadores en los literales de punto flotante ([v0.13.7](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.13.7)) -- Se agrego soporte para las funciones de primera clase ([v0.14.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.0)) +- Se agregó soporte para x instanceof GenericClass ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) +- Se agregó `StaticArray`, una más eficiente variante de array ([v0.9.3](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.3)) +- Se agregó `Array#flat` ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- Se implementó el argumento `radix` en `Number#toString` ([v0.10.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.1)) +- Se agregó soporte para los separadores en los literales de punto flotante ([v0.13.7](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.13.7)) +- Se agregó soporte para las funciones de primera clase ([v0.14.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.0)) - Se agregaron builtins: `i32/i64/f32/f64.add/sub/mul` ([v0.14.13](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.13)) -- Se implemento `Array/TypedArray/String#at` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) -- Se agrego soporte para las plantillas de strings literales ([v0.18.17](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.17)) -- Se agrego `encodeURI(Component)` y `decodeURI(Component)` ([v0.18.27](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.27)) -- Se agrego `toString`, `toDateString` and `toTimeString` to `Date` ([v0.18.29](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.29)) -- Se agrego `toUTCString` para `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) -- Se agrego `nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) +- Se implementó `Array/TypedArray/String#at` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) +- Se agregó soporte para las plantillas de strings literales ([v0.18.17](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.17)) +- Se agregó `encodeURI(Component)` y `decodeURI(Component)` ([v0.18.27](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.27)) +- Se agregó `toString`, `toDateString` and `toTimeString` to `Date` ([v0.18.29](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.29)) +- Se agregó `toUTCString` para `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) +- Se agregó `nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) ### Optimizaciones -- `Math` funciones como `exp`, `exp2`, `log`, `log2` y `pow` fueron reemplazadas por variantes mas rapidas ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- Funciones `Math` como `exp`, `exp2`, `log`, `log2` y `pow` fueron reemplazadas por variantes más rápidas ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) - Optimizar ligeramente `Math.mod` ([v0.17.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.1)) - Caché de más accesos a campos en std Map y Set ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) - Optimizar para potencias de dos en `ipow32/64` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) ### Otros -- El tipo de un literal de array puede ahora inferirse a partir de su contenido ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- El tipo de un de array literal ahora puede inferirse a partir de su contenido ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) - Actualizado stdlib a Unicode 13.0.0 ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) ## ¿Cómo actualizar? -1. Cambiar tus asignaciones `apiVersion` en `subgraph.yaml` a `0.0.6`: +1. Cambiar tus mappings `apiVersion` en `subgraph.yaml` a `0.0.6`: ```yaml ... @@ -72,7 +72,7 @@ npm install --save-dev @graphprotocol/graph-cli@latest npm install --save @graphprotocol/graph-ts@latest ``` -4. Sigue el resto de la guía para arreglar los cambios que rompen el languaje. +4. Sigue el resto de la guía para arreglar los cambios que rompen el lenguaje. 5. Ejecuta `codegen` y `deploy` nuevamente. ## Rompiendo los esquemas @@ -98,7 +98,7 @@ if (maybeValue) { } ``` -O forzarlo asi: +O forzarlo así: ```typescript let maybeValue = load()! // rompiendo el runtime si el valor es nulo @@ -132,7 +132,7 @@ Tendrás que cambiar el nombre de las variables duplicadas si tienes una variabl ### Comparaciones Nulas -Al hacer la actualización en ut subgrafo, a veces pueden aparecer errores como estos: +Al hacer la actualización en un subgrafo, a veces pueden aparecer errores como estos: ```typescript ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' is not assignable to type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt'. @@ -141,7 +141,7 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i in src/mappings/file.ts(41,21) ``` -Para solucionarlo puedes simplemente cambiar la declaracion `if` por algo así: +Para solucionarlo puedes simplemente cambiar la declaración `if` por algo así: ```typescript if (!decimals) { @@ -162,7 +162,7 @@ let byteArray = new ByteArray(10) let uint8Array = byteArray as Uint8Array // equivalent to: byteArray ``` -Sin embargo, esto sólo funciona en dos casos: +Sin embargo, esto solo funciona en dos casos: - Casting de primitivas (entre tipos como `u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); - Upcasting en la herencia de clases (subclase → superclase) @@ -225,20 +225,20 @@ let bytes = new Bytes(2) changetype(bytes) // works :) ``` -Si sólo quieres eliminar la anulabilidad, puedes seguir usando el `as` operador (o `variable`), pero asegúrate de que el valor no puede ser nulo, de lo contrario se romperá. +Si solo quieres eliminar la anulabilidad, puedes seguir usando el `as` operador (o `variable`), pero asegúrate de que el valor no puede ser nulo, de lo contrario se romperá. ```typescript // eliminar anulabilidad let previousBalance = AccountBalance.load(balanceId) // AccountBalance | null if (previousBalance != null) { - return previousBalance as AccountBalance // safe remove null + return previousBalance as AccountBalance // sabe remove null } let newBalance = new AccountBalance(balanceId) ``` -Para el caso de la anulabilidad se recomienda echar un vistazo al [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks), hara que tu codigo sea mas limpio 🙂 +Para el caso de la anulabilidad se recomienda echar un vistazo al [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks), hará que tu código sea más limpio 🙂 También hemos añadido algunos métodos estáticos en algunos tipos para facilitar el casting, son: @@ -249,7 +249,7 @@ También hemos añadido algunos métodos estáticos en algunos tipos para facili ### Comprobación de anulabilidad con acceso a la propiedad -Para usar el [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks) puedes usar la declaracion `if` o el operador ternario (`?` and `:`) asi: +Para usar el [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks) puedes usar la declaración `if` o el operador ternario (`?` and `:`) asi: ```typescript let something: string | null = 'data' @@ -267,7 +267,7 @@ if (something) { } ``` -Sin embargo eso sólo funciona cuando estás haciendo el `if` / ternario en una variable, no en un acceso a una propiedad, como este: +Sin embargo eso solo funciona cuando estás haciendo el `if` / ternario en una variable, no en un acceso a una propiedad, como este: ```typescript class Container { @@ -415,7 +415,7 @@ total.amount = total.amount + BigInt.fromI32(1) ### Inicialización de las propiedades de la clase -Si exportas alguna clase con propiedades que son otras clases (declaradas por ti o por la libreria estándar) así: +Si exportas alguna clase con propiedades que son otras clases (declaradas por ti o por la librería estándar) así: ```typescript class Thing {} @@ -449,7 +449,7 @@ export class Something { } ``` -### Inicializacion de Array +### Inicialización de Array La clase `Array` sigue aceptando un número para inicializar la longitud de la lista, sin embargo hay que tener cuidado porque operaciones como `.push` en realidad aumentarán el tamaño en lugar de añadirlo al principio, por ejemplo: @@ -459,7 +459,7 @@ let arr = new Array(5) // ["", "", "", "", ""] arr.push('something') // ["", "", "", "", "", "something"] // size 6 :( ``` -Dependiendo de los tipos que estés utilizando, por ejemplo los anulables, y de cómo estés accediendo a ellos, podrías encontrarte con un error de ejecución como éste: +Dependiendo de los tipos que estés utilizando, por ejemplo los anulables, y de cómo estés accediendo a ellos, podrías encontrarte con un error de ejecución como este: ``` ERRO Handler skipped due to execution failure, error: Mapping aborted at ~lib/array.ts, line 110, column 40, with message: Element type must be nullable if array is holey wasm backtrace: 0: 0x19c4 - !~lib/@graphprotocol/graph-ts/index/format 1: 0x1e75 - !~lib/@graphprotocol/graph-ts/common/collections/Entity#constructor 2: 0x30b9 - !node_modules/@graphprotocol/graph-ts/global/global/id_of_type @@ -511,14 +511,14 @@ type MyEntity @entity { } ``` -Esto cambio debido a las diferencias de nulidad entre las versiones de AssemblyScript, y está relacionado con el archivo `src/generated/schema.ts` (ruta por defecto, puede que lo hayas cambiado). +Esto cambió debido a las diferencias de anulabilidad entre las versiones de AssemblyScript, y está relacionado con el archivo `src/generated/schema.ts` (ruta por defecto, puede que lo hayas cambiado). ### Otros - Alineado `Map#set` y `Set#add` con el spec, devolviendo `this` ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) - Las arrays ya no heredan de ArrayBufferView, sino que son distintas ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -- Las clases inicializadas a partir de literales de objetos ya no pueden definir un constructor ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- Las clases inicializadas a partir de objetos literales ya no pueden definir un constructor ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) - El resultado de una operación binaria `**` es ahora el entero denominador común si ambos operandos son enteros. Anteriormente, el resultado era un flotante como si se llamara a `Math/f.pow` ([v0.11.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.11.0)) -- Coercionar `NaN` a `false` cuando casting a `bool` ([v0.14.9](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.9)) -- Al desplazar un valor entero pequeño de tipo `i8`/`u8` o `i16`/`u16`, sólo los 3 o 4 bits menos significativos del valor RHS afectan al resultado, de forma análoga al resultado de un `i32.shl` que sólo se ve afectado por los 5 bits menos significativos del valor RHS. Ejemplo: `someI8 << 8` previamente producia el valor `0`, pero ahora produce `someI8` debido a enmascarar el RHS como `8 & 7 = 0` (3 bits) ([v0.17.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.0)) +- Coerción `NaN` a `false` cuando casting a `bool` ([v0.14.9](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.9)) +- Al desplazar un valor entero pequeño de tipo `i8`/`u8` o `i16`/`u16`, sólo los 3 o 4 bits menos significativos del valor RHS afectan al resultado, de forma análoga al resultado de un `i32.shl` que sólo se ve afectado por los 5 bits menos significativos del valor RHS. Ejemplo: `someI8 << 8` previamente producía el valor `0`, pero ahora produce `someI8` debido a enmascarar el RHS como `8 & 7 = 0` (3 bits) ([v0.17.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.0)) - Corrección de errores en las comparaciones de strings relacionales cuando los tamaños difieren ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) diff --git a/website/pages/hi/cookbook/grafting.mdx b/website/pages/hi/cookbook/grafting.mdx new file mode 100644 index 000000000000..f57e8984142b --- /dev/null +++ b/website/pages/hi/cookbook/grafting.mdx @@ -0,0 +1,186 @@ +--- +title: एक कॉन्ट्रैक्ट बदलें और उसका इतिहास ग्राफ्टिंग के साथ रखें +--- + +इस गाइड में, आप सीखेंगे कि मौजूदा सबग्राफ को ग्राफ्ट करके नए सबग्राफ कैसे बनाएं और तैनात करें। + +## ग्राफ्टिंग क्या है? + +ग्राफ्टिंग एक वर्तमान सब-ग्राफ के डाटा का दोबारा इस्तेमाल करता है और उसे बाद के ब्लॉक्स में इंडेक्स करना चालू कर देता है| यह विकास की प्रक्रिया में उपयोगी है क्यूंकि इसकी वजह से मैप्पिंग्स में छोटी-मोटी त्रुटियों से छुटकारा पाया जा सकता है या फिर एक मौजूदा सब-ग्राफ को विफल होने के बाद दोबारा चालू किया जा सकता है| साथ हीं, इसका इस्तेमाल ऐसे सब-ग्राफ में कोई खूबी जोड़ते वक़्त भी किया जा सकता है जिसमे शुरुआत से इंडेक्स करने में काफी लम्बा वक़्त लगता हो| + +ग्राफ्टेड सबग्राफ एक ग्राफक्यूएल स्कीमा का उपयोग कर सकता है जो बेस सबग्राफ के समान नहीं है, लेकिन इसके अनुकूल हो। यह अपने आप में एक मान्य सबग्राफ स्कीमा होना चाहिए, लेकिन निम्नलिखित तरीकों से बेस सबग्राफ के स्कीमा से विचलित हो सकता है: + +- यह इकाई के प्रकारों को जोड़ या हटा सकता है| +- यह इकाई प्रकारों में से गुणों को हटाता है| +- यह प्रभावहीन गुणों को इकाई प्रकारों में जोड़ता है| +- यह प्रभाव वाले गुणों को प्रभावहीन गुणों में बदल देता है| +- यह इनम्स में महत्व देता है| +- यह इंटरफेस जोड़ता या हटाता है| +- यह कि, किन इकाई प्रकारों के लिए इंटरफ़ेस लागू होगा, इसे बदल देता है| + +अधिक जानकारी के लिए आप देख सकते हैं: + +- [ग्राफ्टिंग](https://thegraph.com/docs/en/developing/creating-a-subgraph#grafting-onto-existing-subgraphs) + +इस अनुशिक्षण में हम एक बुनियादी उदहारण देखेंगे| हम एक मौजूदा कॉन्ट्रैक्ट को एक समान कॉन्ट्रैक्ट से बदल देंगे( नए एड्रेस के साथ, मगर सामान कोड). उसके बाद हम एक मौजूदा सब-ग्राफ एक "बेस" सब-ग्राफ में ग्राफ्ट कर देंगे नए कॉन्ट्रैक्ट की निगरानी करेगा| + +## एक मौजूदा सब-ग्राफ बनाना + +सब-ग्राफ बनाना द ग्राफ का एक अहम हिस्सा है, गहराई में [यहां](http://localhost:3000/en/cookbook/quick-start/)बताया गया है| इस अनुशिक्षां में दिए -ग्राफ को बनाने और डेप्लोये करने में सक्षम होने के लिए यह रेपो प्रदान की गयी है: + +- [सब-ग्राफ उदाहरण रेपो](https://github.com/t-proctor/grafting-tutorial) + +> नोट: सब-ग्राफ में इस्तेमाल किया गया कॉन्ट्रैक्ट निम्न [हैकथॉन आरम्भक](https://github.com/schmidsi/hackathon-starterkit) से लिया गया है| + +## सब ग्राफ मैनिफेस्ट की परिभाषा + +सब ग्राफ मैनिफेस्ट `subgraph.yaml` द्वारा सब-ग्राफ के डाटा सोर्स, ट्रिगर ऑफ़ इंटरेस्ट, और इन ट्रिगर के जवाब में सिस्टेमाल होने वाले फंक्शन्स की पहचान करता है| आपके द्वारा इस्तेमाल किये जाने वाले सब-ग्राफ मैनिफेस्ट का उदाहरण नीचे देखें: + +```yaml +specVersion: 0.0.4 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: goerli + source: + address: '0x4Ed995e775D3629b0566D2279f058729Ae6EA493' + abi: Lock + startBlock: 7674603 + 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` डाटा सोर्स वह ऐ बी आई और कॉन्ट्रैक्ट एड्रेस है जो कि हमे तब मिलेगा जब हम अपना कॉन्ट्रैक्ट संकलित और तैनात करते हैं| +- नेटवर्क क्वेरी किये जाने वाले इंडेक्स्ड नेटवर्क के अनुरूप होना चाहिए। चूँकि हम गोएर्ली टेस्ट नेट का इस्तेमाल क्र रहे हैं, नेटवर्क `goerli` +- `mapping` सेक्शन उन ट्रिगर ऑफ़ इंटरेस्ट और उनके जवाब में चलने वाले फंक्शन्स को परिभासित करता है| इस स्थिति में, हम `Withdrawal` फंक्शन को सुनते हैं और `handleWithdrawal` फंक्शन को कॉल करते हैं| + +## ग्राफ्टिंग मैनिफेस्ट की परिभाषा + +ग्राफ्टिंग करने के लिए मूल सब-ग्राफ मैनिफेस्ट में 2 नई चीज़ें जोड़ने की आवश्यकता है: + +```yaml +--- +features: + - grafting # feature name +graft: + base: Qm... # subgraph ID of base subgraph + block: 1502122 # block number +``` + +- `विषेशताएँ:` सभी इस्तेमाल किये गए [विषेशताओं के नामों](developing/creating-a-subgraph/#experimental-features) की सूची है| +- `graft:`: `base` सब-ग्राफ और उसके ऊपर ग्राफ्ट किये जाने वाले ब्लॉक का मैप है| `block` वह ब्लॉक संख्या है जहाँ से इंडेक्सिंग स्टार्ट करनी है| द ग्राफ बेस सब-ग्राफ तक के डाटा को कॉपी करके, जिसमे दिया हुआ ब्लॉक भी शामिल है, फिर आगे के नए सब-ग्राफ को उस ब्लॉक से इंडेक्स करना शुरू कर देता है| + +`base` और `block` मूल्यों को दो सब-ग्राफ्स को डेप्लॉय करके पता किया जा सकता है: एक बेस इंडेक्सिंग के लिए और एक ग्राफ्टिंग के लिए| + +## बेस सब-ग्राफ को तैनात करना + +1. [द ग्राफ स्टूडियो यू आई](https://thegraph.com/studio/) पर जायें और एक गोएर्ली टेस्ट नेट पर एक सब-ग्राफ बनाएं जिसका नाम `graft-example` होना चाहिए| +2. अपने सब-ग्राफ पेज पर `AUTH & DEPLOY` भाग में `graft-example` फोल्डर में दिए गए दिशा निर्देशों का पालन करें| +3. एक बार पूरा होने पर, सत्यापित करें की इंडेक्सिंग सही ढंग से हो गयी है| यदि आप निम्न कमांड ग्राफ प्लेग्राउंड में चलाते हैं + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +तो हमे कुछ ऐसा दिखता है: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0x13098b538a61837e9f29b32fb40527bbbe63c9120c250242b02b69bb42c287e5-5", + "amount": "0", + "when": "1664367528" + }, + { + "id": "0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498-3", + "amount": "0", + "when": "1664367648" + } + ] + } +} +``` + +एक बार आपका सत्यापित सब-ग्राफ ढंग से इंडेक्स हो जाता है तो आप बिना किसी देरी के अपना सब-ग्राफ को ग्राफ्टिंग से अपडेट कर सकते हैं| + +## ग्राफ्टिंग सब-ग्राफ तैनात करना + +ग्राफ्ट प्रतिस्तापित subgraph.yaml में एक नया कॉन्ट्रैक्ट एड्रेस होगा| यह तब हो सकता है जब आप अपना डैप अपडेट करें, कॉन्ट्रैक्ट को दोबारा तैनात करें, इत्यादि| + +1. [द ग्राफ स्टूडियो यू आई](https://thegraph.com/studio/) पर जायें और एक गोएर्ली टेस्ट नेट पर एक सब-ग्राफ बनाएं जिसका नाम `graft-replacement` होना चाहिए| +2. एक नया मैनिफेस्ट बनाएं| `subgraph.yaml`, `graph-replacement` के लिए एक अलग कॉन्ट्रैक्ट एड्रेस और नयी जानकारी, कि उसे कैसे ग्राफ्ट किया जाना चाहिए रखता है | यह `block` पुराने कॉन्ट्रैक्ट द्वारा [आखिरी बार मापी गयी गतिविधि](https://goerli.etherscan.io/tx/0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498) जिसकी फिलहाल हमें ज़रूरत है और पुराने कॉन्ट्रैक्ट का `बेस` हैं| `base` सब-ग्राफ आईडी मूल `graph-example` सब-ग्राफ उदहारण के लिए `डेप्लॉयमेंट आईडी` है| आप इसे द ग्राफ स्टूडियो यूआई में भी देख सकते है| +3. अपने सब-ग्राफ पेज पर `AUTH & DEPLOY` भाग में `graft-replacement` फोल्डर में दिए गए दिशा निर्देशों का पालन करें| +4. एक बार पूरा होने पर, सत्यापित करें की इंडेक्सिंग सही ढंग से हो गयी है| यदि आप निम्न कमांड ग्राफ प्लेग्राउंड में चलाते हैं + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +आपको यह वापस मिलना चाहिए: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0x13098b538a61837e9f29b32fb40527bbbe63c9120c250242b02b69bb42c287e5-5", + "amount": "0", + "when": "1664367528" + }, + { + "id": "0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498-3", + "amount": "0", + "when": "1664367648" + }, + { + "id": "0xb4010e4c76f86762beb997a13cf020231778eaf7c64fa3b7794971a5e6b343d3-22", + "amount": "0", + "when": "1664371512" + } + ] + } +} +``` + +आप देख सकते हैं कि `graft-replacement`सब-ग्राफ पुराने `graph-example` डाटा और नए कॉन्ट्रैक्ट के नए डाटा से इंडेक्सिंग कर रहा है| मूल सामग्री से दो `Withdrawal` गतिविधियां प्राप्त हुई थी| [गतिविधि 1](https://goerli.etherscan.io/tx/0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498) और [गतिविधि 2](https://goerli.etherscan.io/address/0x4ed995e775d3629b0566d2279f058729ae6ea493)| नए कॉन्ट्रैक्ट द्वारा एक `Withdrawal` गतिविधि [गतिविधि 3](https://goerli.etherscan.io/tx/0xb4010e4c76f86762beb997a13cf020231778eaf7c64fa3b7794971a5e6b343d3) के बाद प्राप्त हुई| पहले के दो इंडेक्स किये हुए ट्रांसक्शन (गतिविधि 1 और 2) और नया ट्रांसक्शन(गतिबिधि 3) को साथ में `graft-replacement` सब-ग्राफ में मिला दिया गया| + +बधाई हो! आपने सफलतापूर्वक एक सुब-ग्राफ को दूसरे में ग्राफ्ट कर लिया है| + +## अतिरिक्त संसाधन + +अगर आप ग्राफ्टिंग के साथ और अधिक अनुभव चाहते हैं तोह आपके लिए निम्न कुछ लोकप्रिय कॉन्ट्रैक्ट्स हैं: + +- [कर्व](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/templates/curve.template.yaml) +- [इ आर सी - 721](https://github.com/messari/subgraphs/blob/master/subgraphs/erc721-metadata/subgraph.yaml) +- [यूनीस्वैप](https://github.com/messari/subgraphs/blob/master/subgraphs/uniswap-v3/protocols/uniswap-v3/config/templates/uniswap.v3.template.yaml) + +ग्राफ में और अधिक विशेषज्ञता पाने के लिए, डेटासोर्स में और अधिक बदलाव लाने के तरीको के बारे में सोचने किए कोशिश करिये। विकल्प जैसे कि [Data Source Templates](developing/creating-a-subgraph/#data-source-templates) भी कुछ इसी प्रकार के कार्य कर सकते हैं + +> नोट: इस आर्टिकल में काफी सामग्री पहले से प्रकाशित [आरवीव आर्टिकल](/cookbook/arweave/) से ली गयी है| diff --git a/website/pages/hi/cookbook/migrating-a-subgraph.mdx b/website/pages/hi/cookbook/migrating-a-subgraph.mdx new file mode 100644 index 000000000000..8cdc17a0d328 --- /dev/null +++ b/website/pages/hi/cookbook/migrating-a-subgraph.mdx @@ -0,0 +1,219 @@ +--- +title: किसी मौजूदा सबग्राफ को ग्राफ़ नेटवर्क में माइग्रेट करना +--- + +## परिचय + +यह गाइड है कि कैसे अपने सबग्राफ को होस्टेड सर्विस से द ग्राफ के विकेंद्रीकृत नेटवर्क में माइग्रेट किया जाए। Opyn, UMA, mStable, Audius, PoolTogether, Livepeer, RAI, Enzyme, DODO, Pickle, और BadgerDAO जैसी परियोजनाओं के लिए द ग्राफ़ नेटवर्क में माइग्रेशन सफल रहा है, जो सभी नेटवर्क पर इंडेक्सर्स द्वारा दिए गए डेटा पर निर्भर हैं। ग्राफ़ के विकेन्द्रीकृत नेटवर्क पर अब 700 से अधिक सबग्राफ लाइव हैं, जो क्वेरी शुल्क उत्पन्न करते हैं और वेब3 डेटा को सक्रिय रूप से अनुक्रमित करते हैं। + +माइग्रेशन की प्रक्रिया तेज है और आपके सबग्राफ हमेशा उस विश्वसनीयता और प्रदर्शन से लाभान्वित होंगे जो आप केवल द ग्राफ नेटवर्क पर प्राप्त कर सकते हैं। + +### मान्यताओं + +- आप पहले से ही होस्ट की गई सेवा पर एक सबग्राफ तैनात कर चुके हैं। +- सबग्राफ ग्राफ़ नेटवर्क पर उपलब्ध (या बीटा में उपलब्ध) श्रृंखला को अनुक्रमित कर रहा है। +- सबग्राफ में IPFS या पूर्ण-पाठ खोज निर्भरताएँ नहीं हैं (ये अभी तक विकेंद्रीकृत नेटवर्क पर पूरी तरह से समर्थित नहीं हैं)। + +## किसी मौजूदा सबग्राफ को ग्राफ़ नेटवर्क में माइग्रेट करना + +> आप [सबग्राफ स्टूडियो](https://thegraph.com/studio/) में अपने सबग्राफ के लिए विशिष्ट आदेश प्राप्त कर सकते हैं। + +1. Graph-cli का नवीनतम संस्करण प्राप्त करें: + +```sh +npm install -g @graphprotocol/graph-cli +``` + +```sh +yarn global add @graphprotocol/graph-cli +``` + +पक्का करें कि आपका `apiVersion` subgraph.yaml में `0.0.5` या इससे बड़ा होना चहिए। + +2. सबग्राफ के मुख्य प्रोजेक्ट रिपॉजिटरी के अंदर, सबग्राफ को स्टूडियो पर तैनात करने और बनाने के लिए प्रमाणित करें: + +```sh +graph auth --studio +``` + +3. फाइलें उत्पन्न करें और सबग्राफ बनाएं: + +```sh +graph codegen && graph build +``` + +यदि आपके सबग्राफ में बिल्ड त्रुटियाँ हैं, तो [AssemblyScript माइग्रेशन गाइड](/release-notes/assemblyscript-migration-guide/) देखें। + +4. अपने वॉलेट के साथ [सबग्राफ स्टूडियो](https://thegraph.com/studio/) में साइन इन करें और सबग्राफ तैनात करें। आप अपने `` को Studio UI में ढूंढ सकते हैं, जो आपके सबग्राफ के नाम पर आधारित है। + +```sh +graph deploy --studio +``` + +5. स्टूडियो के खेल के मैदान पर क्वेरियों का परीक्षण करें। यहां [सुशी - मेननेट एक्सचेंज सबग्राफ](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&view=Playground) के कुछ उदाहरण दिए गए हैं: + +```sh +{ + users(first: 5) { + id + liquidityPositions { + id + } + } + bundles(first: 5) { + id + ethPrice + } +} +``` + +6. इस समय पर, आपका सबग्राफ अब सबग्राफ स्टूडियो पर तैनात है, लेकिन अभी तक विकेंद्रीकृत नेटवर्क पर प्रकाशित नहीं हुआ है। अब आप यह सुनिश्चित करने के लिए सबग्राफ का परीक्षण कर सकते हैं कि यह अस्थायी क्वेरी URL का उपयोग करके काम कर रहा है, जैसा कि ऊपर दाएं कॉलम के शीर्ष पर दिखाया गया है। जैसा कि इस नाम से पहले ही पता चलता है, यह एक अस्थायी URL है और इसे उत्पादन में इस्तेमाल नहीं किया जाना चाहिए। + +- प्रकाशन एक ऑन-चेन क्रिया है और इसके लिए एथेरियम में गैस की भुगतान करने के लिए की आवश्यकता होगी - लेनदेन का एक उदाहरण देखें [यहाँ](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b)। 100 gwei पर कीमतें लगभग 0.0425 ETH हैं। +- किसी भी समय आपको अपने सबग्राफ को अपग्रेड करने की आवश्यकता होगी, आपसे अपग्रेड शुल्क लिया जाएगा। अपग्रेड करना आपके मौजूदा सबग्राफ ऑन-चेन का एक और संस्करण प्रकाशित कर रहा है। क्योंकि इसमें एक लागत लगती है, इसीलिए मेननेट पर तैनात करने से पहले गोएरली पर अपने सबग्राफ को तैनात करने और परीक्षण करने की अत्यधिक अनुशंसा की जाती है। कुछ मामलों में, उस सबग्राफ पर कोई संकेत नहीं होने पर कुछ जीआरटी की भी आवश्यकता हो सकती है। उस सबग्राफ संस्करण (ऑटो-माइग्रेट का उपयोग करके) पर सिग्नल/क्यूरेशन होने की स्थिति में, करों को विभाजित किया जाएगा। + +7. "प्रकाशित करें" बटन दबाकर ग्राफ़ के विकेंद्रीकृत नेटवर्क पर सबग्राफ प्रकाशित करें। + +और बस! आपके द्वारा प्रकाशित किए जाने के बाद, आप [द ग्राफ़ एक्सप्लोरर](https://thegraph.com/explorer) के माध्यम से विकेंद्रीकृत नेटवर्क पर अपने सबग्राफ को लाइव देख सकेंगे। + +डिस्कॉर्ड पर [#Curators channel](https://discord.gg/rC8rBuRtbH) का बेझिझक लाभ उठाएं ताकि क्यूरेटर को पता चल सके कि आपका सबग्राफ सिग्नल देने के लिए तैयार है। यदि आप उनके साथ अपनी अपेक्षित क्वेरी मात्रा साझा करते हैं तो यह भी सहायक होगा। इसलिए, वे अनुमान लगा सकते हैं कि उन्हें आपके सबग्राफ पर कितने जीआरटी का संकेत देना चाहिए। + +### एक एपीआई key बनाएँ + +आप [यहां](https://thegraph.com/studio/apikeys/) सबग्राफ स्टूडियो में एक एपीआई key उत्पन्न कर सकते हैं। + +![एपीआई key निर्माण पेज](/img/api-image.png) + +प्रत्येक सप्ताह के अंत में, इस अवधि के दौरान किए गए क्वेरी शुल्क के आधार पर एक चालान जनरेट किया जाएगा। आपके बैलेंस में उपलब्ध GRT का उपयोग करके इस चालान का स्वचालित रूप से भुगतान किया जाएगा। आपकी क्वेरी शुल्क की लागत वापस लेने के बाद आपकी शेष राशि अपडेट की जाएगी। क्वेरी शुल्क का भुगतान आर्बिट्रम नेटवर्क के माध्यम से जीआरटी में किया जाता है। आपको निम्नलिखित चरणों के माध्यम से अपनी एपीआई key को सक्षम करने के लिए आर्बिट्रम बिलिंग कॉन्ट्रैक्ट में जीआरटी जोड़ने की आवश्यकता होगी: + +- अपनी पसंद के एक्सचेंज पर जीआरटी खरीदें। +- अपने वॉलेट में जीआरटी भेजें। +- स्टूडियो में बिलिंग पेज पर, ऐड जीआरटी पर क्लिक करें। + +![बिलिंग में जीआरटी जोड़ें](/img/Add-GRT-New-Page.png) + +- अपनी बिलिंग शेष राशि में अपना GRT जोड़ने के लिए चरणों का पालन करें। +- आपका GRT स्वचालित रूप से आर्बिट्रम नेटवर्क से जुड़ जाएगा और आपके बिलिंग बैलेंस में जुड़ जाएगा। + +![बिलिंग फलक](/img/New-Billing-Pane.png) + +> ध्यान दें: अपनी बिलिंग शेष राशि में GRT जोड़ने के बारे में पूर्ण निर्देशों के लिए [आधिकारिक बिलिंग पृष्ठ](../billing.mdx) देखें। + +### अपनी एपीआई key सुरक्षित करना + +यह अनुशंसा की जाती है कि आप एपीआई के उपयोग को दो तरीकों से सीमित करके सुरक्षित करें: + +1. अधिकृत सबग्राफ +2. अधिकृत डोमेन + +आप अपनी एपीआई key [यहां](https://thegraph.com/studio/apikeys/test/) सुरक्षित कर सकते हैं। + +![सबग्राफ लॉकडाउन पेज](/img/subgraph-lockdown.png) + +### विकेंद्रीकृत नेटवर्क पर अपने सबग्राफ को क्वेरी करना + +अब आप ग्राफ़ एक्सप्लोरर में नेटवर्क पर इंडेक्सर्स की इंडेक्सिंग स्थिति की जांच कर सकते हैं (उदाहरण [यहां](https://thegraph.com/explorer/subgraph?id=S9ihna8D733WTEShJ1KctSTCvY1VJ7gdVwhUujq4Ejo&view=Indexers)). शीर्ष पर हरी रेखा इंगित करती है कि पोस्टिंग के समय 8 इंडेक्सर्स ने उस सबग्राफ को सफलतापूर्वक अनुक्रमित किया। इंडेक्सर टैब में भी आप देख सकते हैं कि कौन से इंडेक्सर्स ने आपका सबग्राफ उठाया है। + +![रॉकेट पूल सबग्राफ](/img/rocket-pool-subgraph.png) + +जैसे ही पहले इंडेक्सर ने आपके सबग्राफ को पूरी तरह से इंडेक्स कर लिया, आप सबग्राफ को विकेंद्रीकृत नेटवर्क पर क्वेरी करना शुरू कर सकते हैं। अपने सबग्राफ के लिए क्वेरी URL को पुनः प्राप्त करने के लिए, आप क्वेरी URL के बगल में स्थित प्रतीक पर क्लिक करके इसे कॉपी/पेस्ट कर सकते हैं। आपको कुछ ऐसा दिखाई देगा: + +`https://gateway.thegraph.com/api/[api-key]/subgraphs/id/S9ihna8D733WTEShJ1KctSTCvY1VJ7gdVwhUujq4Ejo` + +महत्वपूर्ण: `[api-key]` को उपरोक्त अनुभाग में जेनरेट की गई वास्तविक API key से बदलना सुनिश्चित करें। + +अब आप अपने ग्राफ़िकल अनुरोधों को भेजने के लिए अपने डैप में उस क्वेरी URL का उपयोग कर सकते हैं। + +बधाई हो! अब आप विकेंद्रीकरण के अग्रणी हैं! + +> नोट: नेटवर्क की वितरित प्रकृति के कारण ऐसा हो सकता है कि अलग-अलग इंडेक्सर्स ने अलग-अलग ब्लॉकों तक इंडेक्स किया हो। केवल ताजा डेटा प्राप्त करने के लिए आप न्यूनतम ब्लॉक निर्दिष्ट कर सकते हैं जिसे इंडेक्सर को ब्लॉक के साथ आपकी क्वेरी को पूरा करने के लिए अनुक्रमित करना होगा: `{ number_gte: $minBlock }` फ़ील्ड तर्क जैसा कि नीचे दिए गए उदाहरण में दिखाया गया है : + +```graphql +{ + stakers(block: { number_gte: 14486109 }) { + id + } +} +``` + +नेटवर्क की प्रकृति के बारे में अधिक जानकारी और पुनर्संगठनों को कैसे संभालना है, इसका वर्णन दस्तावेज़ीकरण लेख [वितरित सिस्टम्स](/querying/distributed-systems/) में किया गया है। + +## नेटवर्क पर एक सबग्राफ को अपग्रेड करना + +यदि आप नेटवर्क पर एक मौजूदा सबग्राफ को अपग्रेड करना चाहते हैं, तो आप ग्राफ़ सीएलआई का उपयोग करके सबग्राफ स्टूडियो में अपने सबग्राफ का एक नया संस्करण तैनात करके ऐसा कर सकते हैं। + +1. अपने वर्तमान सबग्राफ में परिवर्तन करें। गोएर्ली में प्रकाशित करके सबग्राफ स्टूडियो पर छोटे सुधारों का परीक्षण करना एक अच्छा विचार है। +2. निम्नलिखित को तैनात करें और कमांड में नया संस्करण निर्दिष्ट करें (जैसे। v0.0.1, v0.0.2, आदि): + +```sh +graph deploy --studio +``` + +3. खेल के मैदान में क्वेरी करके सबग्राफ स्टूडियो में नए संस्करण का परीक्षण करें +4. ग्राफ़ नेटवर्क पर नया संस्करण प्रकाशित करें। याद रखें कि इसके लिए गैस की आवश्यकता होती है (जैसा कि ऊपर अनुभाग में बताया गया है)। + +### ओनर अपग्रेड फीस: डीप डाइव + +एक अपग्रेड के लिए GRT को सबग्राफ के पुराने संस्करण से नए संस्करण में माइग्रेट करने की आवश्यकता होती है। इसका मतलब है कि हर अपग्रेड के लिए, एक नया बॉन्डिंग कर्व बनाया जाएगा (बांडिंग कर्व्स के बारे में[यहां](/network/curating#bonding-curve-101) पर अधिक)। + +नया बॉन्डिंग कर्व नए संस्करण में माइग्रेट किए जा रहे सभी GRT पर 2.5% क्यूरेशन टैक्स लेता है। मालिक को इसका 50% या 1.25% भुगतान करना होगा। अन्य 1.25% शुल्क के रूप में सभी क्यूरेटरों द्वारा अवशोषित किया जाता है। यह प्रोत्साहन डिजाइन एक सबग्राफ के मालिक को रिकर्सिव अपग्रेड कॉल के साथ अपने सभी क्यूरेटर के फंड को निकालने में सक्षम होने से रोकने के लिए है। यदि कोई क्यूरेशन गतिविधि नहीं है, तो आपको अपने खुद के सबग्राफ को संकेत देने के लिए कम से कम 100 जीआरटी का भुगतान करना होगा। + +आइए एक उदाहरण बनाते हैं, यह केवल तभी होता है जब आपका सबग्राफ सक्रिय रूप से क्यूरेट किया जा रहा हो: + +- एक सबग्राफ के v1 पर ऑटो-माइग्रेट का उपयोग करके 100,000 GRT का संकेत दिया जाता है +- मालिक ने v2 में अपग्रेड किया। 100,000 GRT को एक नए बॉन्डिंग कर्व में माइग्रेट किया जाता है, जहां 97,500 GRT को नए कर्व में डाला जाता है और 2,500 GRT को बर्न किया जाता है +- आधे शुल्क का भुगतान करने के लिए मालिक के पास 1250 GRT जला हुआ है। अपग्रेड से पहले मालिक के पास यह उनके वॉलेट में होना चाहिए, अन्यथा, अपग्रेड सफल नहीं होगा। यह अपग्रेड होने वाले समान लेनदेन में होता है। + +_जबकि यह तंत्र वर्तमान में नेटवर्क पर लाइव है, समुदाय वर्तमान में सबग्राफ डेवलपर्स के लिए अपग्रेड की लागत को कम करने के तरीकों पर चर्चा कर रहा है।_ + +### एक सबग्राफ का एक स्थिर संस्करण बनाए रखना + +यदि आप अपने सबग्राफ में बहुत सारे बदलाव कर रहे हैं, तो इसे लगातार अपग्रेड करना और अपग्रेड लागतों को सामने रखना एक अच्छा विचार नहीं है। अपने सबग्राफ का एक स्थिर और सुसंगत संस्करण बनाए रखना महत्वपूर्ण है, न केवल लागत के नजरिए से बल्कि इसलिए भी कि इंडेक्सर्स अपने सिंकिंग समय में आत्मविश्वास महसूस कर सकें। जब आप अपग्रेड की योजना बनाते हैं तो इंडेक्सर्स को फ़्लैग किया जाना चाहिए ताकि इंडेक्सर सिंकिंग समय प्रभावित न हो। डिस्कॉर्ड पर [#इंडेक्सर्स चैनल](https://discord.gg/rC8rBuRtbH) का लाभ उठाने का महसूस करें ताकि इंडेक्सर्स को पता चल सके कि आप अपने सबग्राफ का संस्करण कब बना रहे हैं। + +सबग्राफ ओपन एपीआई हैं जिनका बाहरी डेवलपर्स लाभ उठा रहे हैं। ओपन एपीआई को सख्त मानकों का पालन करने की जरूरत है ताकि वे बाहरी डेवलपर्स के ऐप्स को तोड़ न दें। द ग्राफ़ नेटवर्क में, एक सबग्राफ़ डेवलपर को इंडेक्सर्स पर विचार करना चाहिए और उन्हें एक नया सबग्राफ़ **साथ ही** अन्य डेवलपर्स जो अपने सबग्राफ़ का उपयोग कर रहे हैं, को सिंक करने में कितना समय लगता है। + +### सबग्राफ के मेटाडेटा को अपडेट करना + +आप एक नया संस्करण प्रकाशित किए बिना अपने सबग्राफ के मेटाडेटा को अपडेट कर सकते हैं। मेटाडेटा में सबग्राफ नाम, छवि, विवरण, वेबसाइट URL, मुल कोड के URL और श्रेणियां शामिल हैं। डेवलपर सबग्राफ स्टूडियो में अपने सबग्राफ विवरण अपडेट करके ऐसा कर सकते हैं जहां आप सभी लागू फ़ील्ड संपादित कर सकते हैं। + +सुनिश्चित करें कि **एक्सप्लोरर में सबग्राफ विवरण अपडेट** चेक किया गया है और ** सेव ** पर क्लिक करें। यदि इसे चेक किया जाता है, तो एक ऑन-चेन लेनदेन उत्पन्न होगा जो एक्सप्लोरर में सबग्राफ विवरण अपडेट करता है बिना किसी नए परिनियोजन के एक नया संस्करण प्रकाशित किए बिना। + +## ग्राफ़ नेटवर्क में एक सबग्राफ को तैनात करने के लिए सर्वोत्तम अभ्यास + +1. सबग्राफ डेवलपमेंट के लिए ENS नाम का लाभ उठाना: + +- अपना ENS सेट करें: [https://app.ens.domains/](https://app.ens.domains/) +- [यहां](https://thegraph.com/explorer/settings?view=display-name) अपनी सेटिंग में अपना ENS नाम जोड़ें। + +2. आपके प्रोफाइल जितने अधिक भरे हुए हैं, आपके सबग्राफ के अनुक्रमित और क्यूरेट होने की संभावना उतनी ही बेहतर है। + +## ग्राफ़ नेटवर्क पर एक सबग्राफ का बहिष्कार करना + +अपने सबग्राफ को बहिष्कृत करने और इसे ग्राफ़ नेटवर्क से निकालने के लिए [यहां](/managing/deprecating-a-subgraph) चरणों का पालन करें। + +## ग्राफ़ नेटवर्क पर एक सबग्राफ + बिलिंग को क्वेरी करना + +होस्ट की गई सेवा की स्थापना डेवलपर्स को बिना किसी प्रतिबंध के अपने सबग्राफ तैनात करने की अनुमति देने के लिए की गई थी। + +द ग्राफ नेटवर्क को वास्तव में विकेंद्रीकृत करने के लिए, प्रोटोकॉल के प्रोत्साहन के मुख्य भाग के रूप में क्वेरी शुल्क का भुगतान करना होगा। एपीआई की सदस्यता लेने और क्वेरी शुल्क का भुगतान करने के बारे में अधिक जानकारी के लिए, बिलिंग दस्तावेज़ [यहां](/billing/) देखें। + +### नेटवर्क पर क्वेरी शुल्क का अनुमान लगाना + +जबकि यह उत्पाद UI में एक लाइव विशेषता नहीं है, आप प्रति माह भुगतान करने के इच्छुक राशि को लेकर और इसे अपनी अपेक्षित क्वेरी मात्रा से विभाजित करके अपना अधिकतम बजट प्रति क्वेरी निर्धारित कर सकते हैं। + +जब आप अपने क्वेरी बजट पर निर्णय लेते हैं, तो इस बात की कोई गारंटी नहीं है कि एक इंडेक्सर उस मूल्य पर क्वेरी को प्रस्तुत करने के लिए तैयार होगा। यदि कोई गेटवे आपको एक इंडेक्सर से मेल कर सकता है जो आपके द्वारा भुगतान किए जाने वाले मूल्य से समान या कम कीमत पर एक प्रश्न प्रस्तुत करने के लिए तैयार है, तो आप अपने बजट **और** उनकी कीमत के डेल्टा/अंतर का भुगतान करेंगे। परिणामस्वरूप, कम क्वेरी मूल्य आपके लिए उपलब्ध इंडेक्सर के पूल को कम कर देता है, जो आपको प्राप्त होने वाली सेवा की गुणवत्ता को प्रभावित कर सकता है। उच्च क्वेरी शुल्क होना फायदेमंद है, क्योंकि यह आपके सबग्राफ के लिए क्यूरेशन और बड़े-नाम वाले इंडेक्सर्स को आकर्षित कर सकता है। + +याद रखें कि यह एक गतिशील और बढ़ता हुआ बाजार है, लेकिन आप इसके साथ कैसे इंटरैक्ट करते हैं यह आपके नियंत्रण में है। प्रोटोकॉल या गेटवे में निर्दिष्ट कोई अधिकतम या न्यूनतम मूल्य नहीं है। उदाहरण के लिए, आप नीचे नेटवर्क पर (प्रति सप्ताह के आधार पर) कुछ डैप द्वारा भुगतान की गई कीमत को देख सकते हैं। अंतिम कॉलम देखें, जो जीआरटी में क्वेरी फीस दिखाता है। + +![क्वेरी शुल्क](/img/QueryFee.png) + +## अतिरिक्त संसाधन + +यदि आप अभी भी भ्रमित हैं, तो डरें नहीं! नीचे दिए गए संसाधनों को देखें या नीचे दिए गए विकेंद्रीकृत नेटवर्क में सबग्राफ माइग्रेट करने के बारे में हमारी वीडियो गाइड देखें: + + + +- [ग्राफ नेटवर्क कॉन्ट्रैक्ट](https://github.com/graphprotocol/contracts) +- [क्यूरेशन कॉन्ट्रैक्ट](https://github.com/graphprotocol/contracts/blob/dev/contracts/curation/Curation.sol) - अंतर्निहित कॉन्ट्रैक्ट जिसे GNS लपेटता है + - Address - `0x8fe00a685bcb3b2cc296ff6ffeab10aca4ce1538` +- [सबग्राफ स्टूडियो प्रलेखन](/deploying/subgraph-studio) diff --git a/website/pages/hi/cookbook/subgraph-uncrashable.mdx b/website/pages/hi/cookbook/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..03fac30ce9da --- /dev/null +++ b/website/pages/hi/cookbook/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: सुरक्षित सबग्राफ कोड जेनरेटर +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/) एक कोड जनरेशन टूल है जो किसी प्रोजेक्ट के ग्राफ़क्यूएल स्कीमा से सहायक फंक्शन्स का एक सेट उत्पन्न करता है. यह सुनिश्चित करता है कि आपके सबग्राफ में इकाइयों के साथ सभी इंटरैक्शन पूरी तरह से सुरक्षित और एक जैसा हैं। + +### सबग्राफ अनक्रैशेबल के साथ एकीकृत क्यों करें? + +- ** निरंतर अपटाइम**। गलत तरीके से हैंडल की गई इकाइयां सबग्राफ को क्रैश कर सकती हैं, जो कि ग्राफ़ पर निर्भर परियोजनाओं के लिए हानिकारक हो सकता है। अपने सबग्राफ को "अनक्रैशेबल" बनाने और व्यवसाय की निरंतरता सुनिश्चित करने के लिए सहायक फंक्शन्स सेट करें। + +- **पूरी तरह से सुरक्षित**। सबग्राफ विकास में देखी जाने वाली साधारण समस्याएं हैं अपरिभाषित इकाइयों का लोड होना, इकाइयों के सभी मूल्यों को स्थापित या प्रारंभ नहीं करना, और इकाइयों को लोड करने और सेव करने पर दौड़ की स्थिति का होना। सुनिश्चित करें कि इकाइयों के साथ सभी इंटरैक्शन पूरी तरह से एटोमिक हो। + +- **उपयोगकर्ता विन्यास योग्य** डिफ़ॉल्ट मान सेट करें और सुरक्षा जांच के स्तर को कॉन्फ़िगर करें जो आपकी व्यक्तिगत परियोजना की आवश्यकताओं के अनुरूप हो। डेटा सटीकता सुनिश्चित करने के लिए समस्या को ठीक करने में मदद करने के लिए चेतावनी लॉग रिकॉर्ड किए जाते हैं जहां सबग्राफ तर्क का उल्लंघन होता है। + +**प्रमुख विशेषताऐं** + +- कोड जनरेशन टूल **सभी** सबग्राफ प्रकारों को समायोजित करता है और उपयोगकर्ताओं के लिए मूल्यों पर समझदार डिफ़ॉल्ट सेट करने के लिए कॉन्फ़िगर करने योग्य है। कोड जनरेशन इस कॉन्फिग का उपयोग सहायक फंक्शन्स को उत्पन्न करने के लिए करेगा जो उपयोगकर्ता विनिर्देश के लिए हैं। + +- फ्रेमवर्क में इकाई वैरिएबल के समूहों के लिए कस्टम, लेकिन सुरक्षित, सेटर फ़ंक्शन बनाने का एक तरीका (कॉन्फिग फ़ाइल के माध्यम से) भी शामिल है। इस तरह उपयोगकर्ता के लिए एक पुरानी ग्राफ़ इकाई को लोड/उपयोग करना असंभव है और फ़ंक्शन द्वारा आवश्यक वैरिएबल को सहेजना या सेट करना भूलना भी असंभव है। + +- चेतावनी लॉग्स लॉग्स के रूप में रिकॉर्ड किए जाते हैं जो इंगित करते हैं कि डेटा सटीकता सुनिश्चित करने के लिए समस्या को ठीक करने में मदद करने के लिए सबग्राफ लॉजिक का उल्लंघन कहां हुआ है। इन लॉग्स को 'लॉग्स' सेक्शन के तहत द ग्राफ की होस्टेड सेवा में देखा जा सकता है। + +सबग्राफ अनक्रैशेबल को ग्राफ़ CLI codegen कमांड का उपयोग करके एक वैकल्पिक फ़्लैग के रूप में चलाया जा सकता है। + +```sh +graph codegen -u [options] [] +``` + +अधिक जानने के लिए और सुरक्षित सबग्राफ विकसित करने के साथ आरंभ करने के लिए [सबग्राफ अनक्रैशेबल डॉक्यूमेंटेशन](https://float-capital.github.io/float-subgraph-uncrashable/docs/) पर जाएं या यह [वीडियो ट्यूटोरियल](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial) देखें। diff --git a/website/pages/hi/deploying/subgraph-studio-faqs.mdx b/website/pages/hi/deploying/subgraph-studio-faqs.mdx new file mode 100644 index 000000000000..05642f55e642 --- /dev/null +++ b/website/pages/hi/deploying/subgraph-studio-faqs.mdx @@ -0,0 +1,31 @@ +--- +title: सबग्राफ स्टूडियो अक्सर पूछे जाने वाले प्रश्न +--- + +### सबग्राफ स्टूडियो क्या है? + +[सबग्राफ स्टूडियो](https://thegraph.com/studio/) सबग्राफ और एपीआई key बनाने, प्रबंधित करने और प्रकाशित करने के लिए एक डैप है। + +### 2. मैं एक एपीआई key कैसे बना सकता हूँ? + +एपीआई बनाने के लिए, सबग्राफ स्टूडियो में नेविगेट करें और अपने वॉलेट को कनेक्ट करें। आप शीर्ष पर एपीआई keys टैब पर क्लिक करने में सक्षम होंगे। वहां, आप एक एपीआई key बनाने में सक्षम होंगे। + +### 3. क्या मैं कई एपीआई keys बना सकता हूं? + +हाँ! आप विभिन्न परियोजनाओं में उपयोग करने के लिए कई एपीआई keys बना सकते हैं। [यहां](https://thegraph.com/studio/apikeys/) लिंक देखें। + +### 4. मैं एपीआई key के लिए डोमेन को कैसे प्रतिबंधित करूं? + +एपीआई key बनाने के बाद, सुरक्षा अनुभाग में, आप उन डोमेन को परिभाषित कर सकते हैं जो किसी विशिष्ट एपीआई key को क्वेरी कर सकते हैं। + +### 5. क्या मैं अपना सबग्राफ किसी अन्य को स्थानांतरित कर सकता हूं? + +हां, मेननेट पर प्रकाशित किए गए सबग्राफ को एक नए वॉलेट या मल्टीसिग में स्थानांतरित किया जा सकता है। आप सबग्राफ के विवरण पृष्ठ पर 'प्रकाशित करें' बटन के आगे तीन बिंदुओं पर क्लिक करके और 'स्वामित्व स्थानांतरित करें' का चयन करके ऐसा कर सकते हैं। + +ध्यान दें कि एक बार स्थानांतरित हो जाने के बाद आप स्टूडियो में सबग्राफ को देख या संपादित नहीं कर पाएंगे। + +### 6. यदि मैं उस सबग्राफ का डेवलपर नहीं हूं जिसका मैं उपयोग करना चाहता हूं तो मैं सबग्राफ के लिए क्वेरी URL कैसे ढूंढूं? + +आप ग्राफ़ एक्सप्लोरर के सबग्राफ विवरण अनुभाग में प्रत्येक सबग्राफ का क्वेरी URL पा सकते हैं। जब आप "क्वेरी" बटन पर क्लिक करते हैं, तो आपको एक फलक पर निर्देशित किया जाएगा, जिसमें आप उस सबग्राफ का क्वेरी URL देख सकते हैं, जिसमें आप रुचि रखते हैं। फिर आप `` प्लेसहोल्डर को बदल सकते हैं एपीआई key के साथ आप सबग्राफ स्टूडियो में लाभ उठाना चाहते हैं। + +याद रखें कि आप एक एपीआई key बना सकते हैं और नेटवर्क पर प्रकाशित किसी सबग्राफ को क्वेरी कर सकते हैं, भले ही आप स्वयं एक सबग्राफ बनाते हों। नई एपीआई key के माध्यम से ये प्रश्न, नेटवर्क पर किसी अन्य के रूप में भुगतान किए गए प्रश्न हैं। diff --git a/website/pages/ja/arbitrum-faq.mdx b/website/pages/ja/arbitrum-faq.mdx new file mode 100644 index 000000000000..16bf8e538be1 --- /dev/null +++ b/website/pages/ja/arbitrum-faq.mdx @@ -0,0 +1,80 @@ +--- +title: Arbitrum FAQ +--- + +Arbitrum の請求に関する FAQ をご覧になりたい方は、[こちら](#billing-on-arbitrum-faqs)をクリックしますと、FAQ に飛びます。 + +## 一般的なよくある質問 + +### The Graph が L2 ソリューションを導入する理由は? + +The Graph を L2 でスケールさせることで、ネットワーク参加者は以下を期待できます: + +- ガス代が 26 倍節約できる + +- 取引スピードの高速化 + +- イーサリアムによる保護 + +このプロトコルにより、ネットワーク参加者は、ガス料金を削減して、より頻繁にやり取りできます。これにより、インデクサーはより多くのサブグラフにインデックスを付けることができ、開発者はサブグラフをより簡単に展開およびアップグレードでき、委任者はより頻繁に GRT を委任できるようになり、キュレーターはより多くのサブグラフにシグナルを追加できるようになります。 + +グラフコミュニティ[は、昨年、Arbitrum を進めることを決定しました](https://forum.thegraph.com/t/gip-0031-arbitrum-grt-bridge/3305)。 + +### The Graph on L2 を利用するために必要なことは何ですか? + +ユーザーは、次のいずれかの方法を使用して、GRT と ETH をブリッジします。 + +- [アービトラムのグラフ ブリッジ](https://bridge.arbitrum.io/?l2ChainId=42161) +- [TransferTo](https://transferto.xyz/swap) +- [Connext Bridge](https://bridge.connext.network/) +- [Hop Exchange](https://app.hop.exchange/#/send?token=ETH) + +L2 での The Graph の活用には、このドロップダウンスイッチャーを使用して、チェーンを切り替えてください。 + +{/* Insert an image */} ![Arbitrumの切り替えができるドロップダウン式スイッチャー](/img/arbitrum-screenshot-toggle.png) + +### サブグラフ開発者、データ消費者、インデクサー、キュレーター、デリゲーターは何をする必要がありますか? + +直ちに必要な措置はありません。 + +コア開発者チームは、デリゲーション、キュレーション、サブグラフの Arbitrum への移行を大幅に容易にする移行ヘルパーの作成に取り組んでいます。ネットワーク参加者は、2023 年 4 月にマイグレーションヘルパーが利用できるようになることを期待しています。 + +また、グラフコミュニティは、2023 年 2 月または 3 月に Arbitrum でインデックス報酬が有効になることを期待しています。 + +### L2 でのネットワークに参加したい場合は、どうすればいいのでしょうか? + +[L2 でのネットワークのテスト](https://testnet.thegraph.com/explorer)にご協力いただき、[Discord](https://discord.gg/vtvv7FP)であなたの経験に関するフィードバックをご報告ください。 + +### L2 へのネットワーク拡張に伴うリスクはありますか? + +すべてのスマートコントラクトは、徹底的に[監査](https://github.com/graphprotocol/contracts/blob/dev/audits/OpenZeppelin/2022-07-graph-arbitrum-bridge-audit.pdf)されています。 + +また、安全でシームレスな移行を実現するために、万が一の事態に備えた対策が講じられています。詳細は[こちら](https://forum.thegraph.com/t/gip-0037-the-graph-arbitrum-deployment-with-linear-rewards-minted-in-l2/3551#risks-and-security-considerations-20)でご確認ください。 + +### イーサリアムの既存のサブグラフは引き続き使えるのでしょうか? + +はい、グラフネットワークのコントラクトは、後日 Arbitrum に完全に移行するまでは、Ethereum と Arbitrum の両方で並行して運用される予定です。 + +### GRT は Arbitrum に新しいスマートコントラクトをデプロイするのでしょうか? + +はい、GRT には追加の [Arbitrum のスマート コントラクト](https://arbiscan.io/address/0x9623063377ad1b27544c965ccd7342f7ea7e88c7)があります。ただし、イーサリアム メインネット [GRT コントラクト](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7)は引き続き運用されます。 + +## Arbitrum での課金に関する FAQ + +### 課金バランスの GRT についてはどうすればいいのでしょうか? + +何もない!?あなたの GRT は Arbitrum に安全に移行され、あなたがこれを読んでいる間、クエリの支払いに使われているのです。 + +### 自分の資金が Arbitrum に安全に移行されたことを確認するにはどうすればよいですか? + +GRT の課金バランスは、すでにすべて Arbitrum に正常に移行しています。Arbitrum の[こちら](https://arbiscan.io/address/0x1B07D3344188908Fb6DEcEac381f3eE63C48477a)で課金コントラクトを確認することができます。 + +### Arbitrum ブリッジの安全性を確認するにはどうすればよいですか? + +このブリッジは、[厳重な監査](https://code4rena.com/contests/2022-10-the-graph-l2-bridge-contest)を受け、すべての利用者の安全・安心を確保しています。 + +### イーサリアムメインネットのウォレットから GRT を追加する場合、何をする必要があるのでしょうか? + +GRT を Arbitrum の課金バランスに追加することは、[Subgraph Studio](https://thegraph.com/studio/)でワンクリックの体験で可能です。GRT を Arbitrum に簡単にブリッジし、API キーを 1 回のトランザクションで充填することができます。 + +GRT の追加、引き出し、取得に関する詳しい説明は、[課金ページ](https://thegraph.com/docs/en/billing/)をご覧ください。 diff --git a/website/pages/ja/cookbook/arweave.mdx b/website/pages/ja/cookbook/arweave.mdx index 6fa67f40c7a0..e4f05080f35f 100644 --- a/website/pages/ja/cookbook/arweave.mdx +++ b/website/pages/ja/cookbook/arweave.mdx @@ -1,61 +1,61 @@ --- -title: Building Subgraphs on Arweave +title: Arweaveでのサブグラフ構築 --- -> Arweave support in Graph Node and on the Hosted Service is in beta: please reach us on [Discord](https://discord.gg/rC8rBuRtbH) with any questions about building Arweave subgraphs! +> グラフノードとホスティングサービスにおける Arweave のサポートはベータ版です。Arweave サブグラフの構築に関するご質問は[Discord](https://discord.gg/rC8rBuRtbH)にご連絡ください。 -In this guide, you will learn how to build and deploy Subgraphs to index the Arweave blockchain. +このガイドでは、Arweave ブロックチェーンのインデックスを作成するためのサブグラフの構築とデプロイ方法について学びます。 -## What is Arweave? +## 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 プロトコルは、開発者がデータを永久に保存することを可能にし、それが Arweave と IPFS の主な違いです。IPFS は永続性に欠ける一方、Arweave に保存されたファイルは変更も削除もできません。 -Arweave already has built numerous libraries for integrating the protocol in a number of different programming languages. For more information you can check: +Arweave は既に、さまざまなプログラミング言語でプロトコルを統合するための多数のライブラリを構築しています。詳細については、次を確認できます。 - [Arwiki](https://arwiki.wiki/#/en/main) -- [Arweave Resources](https://www.arweave.org/build) +- [Arweave リソース](https://www.arweave.org/build) -## What are Arweave Subgraphs? +## 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/). +グラフを使用すると、「サブグラフ」と呼ばれるカスタムのオープン API を構築できます。サブグラフは、を使用していつでもクエリできるようにするために、インデクサー (サーバー オペレーター) に、ブロックチェーンでインデックスを作成してサーバーに保存するデータを伝えるために使用されます。 [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. +[Graph Node](https://github.com/graphprotocol/graph-node) は、Arweave プロトコルでデータをインデックス化できるようになりました。現在の統合は、Arweave をブロックチェーン (ブロックとトランザクション) としてインデックス付けするだけで、保存されたファイルにはまだインデックス付けしていません。 -## Building an Arweave Subgraph +## Arweave サブグラフの作成 -To be able to build and deploy Arweave Subgraphs, you need two packages: +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`. +1. `@graphprotocol/graph-cli` version 0.30.2 以降 - サブグラフの構築と展開を行うコマンドラインツールです。[ここをクリック](https://www.npmjs.com/package/@graphprotocol/graph-cli)し、`npm`を使用してダウンロードしてください。 +2. `@graphprotocol/graph-ts` version 0.27.0 以降 - サブグラフに特化した型のライブラリです。[こちらをクリック](https://www.npmjs.com/package/@graphprotocol/graph-ts)して、`npm`でダウンロードしてください。 -## Subgraph's components +## サブグラフのコンポーネント -There are three components of a subgraph: +サブグラフには 3 つの構成要素があります: -### 1. Manifest - `subgraph.yaml` +### 1. マニフェスト - `subgraph.yaml` -Defines the data sources of interest, and how they should be processed. Arweave is a new kind of data source. +対象のデータ ソースとその処理方法を定義します。 Arweave は新しい種類のデータ ソースです。 -### 2. Schema - `schema.graphql` +### 2. スキーマ - `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. +ここでは、GraphQL を使用してサブグラフにインデックスを付けた後にクエリできるようにするデータを定義します。これは実際には API のモデルに似ており、モデルはリクエスト本文の構造を定義します。 -The requirements for Arweave subgraphs are covered by the [existing documentation](/developing/creating-a-subgraph/#the-graphql-schema). +Arweave サブグラフの要件は、[existing documentation](/developing/creating-a-subgraph/#the-graphql-schema)に網羅されています。 -### 3. AssemblyScript Mappings - `mapping.ts` +### 3. アセンブリスクリプトマッピング - `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: +サブグラフの開発には 2 つの重要なコマンドがあります: ``` -$ 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 codegen # マニフェストで識別されたようにファイルから型を生成します +$ グラフ ビルド # AssemblyScript ファイルから Web アセンブリを生成し、/build フォルダにすべてのサブグラフ ファイルを準備します ``` -## 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: +サブグラフ マニフェスト `subgraph.yaml` は、サブグラフのデータ ソース、関心のあるトリガー、およびこれらのトリガーに応答して実行される関数を識別します。Arweave サブグラフのサブグラフ マニフェストの例については、以下を参照してください: ```yaml specVersion: 0.0.5 @@ -82,30 +82,30 @@ dataSources: - 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. On the Hosted Service, 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 サブグラフは新しい種類のデータ ソースを導入します (`arweave`) +- ネットワークはホスティングするグラフノード上のネットワークに対応する必要があります。ホスティングサービス上では、Arweave のメインネットは`arweave-mainnet`です。 +- Arweave データ ソースには、オプションの source.owner フィールドが導入されています。これは、Arweave ウォレットの公開鍵です。 -Arweave data sources support two types of handlers: +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. Note that only exact matches are processed. Currently an owner is required for `transactionHandlers`. +- `blockHandlers` - すべての新しい Arweave ブロックに対して実行されます。source.owner は必要ありません。 +- `transactionHandlers` - データ ソースの `source.owner` が所有者であるすべてのトランザクションで実行されます。現在、`transactionHandlers` には所有者が必要です。ユーザーがすべてのトランザクションを処理したい場合は、`source.owner` として "" を指定する必要があります。 -> The source.owner is the owner's Public Key, rather than the owner's address. +> Source.owner は、所有者のアドレスまたは公開鍵にすることができます。 -> Transactions are the building blocks of the Arweave permaweb and they are objects created by end-users. +> トランザクションは Arweave permaweb の構成要素であり、エンドユーザーによって作成されるオブジェクトです。 -> Note: [Bundlr](https://bundlr.network/) transactions are not supported yet. +> 注意:[Bundlr](https://bundlr.network/)トランザクションはまだサポートされていません。 -## 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). +スキーマの定義は、結果として得られるサブグラフ・データベースの構造と、エンティティ間の関係を記述する。これは、元のデータソースに依存しません。スキーマ定義の詳細は、[ こちら](/developing/creating-a-subgraph/#the-graphql-schema)にあります。 -## AssemblyScript Mappings +## AssemblyScript マッピング -The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). +イベントを処理するハンドラは、[AssemblyScript](https://www.assemblyscript.org/) で記述されています。 -Arweave indexing introduces Arweave-specific data types to the [AssemblyScript API](/developing/assemblyscript-api/). +Arweave のインデックス作成は、[AssemblyScript API](/developing/assemblyscript-api/)に Arweave 固有のデータ型を導入しています。 ```tsx class Block { @@ -146,94 +146,94 @@ class Transaction { } ``` -Block handlers receive a `Block`, while transactions receive a `Transaction`. +ブロックハンドラは`Block`を受け取り、トランザクションは`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). +Arweave サブグラフのマッピングの記述は、Ethereum サブグラフのマッピングの記述と非常に似ています。詳細については、[こちら](/developing/creating-a-subgraph/#writing-mappings)をクリックしてください。 -## Deploying an Arweave Subgraph on the Hosted Service +## ホステッド サービスへの Arweave サブグラフのデプロイ -Once your subgraph has been created on the Hosed Service dashboard, you can deploy by using the `graph deploy` CLI command. +ホストされたサービスのダッシュボード上でサブグラフを作成したら、展開は「使用する」を使って行うことができます`graph deploy` CLI コマンド ```bash graph deploy --node https://api.thegraph.com/deploy/ --ipfs https://api.thegraph.com/ipfs/ --access-token ``` -## Querying an Arweave Subgraph +## Arweave サブグラフのクエリ -The GraphQL endpoint for Arweave subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/querying/graphql-api/) for more information. +Arweave サブグラフの GraphQL エンドポイントは、スキーマ定義によって決定され、既存の API インタフェースが使用されます。詳細は[GraphQL API documentation](/querying/graphql-api/)を参照してください。 -## Example Subgraphs +## サブグラフの例 -Here is an example subgraph for reference: +参考までにサブグラフの例を紹介します: -- [Example subgraph for Arweave](https://github.com/graphprotocol/example-subgraph/tree/arweave-blocks-transactions) +- [Arweave のサブグラフの例](https://github.com/graphprotocol/example-subgraphs/tree/main/arweave/blocks-transactions) -## FAQ +## よくある質問 -### Can a subgraph index Arweave and other chains? +### サブグラフは Arweave やその他のチェーンにインデックスを付けることができますか? -No, a subgraph can only support data sources from one chain/network. +いいえ、サブグラフは 1 つのチェーン/ネットワークのデータソースのみをサポートします。 -### Can I index the stored files on Arweave? +### 保存されたファイルを Arweave でインデックス化することはできますか? -Currently, The Graph is only indexing Arweave as a blockchain (its blocks and transactions). +現在、The Graph は Arweave をブロックチェーン (ブロックとトランザクション) としてのみインデックス化しています。 -### Can I identify Bundlr bundles in my subgraph? +### 自分のサブグラフにある Bundlr バンドルは特定できるのか? -This is not currently supported. +現在はサポートされていません。 -### How can I filter transactions to a specific account? +### トランザクションを特定のアカウントにフィルターするにはどうすればよいですか? -The source.owner is the user's public key, rather than the account address. We are working on adding account filtering support. +Source.owner には、ユーザの公開鍵またはアカウントアドレスを指定することができます。 -### 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/). +通常、データはバイトとしてマッピングに渡され、直接格納されている場合はサブグラフに `hex` 形式で返されます (例: ブロックおよびトランザクション ハッシュ). あなたは A に変換したいかもしれません `base64` or `base64 URL` 私たちのマッピングでの安全なフォーマットを日本語に翻訳すると、ブロックエクスプローラーなどで表示されるものに一致するようになります[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`: +以下の`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", "+", "/" + "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", "-", "_" + "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; + 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/pages/ja/cookbook/base-testnet.mdx b/website/pages/ja/cookbook/base-testnet.mdx new file mode 100644 index 000000000000..0f6fab7305dc --- /dev/null +++ b/website/pages/ja/cookbook/base-testnet.mdx @@ -0,0 +1,112 @@ +--- +title: Baseでのサブグラフ構築 +--- + +このガイドでは、Base テストネットでのサブグラフの初期化、作成、デプロイの方法を素早く説明します. + +必要なもの: + +- Base テストネットコントラクトアドレス +- 暗号ウォレット(例:MetaMask または Coinbase Wallet) + +## サブグラフスタジオ + +### 1. Graph CLI のインストール + +The Graph CLI (>=v0.41.0) は JavaScript で書かれており、使用するには `npm` または `yarn` のいずれかをインストールする必要があります。 + +```sh +# NPM +npm install -g @graphprotocol/graph-cli + +# Yarn +yarn global add @graphprotocol/graph-cli +``` + +### 2. Subgraph Studio であなたのサブグラフを作成してください。」となります。 + +[Subgraph Studio](https://thegraph.com/studio/) に移動し、クリプト ウォレットを接続します。 + +接続後「Create a Subgraph」をクリックし、サブグラフの名称を入力します。 + +インデックス付きブロックチェーンとして「Base (testnet)」を選択し、「Create Subgraph」をクリックします。 + +### 3. サブグラフの初期化 + +> サブグラフに固有のコマンドは、Subgraph Studio で確認することができます。 + +Graph-cli が最新版(0.41.0 以上)に更新されていることを確認します。 + +```sh +グラフ --バージョン +``` + +既存のコントラクトからサブグラフを初期化します。 + +```sh +graph init --studio +``` + +サブグラフのスラッグは、サブグラフの識別子となるものです。CLI ツールは、サブグラフを作成するためのステップを説明します。 + +- Protocol: ethereum +- Subgraph slug: `` +- Directory to create the subgraph in: `` +- Ethereum network: base-testnet \_ Contract address: `` +- Start block (optional) +- Contract name: `` +- イベントのインデックス作成について、[はい]/[いいえ] を選択します ([はい] は、サブグラフがスキーマ エンティティと発行されたイベントの単純なマッピングでブートストラップされることを意味します)。 + +### 3. サブグラフの作成 + +> 排出されたイベントだけがインデックスになる場合は、追加の作業は必要なく、次のステップに進むことができます。 + +前のコマンドは、scaffold subgraph を作成し、これを出発点としてサブグラフを構築することができます。サブグラフに変更を加える場合、主に 3 つのファイルを操作することになります: + +- マニフェスト (subgraph.yaml) - マニフェストは、サブグラフがインデックスするデータソースを定義します。サブグラフを Base testnet にデプロイするには、マニフェストファイルのネットワーク名として`base-testnet`を必ず追加してください。 +- スキーマ (schema.graphql) - GraphQL スキーマは、サブグラフから取得したいデータを定義します。 +- AssemblyScript Mappings (mapping.ts) - データソースからのデータを、スキーマで定義されたエンティティに変換するコードです。 + +追加のデータをインデックス化したい場合は、マニフェスト、スキーマ、マッピングの拡張が必要です。 + +サブグラフの書き方については、[サブグラフの作成](/developing/creating-a-subgraph) をご覧ください。 + +### 4. Subgraph Studio へのデプロイ + +サブグラフをデプロイする前に、Subgraph Studio で認証する必要があります。これは、以下のコマンドを実行することで可能です: + +「スタジオでサブグラフを認証する」 + +``` +graph auth --studio +``` + +次に、サブグラフのディレクトリを入力します。 + +``` + cd +``` + +以下のコマンドでサブグラフを構築します: + +```` +``` +graph codegen && graph build +``` +```` + +最後に、このコマンドでサブグラフをデプロイすることができます: + +```` +``` +graph deploy --studio +``` +```` + +### 5. 「サブグラフをクエリする」 + +サブグラフがデプロイされると、Subgraph Studio の`Development Query URL`を使用して、Dapp からサブグラフをクエリすることができます。 + +注意:Studio API は料金に制限があります。そのため、開発およびテストに使用することを推奨します。 + +サブグラフからデータをクエリする方法については、[サブグラフのクエリ](/querying/querying-the-graph)のページを参照してください。 diff --git a/website/pages/ja/cookbook/cosmos.mdx b/website/pages/ja/cookbook/cosmos.mdx deleted file mode 120000 index 66acfa28a317..000000000000 --- a/website/pages/ja/cookbook/cosmos.mdx +++ /dev/null @@ -1 +0,0 @@ -../../en/cookbook/cosmos.mdx \ No newline at end of file diff --git a/website/pages/ja/cookbook/grafting.mdx b/website/pages/ja/cookbook/grafting.mdx new file mode 100644 index 000000000000..72b1ee6b3457 --- /dev/null +++ b/website/pages/ja/cookbook/grafting.mdx @@ -0,0 +1,186 @@ +--- +title: グラフティングでコントラクトを取り替え、履歴を残す +--- + +このガイドでは、既存のサブグラフをグラフティングして新しいサブグラフを構築し、配備する方法を学びます。 + +## グラフティングとは? + +グラフティングは、既存のサブグラフからデータを再利用し、後のブロックからインデックスを作成します。これは、開発中にマッピングの単純なエラーを素早く乗り越えるため、または、既存のサブグラフが失敗した後に一時的に再び動作させるために有用です。また、ゼロからインデックスを作成するのに時間がかかる機能をサブグラフに追加する場合にも使用できます。 + +グラフト化されたサブグラフは、ベースとなるサブグラフのスキーマと同一ではなく、単に互換性のある GraphQL スキーマを使用することができます。また、それ自体は有効なサブグラフのスキーマでなければなりませんが、以下の方法でベースサブグラフのスキーマから逸脱することができます。 + +- エンティティタイプを追加または削除する +- エンティティタイプから属性を削除する +- 属性を追エンティティタイプに nullable 加する +- null 化できない属性を null 化できる属性に変更する +- enums に値を追加する +- インターフェースの追加または削除 +- インターフェースがどのエンティティタイプに実装されるかを変更する + +詳しくは、こちらでご確認ください。 + +- [Grafting](https://thegraph.com/docs/en/developing/creating-a-subgraph#grafting-onto-existing-subgraphs) + +このチュートリアルでは、基本的なユースケースについて説明します。既存の契約を同一の契約に置き換えます(新しい住所ですが、コードは同じです)。次に、新しいコントラクトを追跡する「ベース」サブグラフに既存のサブグラフを移植します + +## 既存のサブグラフの構築 + +サブグラフの構築は、The Graph の重要な部分であり、[こちら](http://localhost:3000/en/cookbook/quick-start/)でより詳しく説明されています。このチュートリアルで使用する既存のサブグラフをビルドしてデプロイできるようにするために、以下のレポを提供します。 + +- [サブグラフ例文レポ](https://github.com/t-proctor/grafting-tutorial) + +> 注:サブグラフで使用されているコントラクトは、以下の[Hackathon Starterkit](https://github.com/schmidsi/hackathon-starterkit)から取得したものです。 + +## サブグラフマニフェストの定義 + +サブグラフ マニフェスト `subgraph.yaml` は、サブグラフのデータ ソース、関心のあるトリガー、およびこれらのトリガーに応答して実行される関数を識別します。使用するサブグラフ マニフェストの例については、以下を参照してください。 + +```yaml +specVersion: 0.0.4 +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum + name: Lock + network: goerli + source: + address: '0x4Ed995e775D3629b0566D2279f058729Ae6EA493' + abi: Lock + startBlock: 7674603 + 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`データソースは、コンパイルとデプロイ時に取得するアビとコントラクトのアドレスです。 +- ネットワークは、クエリされるインデックス付きネットワークに対応する必要があります。Goerli testnet で実行しているので、ネットワークは `goerli` となります。 +- `mapping`セクションでは、関心のあるトリガーと、それらのトリガーに応答して実行されるべき関数を定義しています。この場合、`Withdrawal`イベントをリスニングし、それが発信されたときに`handleWithdrawal`関数を呼び出すことにしています。 + +## グラフティングマニフェストの定義 + +グラフティングは、元のサブグラフ・マニフェストに新しい 2 つの項目を追加する必要があります。 + +```yaml +--- +特徴: + - グラフト # 機能名 +移植: + base: Qm... # ベース部分グラフの部分グラフID + block: 1502122 # ブロック番号 +``` + +- `features`: 使用されるすべての[feature](developing/creating-a-subgraph/#experimental-features)名のリストです。 +- `graft:`は`base`サブグラフとグラフティングをするブロックのマップです。`block`はインデックスを開始するブロック番号です。Graph は、指定されたブロックまでのベースサブグラフのデータをコピーし、そのブロックから新しいサブグラフのインデックスを作成し続けます。 + +`base`と`block`の値は、2 つのサブグラフを展開することで求めることができます:一つはベースインデックス用、もう一つはグラフティング用です + +## ベースサブグラフの起動 + +1. [Graph Studio UI](https://thegraph.com/studio/)にアクセスし、Guerli testnet 上に`graft-example`というサブグラフを作成します。 +2. レポの `graft-example` フォルダ内のサブグラフのページにある `AUTH & DEPLOY` セクションの指示にしたがってください。 +3. 終了後、サブグラフが正しくインデックスされていることを確認します。The Graph Playground で以下のコマンドを実行すると、サブグラフが正常にインデックスされます。 + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +このようなものが返ってきます: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0x13098b538a61837e9f29b32fb40527bbbe63c9120c250242b02b69bb42c287e5-5", + "amount": "0", + "when": "1664367528" + }, + { + "id": "0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498-3", + "amount": "0", + "when": "1664367648" + } + ] + } +} +``` + +サブグラフが正しくインデックスされていることを確認したら、グラフティングで素早くサブグラフを更新することができます。 + +## グラフティングサブグラフの展開 + +グラフト置換された subgraph.yaml は、新しいコントラクトのアドレスを持つことになります。これは、ダンプを更新したり、コントラクトを再デプロイしたりしたときに起こりうることです。 + +1. [Graph Studio UI](https://thegraph.com/studio/)にアクセスし、Goerli testnet 上に`graft-replacement`というサブグラフを作成します。 +2. 新しいマニフェストを作成します。`graph-replacement` の `subgraph.yaml` には、異なるコントラクト アドレスと、どのようにグラフティングするかについての新しい情報が含まれています。これらは、古いコントラクトで発生する[最後のイベント](https://goerli.etherscan.io/tx/0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498)の`block`と古いサブグラフの`base`です。`base`サブグラフ ID は、元の`graph-example`サブグラフの`Deployment ID`となります。これは、The Graph Studio UI で確認できます。 +3. レポの `graft-replacement` フォルダ内のサブグラフのページにある `AUTH & DEPLOY` セクションの指示にしたがってください。 +4. 終了後、サブグラフが正しくインデックスされていることを確認します。The Graph Playground で以下のコマンドを実行すると、サブグラフが正常にインデックスされます。 + +```graphql +{ + withdrawals(first: 5) { + id + amount + when + } +} +``` + +以下のように返ってくるはずです: + +``` +{ + "data": { + "withdrawals": [ + { + "id": "0x13098b538a61837e9f29b32fb40527bbbe63c9120c250242b02b69bb42c287e5-5", + "amount": "0", + "when": "1664367528" + }, + { + "id": "0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498-3", + "amount": "0", + "when": "1664367648" + }, + { + "id": "0xb4010e4c76f86762beb997a13cf020231778eaf7c64fa3b7794971a5e6b343d3-22", + "amount": "0", + "when": "1664371512" + } + ] + } +} +``` + +`graft-replacement`サブグラフは、古い`graph-example`データと新しいコントラクトアドレスからの新しいデータからインデックスを作成していることがわかります。元のコントラクトは、[Event 1](https://goerli.etherscan.io/tx/0x800c92fcc0edbd26f74e19ad058c62008a47c7789f2064023b987028343dd498)と[Event 2](https://goerli.etherscan.io/address/0x4ed995e775d3629b0566d2279f058729ae6ea493)という 2 つの`Withdrawal`イベントを発行しています。新しいコントラクトは、[イベント 3](https://goerli.etherscan.io/tx/0xb4010e4c76f86762beb997a13cf020231778eaf7c64fa3b7794971a5e6b343d3)の後に、1 つの`Withdrawal`を発行しました。2 つの以前インデックスされたトランザクション(イベント 1、2)と新しいトランザクション(イベント 3)は`graft-replacement`サブグラフで一緒に結合されます。 + +おめでとうございます。あなたは、サブグラフを別のサブグラフにグラフティングすることに成功しました。 + +## その他のリソース + +もっとグラフティングを体験したい方に、人気のあるコントラクトの例をご紹介します: + +- [曲線](https://github.com/messari/subgraphs/blob/master/subgraphs/curve-finance/protocols/curve-finance/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/protocols/uniswap-v3/config/templates/uniswap.v3.template.yaml), + +グラフの専門家になるには、基礎となるデータソースの変更を処理する他の方法について学ぶことを検討してください。[Data Source Templates](developing/creating-a-subgraph/#data-source-templates) のような代替手段で、同様の結果を得ることができます。 + +> 注:この記事の多くの資料は、以前公開された[アルウィーブの記事](/cookbook/arweave/)から引用したものです。 diff --git a/website/pages/ja/cookbook/migrating-a-subgraph.mdx b/website/pages/ja/cookbook/migrating-a-subgraph.mdx index cc8b83322f7d..d15c64eb4c7a 100644 --- a/website/pages/ja/cookbook/migrating-a-subgraph.mdx +++ b/website/pages/ja/cookbook/migrating-a-subgraph.mdx @@ -4,19 +4,19 @@ title: 既存のサブグラフをグラフネットワークに移行する ## イントロダクション -本ガイドは、サブグラフをホステッドサービスから The Graph Network に移行するためのガイドです。The Graph Network への移行は、Opyn、UMA、mStable、Audius、PoolTogether、Livepeer、RAI、Enzyme、DODO、Opyn、Pickle、BadgerDAO などのプロジェクトで成功を収めており、これらのプロジェクトはすべて、ネットワーク上の Indexer が提供するデータに依存しています。現在、The Graph Network には 200 以上のサブグラフが登録されており、クエリフィーを生成し、Web3 データのインデックスを積極的に作成しています。 +これは、サブグラフをホスティングサービスから The Graph の分散型ネットワークに移行する方法について説明したガイドです。The Graph Network への移行は、Opyn, UMA, mStable, Audius, PoolTogether, Livepeer, RAI, Enzyme, DODO, Opyn, Pickle, BadgerDAO などのプロジェクトで成功し、これらはすべてネットワーク上のインデクサーが提供するデータに依存しています。現在、The Graph Network では 700 以上のサブグラフが稼動しており、クエリフィーを生成し、Web3 データのインデックス作成を積極的に行っています。 これで、分散型ネットワークへの移行やサブグラフの管理方法について、必要なことがすべてわかるようになります。移行作業は短時間で完了し、サブグラフは The Graph Network ならではの信頼性とパフォーマンスを永遠に享受することができます。 -### 既存のサブグラフのグラフネットワークへの移行 +### 仮定 -これで完成です。公開されると、[The Graph Explorer](https://thegraph.com/explorer)でネットワーク上のサブグラフをライブで見ることができるようになります。 +- 私はすでにホストされたサービスにサブグラフを展開しました +- サブグラフは、The Graph Network で利用可能な(またはベータ版で利用可能な)チェーンのインデックスを作成しています。 +- サブグラフは IPFS や全文検索の依存関係を持ちません(これらは分散型ネットワークではまだ完全にサポートされていません) -- 公開はオンチェーンのアクションであり、Ethereum でのガスの支払いが必要になることを覚えておいてください。トランザクションの例は[こちら](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b)で見れます。価格はだいたい 100gwei で 0.0425ETH くらいです。 -- サブグラフをアップグレードする必要がある場合は、アップグレード料金が発生します。アップグレードとは、既存のサブグラフの別バージョンをチェーン上に公開することです。アップグレードには費用がかかりますので、メインネットにデプロイする前に、Rinkeby でサブグラフをデプロイしてテストすることを強くお勧めします。また、そのサブグラフにシグナルがない場合、場合によっては GRT が必要になることもあります。そのサブグラフのバージョンにシグナル/キュレーションがある場合(auto-migrate を使用)、税金は分割されます。 -- イーサリアムメインネット以外のチェーンをインデックス化 +## 既存のサブグラフをグラフネットワークに移行する -### ネットワーク上のサブグラフのアップグレード +> サブグラフに固有のコマンドは、[Subgraph Studio](https://thegraph.com/studio/)で確認することができます。 1. 最新版の graph-cli をインストールする: @@ -28,26 +28,29 @@ npm install -g @graphprotocol/graph-cli yarn global add @graphprotocol/graph-cli ``` -2. [Subgraph Studio](https://thegraph.com/studio/)でサブグラフを作成する。その方法については、[Subgraph Studio のドキュメント](/deploying/subgraph-studio)や[ビデオチュートリアル](https://www.youtube.com/watch?v=HfDgC2oNnwo)で説明されています。 -3. メイン・プロジェクトのサブグラフ・リポジトリ内で、スタジオ上でデプロイとビルドを行うためにサブグラフを認証します。 +subgraph.yaml の`apiVersion`が`0.0.5`以上であることを確認してください。 + +2. メイン・プロジェクトのサブグラフ・リポジトリ内で、スタジオ上でデプロイとビルドを行うためにサブグラフを認証します。 ```sh graph auth --studio ``` -4. ファイルを生成し、サブグラフをビルドする: +3. ファイルを生成し、サブグラフをビルドする: ```sh graph codegen && graph build ``` -5. サブグラフをスタジオにデプロイします。Studio の UI で、サブグラフの名前に基づいた``を見つけることができます。 +サブグラフにビルドエラーがある場合は、[AssemblyScript Migration Guide](/release-notes/assemblyscript-migration-guide/) を参照してください。 + +4. ウォレットで[Subgraph Studio](https://thegraph.com/studio/)にサインインし、サブグラフをデプロイしてください。スタジオの UI で、サブグラフの名前に基づいた``を見つけることができます。 ```sh - graph deploy --studio +graph deploy --studio ``` -6. スタジオのプレイグラウンドでクエリをテストします。ここでは、[Sushi - Mainnet Exchange Subgraph](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&view=Playground)の例を示します。 +5. スタジオのプレイグラウンドでクエリをテストします。ここでは、[Sushi - Mainnet Exchange Subgraph](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&view=Playground)の例を示します。 ```sh { @@ -64,21 +67,82 @@ graph codegen && graph build } ``` -7. 説明とサブグラフの詳細を記入し、最大 3 つのカテゴリーを選択してください。必要であれば、スタジオにプロジェクト画像をアップロードしてください。 -8. Publish ボタンを押して、The Graph's Network にサブグラフを公開します。 +6. この時点で、サブグラフは Subgraph Studio 上にデプロイされましたが、分散ネットワークにはまだ公開されていません。サブグラフが意図したとおりに動作しているか、右上の一時的なクエリ URL を用いてテストすることができます。この名前が示すように、これは一時的な URL であり、実運用に使用すべきではありません。 + +- 公開はオンチェーン アクションであり、イーサリアムでガスを支払う必要があります。トランザクションの例は、[こちら](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b)をご覧ください。 100 gwei で 0.0425 ETH。 +- サブグラフをアップグレードする必要がある場合は、アップグレード料金が発生します。アップグレードとは、既存のサブグラフの別バージョンをチェーン上に公開することです。アップグレードには費用がかかりますので、メインネットにデプロイする前に、Rinkeby でサブグラフをデプロイしてテストすることを強くお勧めします。また、そのサブグラフにシグナルがない場合、場合によっては GRT が必要になることもあります。そのサブグラフのバージョンにシグナル/キュレーションがある場合(auto-migrate を使用)、税金は分割されます。 + +7. 「Publish」ボタンを押して、サブグラフを The Graph の分散型ネットワーク上に公開する。 + +以上です!公開が完了すると、[The Graph Explorer](https://thegraph.com/explorer) を介して分散ネットワーク上でサブグラフをライブで表示できるようになります。 + +Discord の [#Curators チャンネル](https://discord.gg/rC8rBuRtbH) を自由に活用して、キュレーターにサブグラフが通知される準備ができていることを知らせてください。また、予想されるクエリ数を共有していただけると助かります。したがって、彼らはあなたのサブグラフでどれだけの GRT を通知する必要があるかを見積もることができます。 + +### API キーの作成 + +API キーは、Subgraph Studio の[こちら](https://thegraph.com/studio/apikeys/)で生成することができます。 + +![APIキー作成ページ](/img/api-image.png) + +毎週末に、その期間に発生したクエリフィーに基づいて請求書が作成されます。この請求書は、お客様の残高にある GRT を使用して自動的に支払われます。クエリ費用が引き落とされた後、残高が更新されます。クエリフィーは、ポリゴンネットワークを経由して GRT で支払われます。API キーを有効にするには、以下の手順で Polygon の課金契約に GRT を追加する必要があります。 + +- ご希望の取引所で GRT をご購入ください。 +- GRT をウォレットに送る. +- Studio の Billing ページで「Add GRT」をクリックします。 + +![GRTを課金に追加](/img/Add-GRT-New-Page.png) + +- 手順に沿って、GRT を課金バランスに追加してください。 +- GRT は自動的に Arbitrum のネットワークにブリッジされ、課金バランスに加算されます。 + +![請求ペイン](/img/New-Billing-Pane.png) + +> 注意:GRT を課金バランスに追加するための詳しい説明は、[公式課金ページ](.../billing.mdx)をご覧ください。 + +### API キーの確保 + +API は 2 つの方法で利用を制限し、セキュリティを確保することが推奨されます。 + +1. オーソライズド・サブグラフ +2. オーソライズド・ドメイン + +API キーは[こちら](https://thegraph.com/studio/apikeys/test/)で確保することができます。 -- 100,000 GRT が、サブグラフの v1 で auto-migrate を使用してシグナリングされます。 -- 100,000 GRT が新しいボンディングカーブに移行され、97,500 GRT が新しいカーブに入り、2,500 GRT がバーンされます。 +![サブグラフのロックダウンページ](/img/subgraph-lockdown.png) -ネットワーク上の既存のサブグラフをアップグレードしたい場合は、Graph CLI を使ってサブグラフの新バージョンを Subgraph Studio にデプロイすることで行うことができます。 +### 分散ネットワーク上の自分のサブグラフをクエリ -アップグレードには、旧バージョンのサブグラフから新バージョンへの GRT の移行が必要です。つまり、アップグレードのたびに、新しいボンディングカーブが作成されます(ボンディングカーブの詳細は[こちら](/network/curating#bonding-curve-101))。 +これで、ネットワーク上の Indexers のインデックス作成状況をグラフエクスプローラで確認できます(例[こちら](https://thegraph.com/explorer/subgraph?id=S9ihna8D733WTEShJ1KctSTCvY1VJ7gdVwhUujq4Ejo&view=Indexers))。上部の緑の線は、投稿時に 8 つのインデクサーがそのサブグラフのインデックス付けに成功したことを示します。また、Indexer タブでは、どのインデクサーがあなたのサブグラフをピックアップしたかを見ることができます。 -### オーナーアップグレード料金 +![Rocket Poolのサブグラフ](/img/rocket-pool-subgraph.png) -新しいボンディングカーブは、新バージョンに移行されるすべての GRT に対して 2.5%のキュレーション税を請求します。オーナーはこのうちの 50%、つまり 1.25%を支払う必要があります。残りの 1.25%はキュレーター全員が手数料として吸収します。このようなインセンティブ設計は、サブグラフのオーナーが再帰的なアップグレードコールでキュレーターの資金をすべて使い果たしてしまうことを防ぐために設けられています。以下の例は、あなたのサブグラフが積極的にキュレーションされている場合に限ります。キュレーション活動が行われていない場合、自分のサブグラフで自分にシグナルを送るためには、最低でも 100GRT を支払わなければなりません。 +最初のインデクサーがあなたのサブグラフを完全にインデックス化したら、分散ネットワーク上でサブグラフのクエリを開始することができます。クエリ URL を取得するためには、クエリ URL の横にある記号をクリックしてコピー&ペーストしてください。以下のような画面が表示されます。 -1. 現在のサブグラフに変更を加える。Rinkeby に公開して Subgraph Studio 上で小さな修正をテストするのが良いアイデアでしょう。 +`https://gateway.thegraph.com/api/[api-key]/subgraphs/id/S9ihna8D733WTEShJ1KctSTCvY1VJ7gdVwhUujq4Ejo` + +重要: `[api-key]` は、必ず上記のセクションで生成された実際の API キーに置き換えてください。 + +この Query URL をダップ内で使用して、GraphQL リクエストを送信することができます。 + +おめでとうございます。あなたは今、分散化のパイオニアです! + +> 注意: ネットワークが分散しているため、異なるインデクサーが異なるブロックまでインデックスを作成していることがあります。新鮮なデータだけを受け取るために、ブロックを使ってクエリを提供するために、 インデクサがインデックスを作成していなければならない最小のブロックを指定することができます。`{ number_gte: $minBlock }` フィールド引数で、以下の例のように指定します。 + +```graphql +{ + stakers(block: { number_gte: 14486109 }) { + id + } +} +``` + +ネットワークの性質や再起動の扱いについての詳細は、ドキュメントの記事[Distributed Systems](/querying/distributed-systems/)で説明されています。 + +## ネットワーク上のサブグラフのアップグレード + +ネットワーク上の既存のサブグラフをアップグレードする場合は、Graph CLI を使用してサブグラフの新しいバージョンを Subgraph Studio にデプロイすることでこれを行うことができます。 + +1. 現在のサブグラフに変更を加える。Goerli に公開して Subgraph Studio 上で小さな修正をテストするのが良いアイデアでしょう。 2. 以下のようにデプロイし、コマンドに新しいバージョンを指定します(例:v0.0.1、v0.0.2 など)。 ```sh @@ -88,31 +152,31 @@ graph deploy --studio 3. Subgraph Studio のプレイグラウンドでクエリを実行し、新バージョンをテストします。 4. 新しいバージョンを The Graph Network で公開します。これにはガスが必要であることを忘れてはなりません(上のセクションで説明)。 -### サブグラフの安定版の維持 +### 所有者のアップグレード料金: 詳細 アップグレードには、旧バージョンのサブグラフから新バージョンのサブグラフへの GRT の移行が必要です。つまり、アップグレードのたびに、新しいボンディングカーブが作成されます(ボンディングカーブについての詳細は[こちら](/network/curating#bonding-curve-101)) -サブグラフに多くの変更を加えている場合、継続的にアップグレードしてアップグレード費用を負担するのは得策ではありません。サブグラフの安定した一貫性のあるバージョンを維持することは、コストの観点からだけでなく、インデクサーが自信を持って同期時間を設定できるようにするためにも重要です。アップグレードを計画する際には、インデクサーの同期時間に影響が出ないように、インデクサにフラグを立てる必要があります。Discord の[#Indexers channel](https://discord.gg/8tgJ7rKW)チャンネルを利用して、サブグラフのバージョンアップをインデクサーに知らせることができます。 +新しい結合曲線では、新しいバージョンに移行されるすべての GRT に対して 2.5% のキュレーション税が課されます。所有者は、この 50% または 1.25% を支払わなければなりません。残りの 1.25% は、手数料としてすべてのキュレーターによって吸収されます。サブグラフの所有者が再帰的なアップグレード呼び出しでキュレーターのすべての資金を使い果たすことができないようにするための場所です。キュレーション活動がない場合は、独自のサブグラフを通知するために最低 100 GRT を支払う必要があります。 -サブグラフは外部の開発者が利用するオープン API です。オープン API は、外部の開発者のアプリケーションを壊さないように、厳格な基準に従う必要があります。The Graph Network では、サブグラフの開発者は、インデクサーが新しいサブグラフを同期するのにかかる時間や、自分のサブグラフを使用している他の開発者のことを考慮しなければなりません。 +例を挙げてみましょう。これは、サブグラフが積極的にキュレートされている場合にのみ当てはまります。 -- ENS を設定する: https://app.ens.domains/ -- ENS 名を[こちら](https://thegraph.com/explorer/settings?view=display-name)の設定に追加します。 +- サブグラフの v1 で自動移行を使用して 100,000 GRT が通知される +- 所有者は v2 にアップグレードします。 100,000 GRT が新しい結合曲線に移行され、そこで 97,500 GRT が新しい曲線に入れられ、2,500 GRT がバーンされます - 所有者は料金の半分の 1250GRT をバーンすることができます。アップグレードの前に、この資金をウォレットに用意しておかなければなりません。この操作は、アップグレードと同じトランザクションで行われます。 _このメカニズムは現在ネットワーク上で稼動していますが、現在コミュニティでは、サブグラフ開発者のアップグレードコストを削減する方法について議論しています。_ -### サブグラフのメタデータの更新 +### サブグラフの安定したバージョンの維持 -「**Update Subgraph Details in Explorer**」がチェックされていることを確認し、「**Save**」をクリックします。これがチェックされていると、新しいデプロイメントで新しいバージョンを公開することなく、エクスプローラでサブグラフの詳細を更新するオンチェーン トランザクションが生成されます。 +サブグラフに多くの変更を加えている場合、継続的にアップグレードしてアップグレード費用を負担するのは得策ではありません。サブグラフの安定した一貫性のあるバージョンを維持することは、コストの観点からだけでなく、インデクサーが自信を持って同期時間を設定できるようにするためにも重要です。アップグレードを計画する際には、インデクサーの同期時間に影響が出ないように、インデクサにフラグを立てる必要があります。Discord の[#Indexers channel](https://discord.gg/8tgJ7rKW)チャンネルを利用して、サブグラフのバージョンアップをインデクサーに知らせることができます。 -プロフィールが充実しているほど、サブグラフがインデックスやキュレーションされる可能性が高くなります。 +サブグラフは、外部の開発者が活用しているオープン API です。オープン API は、外部開発者のアプリケーションを壊さないように、厳格な基準に従う必要があります。 The Graph Network では、サブグラフの開発者は、インデクサーと、新しいサブグラフを同期するのにかかる時間を考慮する必要があります**、およびサブグラフを使用している他の開発者**。 -### ネットワーク上でのクエリ費用の見積もり +### サブグラフのメタデータの更新 -サブグラフを廃止し、The Graph Network から削除するには、[こちら](/managing/deprecating-a-subgraph) の手順に従います。 +新しいバージョンを公開しなくても、サブグラフのメタデータを更新できます。メタデータには、サブグラフ名、画像、説明、Web サイトの URL、ソース コードの URL、およびカテゴリが含まれます。開発者は、該当するすべてのフィールドを編集できる Subgraph Studio でサブグラフの詳細を更新することで、これを行うことができます。 -ホステッドサービスは、開発者が自分のサブグラフを自由にデプロイできるように設定されています。 +**エクスプローラーでサブグラフの詳細を更新** がチェックされていることを確認し、**保存** をクリックします。これがチェックされている場合、新しい展開で新しいバージョンを公開する必要なく、Explorer のサブグラフの詳細を更新するオンチェーン トランザクションが生成されます。 ## グラフネットワークにサブグラフを展開する際のベストプラクティス @@ -125,21 +189,21 @@ _このメカニズムは現在ネットワーク上で稼動していますが ## The Graph Network のサブグラフを廃止する -The Graph Network が真の意味で分散化されるためには、プロトコルのインセンティブの中核としてクエリ料が支払われる必要があります。API の購読やクエリフィーの支払いに関する詳細は、[こちら](/querying/billing)の課金ドキュメントをご覧ください。 +サブグラフを廃止し、The Graph Network から削除するには、[こちら](/managing/deprecating-a-subgraph) の手順に従います。 ## The Graph Network でのサブグラフのクエリと課金について -製品の UI にはまだ反映されていませんが、1 ヶ月に支払う金額を予想されるクエリ量で割ることで、クエリごとの最大予算を設定することができます。 +Hosted Service は、開発者が制限なくサブグラフを展開できるように設定されました。 -クエリの予算は自分で決めることができますが、インデクサーがその価格でクエリを提供してくれる保証はありません。ゲートウェイが、あなたが支払ってもよいと考えている価格以下でクエリを提供してくれるインデクサを紹介してくれた場合、あなたは予算**と**その価格の差分を支払うことになります。その結果、クエリ価格が低ければ、利用できるインデクサーの数が減り、受けるサービスの質に影響が出る可能性があります。クエリ価格が高いと、キュレーションや有名なインデクサーをサブグラフに引き寄せることができるので、有益です。 +The Graph Network が真の意味で分散化されるためには、プロトコルのインセンティブの中核としてクエリ料が支払われる必要があります。API の購読やクエリフィーの支払いに関する詳細は、[こちら](/billing/)の課金ドキュメントをご覧ください。 ### ネットワーク上でのクエリ料の算出 -これはダイナミックで成長中の市場ですが、どのように関わるかは自分でコントロールできることを忘れないでください。プロトコルにもゲートウェイにも、上限や下限の価格は指定されていません。例えば、ネットワーク上のいくつかの dapps が支払う価格(週単位)を以下に示します。最後の列は GRT でのクエリ料を示していますのでご覧ください。例えば、[Pickle Finance](https://www.pickle.finance/)は 1 秒あたり 8 回のリクエストがあり、1 週間で 2.4GRT を支払っています。 +これは製品 UI のライブ機能ではありませんが、1 か月に支払ってもよい金額を予想クエリ量で割ることで、クエリごとの最大予算を設定できます。 クエリ料は各自で決定できますが、インデクサーがその価格でクエリを提供する保証はありません。もしゲートウェイが、ユーザーが支払おうとする価格か、それよりも低い価格でクエリを提供するインデクサーとマッチングできた場合、予算** と**価格の差分を支払うことになります。結果として、クエリ料が低いと、利用できるインデクサープールが減少し、受けられるサービスの品質に影響を与える可能性があります。高いクエリ料は、あなたのサブグラフにキュレーションや有名なインデクサーを引き寄せるインセンティブを持つことから、有益になります。 -まだよくわからないという方も、ご安心ください。以下のリソースをチェックしたり、分散型ネットワークへのサブグラフの移行に関するビデオガイドをご覧ください: +これはダイナミックで成長中の市場ですが、どのように関わるかは自分でコントロールできることを忘れないでください。プロトコルにもゲートウェイにも、上限や下限の価格は指定されていません。例えば、ネットワーク上のいくつかの dapps が支払う価格(週単位)を以下に示します。最後の列は GRT でのクエリ料を示していますのでご覧ください。例えば、Pickle Finance は 1 秒あたり回のリクエストがあり、1 週間で GRT を支払っています。 ![クエリ料](/img/QueryFee.png) diff --git a/website/pages/ja/cookbook/subgraph-debug-forking.mdx b/website/pages/ja/cookbook/subgraph-debug-forking.mdx index 01e4665466cd..c0481bd88049 100644 --- a/website/pages/ja/cookbook/subgraph-debug-forking.mdx +++ b/website/pages/ja/cookbook/subgraph-debug-forking.mdx @@ -1,5 +1,5 @@ --- -title: フォークを使った迅速で簡単なサブグラフのデバッギング +title: フォークを用いた迅速かつ容易なサブグラフのデバッグ --- 大量のデータを処理する多くのシステムと同様に、The Graph の Indexers(グラフノード)は、サブグラフとターゲットブロックチェーンの同期にかなりの時間がかかる場合があります。デバッグを目的とした素早い変更と、インデックス作成に必要な長い待ち時間の不一致は非常に逆効果であり、私たちはそれを十分に認識しています。そこで、[LimeChain](https://limechain.tech/)が開発した**subgraph forking**を導入し、今回はこの機能を使ってサブグラフのデバッグを大幅に高速化する方法を紹介します。 @@ -18,7 +18,7 @@ title: フォークを使った迅速で簡単なサブグラフのデバッギ ## コードを見てみましょう -サブグラフのデバッグに集中するために、物事をシンプルにして、Ethereum Gravity スマートコントラクトのサブグラフのインデックス作成の[例](https://github.com/graphprotocol/example-subgraph)に沿って実行しましょう。 +サブグラフのデバッグに集中するために、物事をシンプルにして、Ethereum Gravity スマートコントラクトのサブグラフのインデックス作成の[例](https://github.com/graphprotocol/example-subgraphs/tree/main/ethereum/gravatar)に沿って実行しましょう。 以下は、`Gravatar`のインデックスを作成するために定義されたハンドラで、バグが全くありません。 @@ -65,7 +65,7 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { さて、ここで 2 つの疑問が生じます: 1. フォークベースとは? -2. 誰がフォークするのか? +2. フォーキングは誰ですか? 回答: @@ -98,5 +98,5 @@ $ cargo run -p graph-node --release -- \ ``` 3. ローカルの Graph ノードが出力するログを調べてみると、すべてうまくいっていることがわかります。 -4. バグのないサブグラフをリモートの Graph ノードにデプロイすることができました。 -5. 完了です。 +4. バグのないサブグラフをリモート グラフ ノードにデプロイし、その後ずっと幸せに暮らしています。 (じゃがいもはありません) +5. 終わり diff --git a/website/pages/ja/cookbook/subgraph-uncrashable.mdx b/website/pages/ja/cookbook/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..e3a4619372c0 --- /dev/null +++ b/website/pages/ja/cookbook/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: 安全なサブグラフのコード生成 +--- + +[Subgraph Uncrashable](https://float-capital.github.io/float-subgraph-uncrashable/)は、プロジェクトの graphql スキーマからヘルパー関数のセットを生成するコード生成ツールです。これにより、サブグラフ内のエンティティとのすべてのインタラクションが完全に安全で一貫性のあるものになることを保証します。 + +### Subgraph Uncrashable と統合する理由は? + +- **継続的なアップタイム**です。誤って処理されたエンティティによってサブグラフがクラッシュすることがあり、The Graph に依存しているプロジェクトに支障をきたすことがあります。ヘルパー関数を設定して、サブグラフを「クラッシュしない」ようにし、ビジネスの継続性を確保しましょう。 + +- **完全な安全**です。サブグラフの開発でよく見られる問題は、未定義のエンティティのロード、エンティティのすべての値の設定または初期化、エンティティのロードと保存のレースコンディションの問題です。エンティティとのすべてのインタラクションが完全にアトミックであることを確認する。 + +- **ユーザー設定可能** デフォルト値を設定し、個々のプロジェクトのニーズに合ったセキュリティチェックのレベルを設定することができます。サブグラフのロジックに違反している箇所を示す警告ログが記録され、データの正確性を確保するために問題の修正に役立ちます。 + +**主な特徴** + +- コード生成ツールは、**すべての**サブグラフ・タイプに対応し、ユーザーが値を正当に設定できるように設定可能です。コード生成は、この設定を用いて、ユーザの仕様に沿ったヘルパー関数を生成します。 + +- また、このフレームワークには、エンティティ変数のグループに対して、カスタムだが安全なセッター関数を作成する方法が(設定ファイルを通じて)含まれています。この方法では、ユーザーが古いグラフ・エンティティをロード/使用することは不可能であり、また、関数が必要とする変数の保存や設定を忘れることも不可能です。 + +- 警告ログは、サブグラフのロジックに違反がある場所を示すログとして記録され、データの正確性を確保するための問題の修正に役立ちます。これらのログは、The Graph のホスティングサービスの「Logs」セクションで確認することができます。 + +Subgraph Uncrashable は、Graph CLI codegen コマンドでオプションのフラグとして実行することができます。 + +```sh +graph codegen -u [options] [] +``` + +[subgraph uncrashable documentation](https://float-capital.github.io/float-subgraph-uncrashable/docs/)や[video tutorial](https://float-capital.github.io/float-subgraph-uncrashable/docs/tutorial)で、より安全なサブグラフの開発について詳しく知ることができます。 diff --git a/website/pages/ja/deploying/deploying-a-subgraph-to-studio.mdx b/website/pages/ja/deploying/deploying-a-subgraph-to-studio.mdx index a24a5bbaf199..2bdeea481cdd 100644 --- a/website/pages/ja/deploying/deploying-a-subgraph-to-studio.mdx +++ b/website/pages/ja/deploying/deploying-a-subgraph-to-studio.mdx @@ -1,10 +1,12 @@ --- -title: Subgraph Studioへのサブグラフのデプロイ +title: Subgraph Studio にサブグラフをデプロイする --- -Subgraph Studio へのサブグラフのデプロイメントは非常に簡単です。ここでは、以下の手順を説明します: +> サブグラフがデータをインデックスするネットワークが、分散型ネットワークで[サポートされている](/developing/supported-chains)ことを確認します。 -- Graph CLI をインストールする(yarn と npm の両方で) +こちらが Subgraph Studio にサブグラフをデプロイする手順です: + +- Graph CLI をインストールする(yarn または npm を使用) - Subgraph Studio でサブグラフを作成する - CLI から自分のアカウントを認証する - Subgraph Studio にサブグラフをデプロイする @@ -50,7 +52,7 @@ Subgraph Studio にサブグラフをデプロイする前に、CLI で自分の 以下は、CLI から認証を行うために必要なコマンドです: ```bash -graph auth --studio graph auth --studio 」 +graph auth --studio 」 ``` ## Subgraph Studio へのサブグラフのデプロイ diff --git a/website/pages/ja/deploying/subgraph-studio-faqs.mdx b/website/pages/ja/deploying/subgraph-studio-faqs.mdx index 7612dddff07b..ed0db754619d 100644 --- a/website/pages/ja/deploying/subgraph-studio-faqs.mdx +++ b/website/pages/ja/deploying/subgraph-studio-faqs.mdx @@ -1,26 +1,30 @@ --- -title: Subgraph StudioのFAQ +title: サブグラフスタジオFAQ --- -### 1. API キーを作成するには? +### 1. Subgraph Studio とは? -Subgraph Studio では、必要に応じて API キーを作成し、それぞれにセキュリティ設定を加えることができます。 +[Subgraph Studio](https://thegraph.com/studio/)は、サブグラフや API キーを作成・管理・公開するための Dapp であり、サブグラフの作成・管理・公開を行う。 -### 2. 複数の API キーを作成できますか? +### 2. API キーを作成するには? + +API を作成するには、Subgraph Studio に移動し、ウォレットを接続します。上部にある API keys タブをクリックします。そこで、API キーを作成することができます。 + +### 3. 複数の API キーを作成できますか? A: はい、できます。異なるプロジェクトで使用するために、[こちら](https://thegraph.com/studio/apikeys/)のリンクをご確認ください。 -### 3. API キーのドメインを制限するには? +### 4. API キーのドメインを制限するには? API キーを作成後、「セキュリティ」セクションで、特定の API キーにクエリ可能なドメインを定義できます。 -### 4. 使用したいサブグラフのクエリ URL はどのように見つけるのですか? +### 5. 自分のサブグラフを他のオーナーに譲渡することはできますか? -各サブグラフのクエリ URL は、「グラフエクスプローラー」の「Subgraph Details」で確認できます。「Query」ボタンをクリックすると、興味のあるサブグラフのクエリ URL が表示されます。ここで、``というプレースホルダーを、Subgraph Studio で利用したい API キーに置き換えることができます。 +はい、メインネットに公開されたサブグラフは、新しいウォレットまたはマルチシグに転送できます。これを行うには、サブグラフの詳細ページの [公開] ボタンの横にある 3 つのドットをクリックし、[所有権を譲渡する] を選択します。 -API キーを作成すると、自分でサブグラフを構築した場合でも、ネットワークに公開されているすべてのサブグラフにクエリを実行できることを覚えておいてください。新しい API キーを介したこれらのクエリは、ネットワーク上の他のクエリと同様に支払われます。 +サブグラフが転送されると、Studio でサブグラフを表示または編集できなくなることに注意してください。 -### 5. 使用したいサブグラフのクエリ URL を見つける方法は? +### 6. 使用したいサブグラフのクエリ URL を見つける方法は? 各サブグラフのクエリ URL は、Graph Explorer の「Subgraph Details」で確認できます。「Query」をクリックすると、興味のあるサブグラフのクエリ URL が表示されます。ここで``というプレースホルダーを、Subgraph Studio で利用したい API キーに置き換えることができます。 diff --git a/website/pages/ja/developing/assemblyscript-api.mdx b/website/pages/ja/developing/assemblyscript-api.mdx index 10e7f09b09c0..65fe1c2c9cac 100644 --- a/website/pages/ja/developing/assemblyscript-api.mdx +++ b/website/pages/ja/developing/assemblyscript-api.mdx @@ -45,6 +45,7 @@ npm install -save-dev @graphprotocol/graph-ts # NPM | バージョン | リリースノート | | :-: | --- | +| 0.0.7 | Ethereum タイプに `TransactionReceipt`と`Log`クラスを追加
Ethereum Event オブジェクトに`receipt`フィールドを追加。 | | 0.0.6 | Ethereum Transaction オブジェクトに`nonce`フィールドを追加 イーサリアムブロックオブジェクトに
Added `baseFeePerGas`を追加 | | 0.0.5 | AssemblyScript がバージョン 0.19.10 にアップグレード(変更点がありますので[`Migration Guide`](/release-notes/assemblyscript-migration-guide))をご覧ください)。
`ethereum.transaction.gasUsed`の名前が`ethereum.transaction.gasLimit`に変更 | | 0.0.4 | Ethereum SmartContractCall オブジェクトに`functionSignature`フィールドを追加 | @@ -65,7 +66,7 @@ AssemblyScript に組み込まれている基本型のドキュメントは[Asse `ByteArray`は、`u8`の配列を表します。 -_構造_ +_工事_ - `fromI32(x: i32): ByteArray` - Decomposes `x` into bytes. - `fromHexString(hex: string): ByteArray` - Input length must be even. Prefixing with `0x` is optional. @@ -82,7 +83,7 @@ _オペレーター_ - `equals(y: ByteArray): bool` – can be written as `x == y`. - `concat(other: ByteArray) : ByteArray` - return a new `ByteArray` consisting of `this` directly followed by `other` -- `concatI32(other: i32) : ByteArray` - return a new `ByteArray` consisting of `this` directly follow by the byte representation of `other` +- `concatI32(other: i32) : ByteArray` - return a new `ByteArray` consisting of `this` directly followed by the byte representation of `other` #### BigDecimal @@ -92,7 +93,9 @@ _オペレーター_ `BigDecimal`は、任意の精度の小数を表現するために使用されます。 -_構造_ +> 注: [内部的には](https://github.com/graphprotocol/graph-node/blob/master/graph/src/data/store/scalar.rs) `BigDecimal` は [IEEE-754 decimal128 浮動小数点フォーマット](https://en.wikipedia.org/wiki/Decimal128_floating-point_format) で保存されており、これは小数点以下の 34 桁をシグニフィカントでサポートします。このため、`BigDecimal` は、Solidity [`ufixed256x18`](https://docs.soliditylang.org/en/latest/types.html#fixed-point-numbers) などのように 34 桁より広い固定小数点を表現するには不向きです。 + +_工事_ - `constructor(bigInt: BigInt)` – creates a `BigDecimal` from an `BigInt`. - `static fromString(s: string): BigDecimal` – parses from a decimal string. @@ -125,7 +128,7 @@ _数学_ `BigInt`クラスの API は以下の通りです。 -_構造_ +_工事_ - `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32` - `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string @@ -136,7 +139,7 @@ _構造_ - `x.toHex(): string` – turns `BigInt` into a string of hexadecimal characters. - `x.toString(): string` – turns `BigInt` into a decimal number string. -- `x.toI32(): i32` – returns the `BigInt` as an `i32`; fails if it the value does not fit into `i32`. It's a good idea to first check `x.isI32()`. +- `x.toI32(): i32` – returns the `BigInt` as an `i32`; fails if the value does not fit into `i32`. It's a good idea to first check `x.isI32()`. - `x.toBigDecimal(): BigDecimal` - converts into a decimal with no fractional part. _数学_ @@ -169,9 +172,9 @@ _数学_ '@graphprotocol/graph-ts'から { TypedMap } をインポートします。 ``` -`TypedMap` はキーと値のペアを格納するために使用することができます。 [この例](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51)を参照してください。 +`TypedMap` can be used to store key-value pairs. See [this example](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). -TypedMap クラスは以下のような API を持っています。 +`TypedMap` クラスには次の API があります - `new TypedMap()` – creates an empty map with keys of type `K` and values of type `T` - `map.set(key: K, value: V): void` – sets the value of `key` to `value` @@ -189,9 +192,9 @@ TypedMap クラスは以下のような API を持っています。 `Bytes`クラスは AssemblyScript の[Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64)を継承しており、`Uint8Array` のすべての機能に加えて、以下の新しいメソッドをサポートしています。 -_構造_ +_工事_ -- `fromHexString(hex: string) : Bytes` - Convert the string `hex` which must consist of an even number of hexadecimal digits to a `ByteArray`. The string `hex` can optionally start with `0x` +- `fromHexString(hex: string) : Bytes` - 文字列 `hex` を `ByteArray` に変換します。これは偶数個の 16 進数で構成される必要があります。文字列 `hex` は、必要に応じて `0x` で開始できます - `fromI32(i: i32) : Bytes` - Convert `i` to an array of bytes _型変換_ @@ -205,7 +208,7 @@ _オペレーター_ - `b.concat(other: Bytes) : Bytes` - - return new `Bytes` consisting of `this` directly followed by `other` - `b.concatI32(other: i32) : ByteArray` - return new `Bytes` consisting of `this` directly follow by the byte representation of `other` -#### Address +#### 住所 ```typescript '@graphprotocol/graph-ts'から { Address } をインポートします。 @@ -213,24 +216,24 @@ _オペレーター_ `Address` extends `Bytes` to represent Ethereum `address` values. -It adds the following method on top of the `Bytes` API: +`Bytes`の API の上に以下のメソッドを追加しています。 - `Address.fromString(s: string): Address` – creates an `Address` from a hexadecimal string - `Address.fromBytes(b: Bytes): Address` – create an `Address` from `b` which must be exactly 20 bytes long. Passing in a value with fewer or more bytes will result in an error -### Store API +### ストア API ```typescript '@graphprotocol/graph-ts'から { store } をインポートします。 ``` -The `store` API allows to load, save and remove entities from and to the Graph Node store. +`store` API は、グラフノードのストアにエンティティを読み込んだり、保存したり、削除したりすることができます。 -Entities written to the store map one-to-one to the `@entity` types defined in the subgraph's GraphQL schema. To make working with these entities convenient, the `graph codegen` command provided by the [Graph CLI](https://github.com/graphprotocol/graph-cli) generates entity classes, which are subclasses of the built-in `Entity` type, with property getters and setters for the fields in the schema as well as methods to load and save these entities. +ストアに書き込まれたエンティティは、サブグラフの GraphQL スキーマで定義された`@entity`タイプに一対一でマッピングされます。 これらのエンティティの扱いを便利にするために、[Graph CLI](https://github.com/graphprotocol/graph-cli)で提供される `graph codegen` コマンドは、組み込みの`Entity`型のサブクラスであるエンティティ・クラスを生成します。 #### エンティティの作成 -The following is a common pattern for creating entities from Ethereum events. +Ethereum のイベントからエンティティを作成する際の一般的なパターンを以下に示します。 ```typescript // Import the Transfer event class generated from the ERC20 ABI @@ -255,13 +258,13 @@ export function handleTransfer(event: TransferEvent): void { } ``` -When a `Transfer` event is encountered while processing the chain, it is passed to the `handleTransfer` event handler using the generated `Transfer` type (aliased to `TransferEvent` here to avoid a naming conflict with the entity type). This type allows accessing data such as the event's parent transaction and its parameters. +チェーンの処理中に`Transfer` イベントが発生すると、生成された`Transfer`タイプ(ここではエンティティタイプとの名前の衝突を避けるために`TransferEvent`とエイリアスされています)を使用して、`handleTransfer`イベントハンドラに渡されます。 このタイプでは、イベントの親トランザクションやそのパラメータなどのデータにアクセスすることができます。 -Each entity must have a unique ID to avoid collisions with other entities. It is fairly common for event parameters to include a unique identifier that can be used. Note: Using the transaction hash as the ID assumes that no other events in the same transaction create entities with this hash as the ID. +各エンティティは、他のエンティティとの衝突を避けるために、ユニークな ID を持たなければなりません。 イベントのパラメータには、使用可能な一意の識別子が含まれているのが一般的です。 注:トランザクションのハッシュを ID として使用することは、同じトランザクション内の他のイベントがこのハッシュを ID としてエンティティを作成しないことを前提としています。 #### ストアからのエンティティの読み込み -If an entity already exists, it can be loaded from the store with the following: +エンティティがすでに存在する場合、以下の方法でストアからロードすることができます。 ```typescript let id = event.transaction.hash // or however the ID is constructed @@ -273,18 +276,18 @@ if (transfer == null) { // Use the Transfer entity as before ``` -As the entity may not exist in the store yet, the `load` method returns a value of type `Transfer | null`. It may thus be necessary to check for the `null` case before using the value. +エンティティはまだストアに存在していない可能性があるため、`load`メソッドは`Transfer | null`型の値を返します。 そのため、値を使用する前に、`null`のケースをチェックする必要があるかもしれません。 > **Note:** エンティティのロードは、マッピングでの変更がエンティティの以前のデータに依存する場合にのみ必要です。 既存のエンティティを更新する 2 つの方法については、次のセクションを参照してください。 #### 既存のエンティティの更新 -There are two ways to update an existing entity: +既存のエンティティを更新するには 2 つの方法があります。 1. `Transfer.load(id)`などでエンティティをロードし、エンティティにプロパティを設定した後、`.save()`でストアに戻す。 2. 単純に`new Transfer(id)`でエンティティを作成し、エンティティにプロパティを設定し、ストアに `.save()`します。 エンティティがすでに存在する場合は、変更内容がマージされます。 -Changing properties is straight forward in most cases, thanks to the generated property setters: +プロパティの変更は、生成されたプロパティセッターのおかげで、ほとんどの場合、簡単です。 ```typescript let transfer = new Transfer(id) @@ -293,16 +296,16 @@ transfer.to = ... transfer.amount = ... ``` -It is also possible to unset properties with one of the following two instructions: +また、次の 2 つの命令のいずれかで、プロパティの設定を解除することも可能です。 ```typescript transfer.from.unset() transfer.from = null ``` -This only works with optional properties, i.e. properties that are declared without a `!` in GraphQL. Two examples would be `owner: Bytes` or `amount: BigInt`. +これは、オプションのプロパティ、つまり GraphQL で`!`を付けずに宣言されているプロパティでのみ機能します。 例としては、`owner: Bytes`や`amount: BigInt`です。 -Updating array properties is a little more involved, as the getting an array from an entity creates a copy of that array. This means array properties have to be set again explicitly after changing the array. The following assumes `entity` has a `numbers: [BigInt!]!` field. +エンティティから配列を取得すると、その配列のコピーが作成されるため、配列のプロパティの更新には少し手間がかかります。 つまり、配列を変更した後は、明示的に配列のプロパティを設定し直す必要があります。 次の例では、`entity` が `numbers: [BigInt!]!` を持っていると仮定します。 ```typescript // This won't work @@ -318,10 +321,10 @@ entity.save() #### ストアからのエンティティの削除 -There is currently no way to remove an entity via the generated types. Instead, removing an entity requires passing the name of the entity type and the entity ID to `store.remove`: +現在、生成された型を使ってエンティティを削除する方法はありません。 代わりに、エンティティを削除するには、エンティティタイプの名前とエンティティ ID を`store.remove`に渡す必要があります。 ```typescript -import { store } from '@graphprotocol/graph-ts' +mport { store } from '@graphprotocol/graph-ts' ... let id = event.transaction.hash store.remove('Transfer', id) @@ -329,15 +332,15 @@ store.remove('Transfer', id) ### Ethereum API -The Ethereum API provides access to smart contracts, public state variables, contract functions, events, transactions, blocks and the encoding/decoding Ethereum data. +Ethereum API は、スマートコントラクト、パブリックステート変数、コントラクト関数、イベント、トランザクション、ブロック、および Ethereum データのエンコード/デコードへのアクセスを提供します。 #### Ethereum タイプのサポート -As with entities, `graph codegen` generates classes for all smart contracts and events used in a subgraph. For this, the contract ABIs need to be part of the data source in the subgraph manifest. Typically, the ABI files are stored in an `abis/` folder. +エンティティと同様に、`graph codegen`は、サブグラフで使用されるすべてのスマートコントラクトとイベントのためのクラスを生成します。 このためには、コントラクト ABI がサブグラフマニフェストのデータソースの一部である必要があります。 通常、ABI ファイルは`abis/`フォルダに格納されています。 -With the generated classes, conversions between Ethereum types and the [built-in types](#built-in-types) take place behind the scenes so that subgraph authors do not have to worry about them. +生成されたクラスでは、Ethereum 型と [組み込み型](#built-in-types)の間の変換が背後で行われるため、サブグラフの作成者はそれらを気にする必要がありません。 -The following example illustrates this. Given a subgraph schema like +以下の例で説明します。 以下のようなサブグラフのスキーマが与えられます。 ```graphql type Transfer @entity { @@ -361,7 +364,7 @@ transfer.save() #### イベントとブロック/トランザクションデータ -Ethereum events passed to event handlers, such as the `Transfer` event in the previous examples, not only provide access to the event parameters but also to their parent transaction and the block they are part of. The following data can be obtained from `event` instances (these classes are a part of the `ethereum` module in `graph-ts`): +前述の例の`Transfer`イベントのように、イベントハンドラに渡された Ethereum イベントは、イベントパラメータへのアクセスだけでなく、その親となるトランザクションや、それらが属するブロックへのアクセスも提供します。 `event` インスタンスからは、以下のデータを取得することができます(これらのクラスは、 `graph-ts`の`ethereum`モジュールの一部です)。 ```typescript class Event { @@ -372,6 +375,7 @@ class Event { block: Block transaction: Transaction parameters: Array + receipt: TransactionReceipt | null } class Block { @@ -403,21 +407,49 @@ class Transaction { input: Bytes nonce: BigInt } + +class TransactionReceipt { + transactionHash: Bytes + transactionIndex: BigInt + blockHash: Bytes + blockNumber: BigInt + cumulativeGasUsed: BigInt + gasUsed: BigInt + contractAddress: Address + logs: Array + status: BigInt + root: Bytes + logsBloom: Bytes +} + +class Log { + address: Address + topics: Array + data: Bytes + blockHash: Bytes + blockNumber: Bytes + transactionHash: Bytes + transactionIndex: BigInt + logIndex: BigInt + transactionLogIndex: BigInt + logType: string + removed: bool | null +} ``` #### スマートコントラクトの状態へのアクセス -The code generated by `graph codegen` also includes classes for the smart contracts used in the subgraph. These can be used to access public state variables and call functions of the contract at the current block. +`graph codegen`が生成するコードには、サブグラフで使用されるスマートコントラクトのクラスも含まれています。 これらを使って、パブリックな状態変数にアクセスしたり、現在のブロックにあるコントラクトの関数を呼び出したりすることができます。 -A common pattern is to access the contract from which an event originates. This is achieved with the following code: +よくあるパターンは、イベントが発生したコントラクトにアクセスすることです。 これは以下のコードで実現できます。 ```typescript -// Import the generated contract class -import { ERC20Contract } from '../generated/ERC20Contract/ERC20Contract' +// Import the generated contract class and generated Transfer event class +import { ERC20Contract, Transfer as TransferEvent } from '../generated/ERC20Contract/ERC20Contract' // Import the generated entity class import { Transfer } from '../generated/schema' -export function handleTransfer(event: Transfer) { +export function handleTransfer(event: TransferEvent) { // Bind the contract to the address that emitted the event let contract = ERC20Contract.bind(event.address) @@ -426,13 +458,15 @@ export function handleTransfer(event: Transfer) { } ``` -As long as the `ERC20Contract` on Ethereum has a public read-only function called `symbol`, it can be called with `.symbol()`. For public state variables a method with the same name is created automatically. +`Transfer`は、エンティティタイプとの名前の衝突を避けるために、ここでは`TransferEvent`にエイリアスされています。 + +Ethereum の `ERC20Contract`に`symbol`というパブリックな読み取り専用の関数があれば、`.symbol()`で呼び出すことができます。 パブリックな状態変数については、同じ名前のメソッドが自動的に作成されます。 -Any other contract that is part of the subgraph can be imported from the generated code and can be bound to a valid address. +サブグラフの一部である他のコントラクトは、生成されたコードからインポートすることができ、有効なアドレスにバインドすることができます。 #### リバートされた呼び出しの処理 -If the read-only methods of your contract may revert, then you should handle that by calling the generated contract method prefixed with `try_`. For example, the Gravity contract exposes the `gravatarToOwner` method. This code would be able to handle a revert in that method: +コントラクトの読み取り専用メソッドが復帰する可能性がある場合は、`try_`を前置して生成されたコントラクトメソッドを呼び出すことで対処しなければなりません。 例えば、Gravity コントラクトでは`gravatarToOwner`メソッドを公開しています。 このコードでは、そのメソッドの復帰を処理することができます。 ```typescript let gravity = Gravity.bind(event.address) @@ -444,11 +478,11 @@ if (callResult.reverted) { } ``` -Note that a Graph node connected to a Geth or Infura client may not detect all reverts, if you rely on this we recommend using a Graph node connected to a Parity client. +ただし、Geth や Infura のクライアントに接続された Graph ノードでは、すべてのリバートを検出できない場合があるので、これに依存する場合は Parity のクライアントに接続された Graph ノードを使用することをお勧めします。 #### 符号化/復号化 ABI -Data can be encoded and decoded according to Ethereum's ABI encoding format using the `encode` and `decode` functions in the `ethereum` module. +`ethereum`モジュールの`encode`/ `decode`関数を使用して、Ethereum の ABI エンコーディングフォーマットに従ってデータをエンコード/デコードすることができます。 ```typescript import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts' @@ -465,7 +499,7 @@ let encoded = ethereum.encode(ethereum.Value.fromTuple(tuple))! let decoded = ethereum.decode('(address,uint256)', encoded) ``` -For more information: +その他の情報: - [ABI Spec](https://docs.soliditylang.org/en/v0.7.4/abi-spec.html#types) - Encoding/decoding [Rust library/CLI](https://github.com/rust-ethereum/ethabi) @@ -477,9 +511,9 @@ For more information: '@graphprotocol/graph-ts'から{ log } をインポートします。 ``` -The `log` API allows subgraphs to log information to the Graph Node standard output as well as the Graph Explorer. Messages can be logged using different log levels. A basic format string syntax is provided to compose log messages from argument. +`log` API は、サブグラフがグラフノードの標準出力やグラフエクスプローラに情報を記録するためのものです。 メッセージは、異なるログレベルを使って記録することができます。 基本的なフォーマット文字列の構文が提供されており、引数からログメッセージを構成することができます。 -The `log` API includes the following functions: +`log` API には以下の機能があります: - `log.debug(fmt: string, args: Array): void` - logs a debug message. - `log.info(fmt: string, args: Array): void` - logs an informational message. @@ -487,7 +521,7 @@ The `log` API includes the following functions: - `log.error(fmt: string, args: Array): void` - logs an error message. - `log.critical(fmt: string, args: Array): void` – logs a critical message _and_ terminates the subgraph. -The `log` API takes a format string and an array of string values. It then replaces placeholders with the string values from the array. The first `{}` placeholder gets replaced by the first value in the array, the second `{}` placeholder gets replaced by the second value and so on. +`log` API は、フォーマット文字列と文字列値の配列を受け取ります。 そして、プレースホルダーを配列の文字列値で置き換えます。 最初の`{}`プレースホルダーは配列の最初の値に置き換えられ、2 番目の`{}`プレースホルダーは 2 番目の値に置き換えられ、以下のようになります。 ```typescript log.info('表示されるメッセージ。{}, {}, {}', [value.toString(), anotherValue.toString(), 'すでに文字列']) @@ -497,7 +531,7 @@ log.info('表示されるメッセージ。{}, {}, {}', [value.toString(), anoth ##### 1 つの値を記録する -In the example below, the string value "A" is passed into an array to become`['A']` before being logged: +以下の例では、文字列値 "A" を配列に渡して`['A']` にしてからログに記録しています。 ```typescript let myValue = 'A' @@ -510,7 +544,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### 既存の配列から 1 つのエントリをロギングする -In the example below, only the first value of the argument array is logged, despite the array containing three values. +以下の例では、配列に 3 つの値が含まれているにもかかわらず、引数の配列の最初の値だけがログに記録されます。 ```typescript let myArray = ['A', 'B', 'C'] @@ -523,7 +557,7 @@ export function handleSomeEvent(event: SomeEvent): void { #### 既存の配列から複数のエントリを記録する -Each entry in the arguments array requires its own placeholder `{}` in the log message string. The below example contains three placeholders `{}` in the log message. Because of this, all three values in `myArray` are logged. +引数配列の各エントリは、ログメッセージ文字列に独自のプレースホルダー`{}`を必要とします。 以下の例では、ログメッセージに 3 つのプレースホルダー`{}`が含まれています。 このため、`myArray`の 3 つの値すべてがログに記録されます。 ```typescript let myArray = ['A', 'B', 'C'] @@ -536,7 +570,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### 既存の配列から特定のエントリをロギングする -To display a specific value in the array, the indexed value must be provided. +配列内の特定の値を表示するには、インデックス化された値を指定する必要があります。 ```typescript export function handleSomeEvent(event: SomeEvent): void { @@ -547,7 +581,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### イベント情報の記録 -The example below logs the block number, block hash and transaction hash from an event: +以下の例では、イベントからブロック番号、ブロックハッシュ、トランザクションハッシュをログに記録しています。 ```typescript '@graphprotocol/graph-ts'から { log } をインポートします。 @@ -567,9 +601,9 @@ export function handleSomeEvent(event: SomeEvent): void { '@graphprotocol/graph-ts'から { ipfs } をインポートします。 ``` -Smart contracts occasionally anchor IPFS files on chain. This allows mappings to obtain the IPFS hashes from the contract and read the corresponding files from IPFS. The file data will be returned as `Bytes`, which usually requires further processing, e.g. with the `json` API documented later on this page. +スマートコントラクトは時折、チェーン上の IPFS ファイルをアンカリングします。 これにより、マッピングはコントラクトから IPFS ハッシュを取得し、IPFS から対応するファイルを読み取ることができます。 ファイルのデータは`Bytes`として返されますが、通常は、このページで後述する `json` API などを使ってさらに処理する必要があります。 -Given an IPFS hash or path, reading a file from IPFS is done as follows: +IPFS のハッシュやパスが与えられた場合、IPFS からのファイルの読み込みは以下のように行われます。 ```typescript // Put this inside an event handler in the mapping @@ -582,9 +616,9 @@ let path = 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile' let data = ipfs.cat(path) ``` -**Note:** `ipfs.cat` is not deterministic at the moment. If the file cannot be retrieved over the IPFS network before the request times out, it will return `null`. Due to this, it's always worth checking the result for `null`. To ensure that files can be retrieved, they have to be pinned to the IPFS node that Graph Node connects to. On the [hosted service](https://thegraph.com/hosted-service), this is [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs). See the [IPFS pinning](/developing/creating-a-subgraph#ipfs-pinning) section for more information. +**注:** `ipfs.cat` は今のところ決定論的なものではありません。もし要求がタイムアウトする前に IPFS ネットワーク上でファイルを取得できなければ、 `null`を返します。このため、常に `null` の結果をチェックする価値があります。 -It is also possible to process larger files in a streaming fashion with `ipfs.map`. The function expects the hash or path for an IPFS file, the name of a callback, and flags to modify its behavior: +また、`ipfs.map`.を使って、大きなファイルをストリーミングで処理することも可能です。 この関数は、IPFS ファイルのハッシュまたはパス、コールバックの名前、そして動作を変更するためのフラグを受け取ります。 ```typescript import { JSONValue, Value } from '@graphprotocol/graph-ts' @@ -614,9 +648,9 @@ ipfs.map('Qm...', 'processItem', Value.fromString('parentId'), ['json']) ipfs.mapJSON('Qm...', 'processItem', Value.fromString('parentId')) ``` -The only flag currently supported is `json`, which must be passed to `ipfs.map`. With the `json` flag, the IPFS file must consist of a series of JSON values, one value per line. The call to `ipfs.map` will read each line in the file, deserialize it into a `JSONValue` and call the callback for each of them. The callback can then use entity operations to store data from the `JSONValue`. Entity changes are stored only when the handler that called `ipfs.map` finishes successfully; in the meantime, they are kept in memory, and the size of the file that `ipfs.map` can process is therefore limited. +現在サポートされている唯一のフラグは`json`で、これを`ipfs.map`に渡さなければなりません。 `json`フラグを使用すると、IPFS ファイルは一連の JSON 値で構成され、1 行に 1 つの値が必要です。 `ipfs.map`への呼び出しは、ファイルの各行を読み込み、`JSONValue`にデシリアライズし、それぞれのコールバックを呼び出します。 コールバックは、エンティティ・オペレーションを使って、`JSONValue`からデータを保存することができます。 エンティティの変更は、`ipfs.map`を呼び出したハンドラが正常に終了したときにのみ保存されます。それまでの間は、メモリ上に保持されるため、`ipfs.map`が処理できるファイルのサイズは制限されます。 -On success, `ipfs.map` returns `void`. If any invocation of the callback causes an error, the handler that invoked `ipfs.map` is aborted, and the subgraph is marked as failed. +成功すると,`ipfs.map`は `void`を返します。 コールバックの呼び出しでエラーが発生した場合、`ipfs.map`を呼び出したハンドラは中止され、サブグラフは失敗とマークされます。 ### Crypto API @@ -624,7 +658,7 @@ On success, `ipfs.map` returns `void`. If any invocation of the callback causes '@graphprotocol/graph-ts'から { crypto } をインポートします。 ``` -The `crypto` API makes a cryptographic functions available for use in mappings. Right now, there is only one: +`crypto` API は、マッピングで使用できる暗号化関数を提供します。 今のところ、1 つしかありません。 - `crypto.keccak256(input: ByteArray): ByteArray` @@ -634,14 +668,14 @@ The `crypto` API makes a cryptographic functions available for use in mappings. '@graphprotocol/graph-ts'から{ json, JSONValueKind } をインポートします。 ``` -JSON data can be parsed using the `json` API: +JSON データは、`json` API を使って解析することができます。 -- `json.fromBytes(data: Bytes): JSONValue` – parses JSON data from a `Bytes` array interpreted as a valid UTF-8 sequence +- `json.fromBytes(data: Bytes): JSONValue` – parses JSON data from a `Bytes` array - `json.try_fromBytes(data: Bytes): Result` – safe version of `json.fromBytes`, it returns an error variant if the parsing failed -- `json.fromString(data: string): JSONValue` – parses JSON data from a valid UTF-8 `String` -- `json.try_fromString(data: string): Result` – safe version of `json.fromString`, it returns an error variant if the parsing failed +- `json.fromString(data: Bytes): JSONValue` – parses JSON data from a valid UTF-8 `String` +- `json.try_fromString(data: string): Result` – `json.fromString` の安全なバージョンで、解析に失敗した場合はエラー バリアントを返します -The `JSONValue` class provides a way to pull values out of an arbitrary JSON document. Since JSON values can be booleans, numbers, arrays and more, `JSONValue` comes with a `kind` property to check the type of a value: +`JSONValue` クラスは、任意の JSON ドキュメントから値を引き出す方法を提供します。 JSON の値には、ブーリアン、数値、配列などがあるため、`JSONValue`には、値の種類をチェックするための`kind`プロパティが付属しています。 ```typescript let value = json.fromBytes(...) @@ -650,11 +684,11 @@ if (value.kind == JSONValueKind.BOOL) { } ``` -In addition, there is a method to check if the value is `null`: +さらに、値が`null`かどうかをチェックするメソッドもあります: - `value.isNull(): boolean` -When the type of a value is certain, it can be converted to a [built-in type](#built-in-types) using one of the following methods: +値の型が確定している場合は,以下のいずれかの方法で[組み込み型](#built-in-types)に変換することができます。 - `value.toBool(): boolean` - `value.toI64(): i64` @@ -667,8 +701,8 @@ When the type of a value is certain, it can be converted to a [built-in type](#b | Source(s) | Destination | Conversion function | | -------------------- | -------------------- | ---------------------------- | -| Address | Bytes | none | -| Address | String | s.toHexString() | +| 住所 | Bytes | none | +| 住所 | String | s.toHexString() | | BigDecimal | String | s.toString() | | BigInt | BigDecimal | s.toBigDecimal() | | BigInt | String (hexadecimal) | s.toHexString() or s.toHex() | @@ -685,7 +719,7 @@ When the type of a value is certain, it can be converted to a [built-in type](#b | Bytes | JSON | json.fromBytes(s) | | int8 | i32 | none | | int32 | i32 | none | -| int32 | BigInt | BigInt.fromI32(s) | +| int32 | BigInt | Bigint.fromI32(s) | | uint24 | i32 | none | | int64 - int256 | BigInt | none | | uint32 - uint256 | BigInt | none | @@ -697,15 +731,16 @@ When the type of a value is certain, it can be converted to a [built-in type](#b | JSON | string | s.toString() | | JSON | Array | s.toArray() | | JSON | Object | s.toObject() | -| String | Address | Address.fromString(s) | -| String | BigInt | BigInt.fromString(s) | +| String | 住所 | Address.fromString(s) | +| Bytes | 住所 | Address.fromString(s) | +| String | BigInt | BigDecimal.fromString(s) | | String | BigDecimal | BigDecimal.fromString(s) | | String (hexadecimal) | Bytes | ByteArray.fromHexString(s) | | String (UTF-8) | Bytes | ByteArray.fromUTF8(s) | ### データソースのメタデータ -You can inspect the contract address, network and context of the data source that invoked the handler through the `dataSource` namespace: +ハンドラを起動した`データソース`のコントラクトアドレス、ネットワーク、コンテキストは、以下のようにして調べることができます。 - `dataSource.address(): Address` - `dataSource.network(): string` @@ -713,7 +748,7 @@ You can inspect the contract address, network and context of the data source tha ### エンティティと DataSourceContext -The base `Entity` class and the child `DataSourceContext` class have helpers to dynamically set and get fields: +ベースとなる`エンティティ`クラスと子クラスの`DataSourceContext`クラスには、フィールドを動的に設定・取得するためのヘルパーが用意されています。 - `setString(key: string, value: string): void` - `setI32(key: string, value: i32): void` @@ -727,3 +762,10 @@ The base `Entity` class and the child `DataSourceContext` class have helpers to - `getBytes(key: string): Bytes` - `getBoolean(key: string): boolean` - `getBigDecimal(key: string): BigDecimal` + +### AssemblyScript のよくある問題 + +サブグラフの開発でよく遭遇する[AssemblyScript](https://github.com/AssemblyScript/assemblyscript)の問題があるようです。これらの問題は、デバッグの難易度に幅がありますが、意識しておくと役に立つかもしれません。以下は、これらの問題の非網羅的なリストです。 + +- [AssembyScript](https://www.assemblyscript.org/status.html#language-features)では、`Private`クラス変数が強制されるわけではありません。クラス変数がクラスオブジェクトから直接変更されないように保護する方法はありません。 +- スコープは [closure functions](https://www.assemblyscript.org/status.html#on-closures) に継承されません。つまり、closure functions の外部で宣言された変数は使用できません。[Developer Highlights #3](https://www.youtube.com/watch?v=1-8AW-lVfrA&t=3243s) で説明されています。 diff --git a/website/pages/ja/developing/unit-testing-framework.mdx b/website/pages/ja/developing/unit-testing-framework.mdx index ec4eddff8abb..9d13e99950db 100644 --- a/website/pages/ja/developing/unit-testing-framework.mdx +++ b/website/pages/ja/developing/unit-testing-framework.mdx @@ -4,72 +4,529 @@ title: ユニットテストフレームワーク Matchstick は[LimeChain](https://limechain.tech/)が開発したユニットテストフレームワークで、サブグラフの開発者がサンドボックス環境でマッピングロジックをテストし、自信を持ってサブグラフをデプロイすることができます! -## Getting Started +## はじめに -### Install dependencies +### 依存関係のインストール -In order to use the test helper methods and run the tests, you will need to install the following dependencies: +テストヘルパーメソッドを使用し、テストを実行するためには、以下の依存関係をインストールする必要があります: ```sh yarn add --dev matchstick-as ``` -❗ `graph-node` depends on PostgreSQL, so if you don't already have it, you will need to install it. We highly advise using the commands below as adding it in any other way may cause unexpected errors! +❗ `graph-node` は PostgreSQL に依存しているので、もしまだ持っていなければ、インストールする必要があります。他の方法で追加すると予期しないエラーが発生する可能性があるので、以下のコマンドを使用することを強くお勧めします! #### MacOS -Postgres installation command: +Postgres のインストールコマンド: ```sh -brew install postgresql +postgresql をインストールします。 +``` + +最新の libpq.5.lib へのシンボリック リンクを作成します _最初にこのディレクトリを作成する必要がある場合があります_ `/usr/local/opt/postgresql/lib/` + +```sh +ln -sf /usr/local/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib /usr/local/opt/postgresql/lib/libpq.5.dylib ``` #### Linux -Postgres installation command (depends on your distro): +Postgres のインストールコマンド(お使いのディストロに依存します)。 ```sh -sudo apt install postgresql +sudo apt postgresql をインストール ``` -### OS-specific release binaries +### WSL (Linux 用 Windows サブシステム) -The release binary comes in two flavours - for **МacOS** and **Linux**. To add **Matchstick** to your subgraph project just open up a terminal, navigate to the root folder of your project and simply run `graph test` - it downloads the latest **Matchstick** binary and runs the specified test or all tests in a test folder (or all existing tests if no datasource flag is specified). Example usage: `graph test gravity`. +WSL では、Docker アプローチとバイナリアプローチの両方で Matchstick を使用することができます。WSL は少しトリッキーなので、以下のような問題に遭遇した場合のヒントを紹介します。 -### Docker +``` +static BYTES = Symbol("Bytes") SyntaxError: Unexpected token = +``` + +または + +``` +/node_modules/gluegun/build/index.js:13 throw up; +``` + +Node.js の新しいバージョンを使っていることを確認してください graph-cli はもう**v10.19.0** をサポートしておらず、これはまだ WSL 上の新しい Ubuntu イメージのデフォルトバージョンになっています。例えばマッチスティックは**v18.1.0** で WSL 上で動作することが確認されており、**nvm** を経由するか、グローバル Node.js を更新すれば切り替えることができます。nodejs を更新したら、`node_modules`を削除し、`npm install`を再度実行するのを忘れないでください! それから、**libpq** がインストールされていることを確認してください。 + +``` +sudo apt-get install libpq-dev (インストール) +``` + +最後に、`graph test` (グローバルにインストールされた graph-cli を使用します。なぜか WSL では壊れているようです)を使用せず、`yarn test` や `npm run test` (ローカル、プロジェクトレベルの graph-cli を使用し、魅力的に動作します。)を使用するようにしてください。そのためには、もちろん `"test"` スクリプトを `package.json` ファイルに記述する必要がありますが、これは以下のような簡単なものです。 + +```json +{ + "name": "demo-subgraph", + "version": "0.1.0", + "scripts": { + "test": "graph test", + ... + }, + "dependencies": { + "@graphprotocol/graph-cli": "^0.30.0", + "@graphprotocol/graph-ts": "^0.27.0", + "matchstick-as": "^0.5.0" + } +} +``` + +### 使い方 + +**Matchstick** をサブグラフ・プロジェクトで使用するには、ターミナルを開き、プロジェクトのルート・フォルダに移動して、 `graph test [options] ` と実行するだけで、最新の **Matchstick** バイナリがダウンロードされて、テスト・フォルダにある指定したテストまたは全てのテストが実行されます (datasource flag が指定されていなければ既存の全てのテスト). + +### CLI options + +これにより、test フォルダ内のすべてのテストが実行されます。 + +```sh +グラフテスト +``` + +これは、gravity.test.ts という名前のテストと、gravity というフォルダの中にあるすべてのテストを実行します: + +```sh +gravityのテスト +``` -From `graph-cli 0.25.2`, the `graph test` command supports running `matchstick` in a docker container with the `-d` flag. The docker implementation uses [bind mount](https://docs.docker.com/storage/bind-mounts/) so it does not have to rebuild the docker image every time the `graph test -d` command is executed. Alternatively you can follow the instructions from the [matchstick](https://github.com/LimeChain/matchstick#docker-) repository to run docker manually. +これは、その特定のテストファイルのみを実行します: + +```sh +graph test path/to/file.test.ts +``` -❗ If you have previously ran `graph test` you may encounter the following error during docker build: +**オプション:** +```sh +-c, --coverage Run the tests in coverage mode +-d, --docker Run the tests in a docker container (Note: Please execute from the root folder of the subgraph) +-f --force Binary: Redownloads the binary. Docker: Redownloads the Dockerfile and rebuilds the docker image. +-h, --help Show usage information +-l, --logs Logs to the console information about the OS, CPU model and download url (debugging purposes) +-r, --recompile Forces tests to be recompiled +-v, --version Choose the version of the rust binary that you want to be downloaded/used ``` - error from sender: failed to xattr node_modules/binary-install-raw/bin/binary-: permission denied + +### Docker + +`graph-cli 0.25.2` からは、`graph test` コマンドが `-d` フラグの付いた docker コンテナでの `matchstick` の実行をサポートしています。docker の実装では、[bind mount](https://docs.docker.com/storage/bind-mounts/) を使用しているので、`graph test -d` コマンドを実行するたびに docker イメージを再構築する必要はありません。また、[matchstick](https://github.com/LimeChain/matchstick#docker-) リポジトリの説明に従って、手動で Docker を実行することもできます。 + +❗ 以前に `graph test` を実行したことがある場合、docker build 中に以下のようなエラーが発生することがあります。 + +```sh + 送信者からのエラー: xattr node_modules/binary-install-raw/bin/binary- へのアクセスに失敗しました: パーミッションが拒否されました。 ``` -In this case create a `.dockerignore` in the root folder and add `node_modules/binary-install-raw/bin` +この場合、ルートフォルダに `.dockerignore` を作成し、 `node_modules/binary-install-raw/bin` を追加してください。 -### Configuration +### コンフィギュレーション -Matchstick can be configured to use a custom tests and libs folder via `matchstick.yaml` config file: +Matchstick は、`matchstick.yaml` 設定ファイルによって、カスタムテスト、ライブラリ、マニフェストのパスを使用するように設定することができます。 ```yaml -testsFolder: ./folderName +testsFolder: path/to/tests libsFolder: path/to/libs +manifestPath: path/to/subgraph.yaml +``` + +### デモ・サブグラフ + +[Demo Subgraph レポ](https://github.com/LimeChain/demo-subgraph)をクローンすることで、このガイドのサンプルを試したり、遊んだりすることができます。 + +### ビデオチュートリアル + +また、[「Matchstick を使ってサブグラフのユニットテストを書く方法」](https://www.youtube.com/playlist?list=PLTqyKgxaGF3SNakGQwczpSGVjS_xvOv3h)のビデオシリーズもご覧ください。 + +## Tests structure (>=0.5.0) + +_**IMPORTANT: Requires matchstick-as >=0.5.0**_ + +### describe() + +`describe(name: String , () => {})` - Defines a test group. + +**_注:_** + +- _ディスクリートは必須ではありません。describe() ブロックの外側で test() を旧来の方法で使用することができます。_ + +例: + +```typescript +import { describe, test } from "matchstick-as/assembly/index" +import { handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar()", () => { + test("Should create a new Gravatar entity", () => { + ... + }) +}) +``` + +Nested `describe()` example: + +```typescript +import { describe, test } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar } from "../../src/gravity" + +describe("handleUpdatedGravatar()", () => { + describe("When entity exists", () => { + test("updates the entity", () => { + ... + }) + }) + + describe("When entity does not exists", () => { + test("it creates a new entity", () => { + ... + }) + }) +}) +``` + +--- + +### test() + +`test(name: String, () =>, should_fail: bool)` - テスト ケースを定義します。 test() は、describe() ブロック内または独立して使用できます + +例: + +```typescript +import { describe, test } from "matchstick-as/assembly/index" +import { handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar()", () => { + test("Should create a new Entity", () => { + ... + }) +}) +``` + +または + +```typescript +test("handleNewGravatar() should create a new entity", () => { + ... +}) + + +``` + +--- + +### beforeAll() + +ファイル中のどのテストよりも前にコードブロックを実行します。もし `beforeAll` が `describe` ブロックの中で宣言された場合、その `describe` ブロックの先頭で実行されます。 + +例 + +`beforeAll` 内のコードは、ファイル内の _all_ テストの前に一度だけ実行されます。 + +```typescript +import { describe, test, beforeAll } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" +import { Gravatar } from "../../generated/schema" + +beforeAll(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = “First Gravatar” + gravatar.save() + ... +}) + +describe("When the entity does not exist", () => { + test("it should create a new Gravatar with id 0x1", () => { + ... + }) +}) + +describe("When entity already exists", () => { + test("it should update the Gravatar with id 0x0", () => { + ... + }) +}) ``` -### Example Subgraph +`beforeAll` 内のコードは、最初の記述ブロックのすべてのテストの前に一度だけ実行されます。 + +```typescript +import { describe, test, beforeAll } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" +import { Gravatar } from "../../generated/schema" -You can try out and play around with the examples from this guide by cloning the [Example Subgraph repo](https://github.com/graphprotocol/example-subgraph) +describe("handleUpdatedGravatar()", () => { + beforeAll(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = “First Gravatar” + gravatar.save() + ... + }) -### Video tutorials + test("updates Gravatar with id 0x0", () => { + ... + }) -Also you can check out the video series on ["How to use Matchstick to write unit tests for your subgraphs"](https://www.youtube.com/playlist?list=PLTqyKgxaGF3SNakGQwczpSGVjS_xvOv3h) + test("creates new Gravatar with id 0x1", () => { + ... + }) +}) +``` -## Write a Unit Test +--- -Let's see how a simple unit test would look like, using the Gravatar [Example Subgraph](https://github.com/graphprotocol/example-subgraph). +### afterAll() -Assuming we have the following handler function (along with two helper functions to make our life easier): +ファイル内の全てのテストの後にコードブロックを実行します。もし `afterAll` が `describe` ブロックの中で宣言された場合、その `describe` ブロックの最後で実行されます。 + +例: + +`afterAll` 内のコードは、ファイル内の _all_ テストの後に一度だけ実行されます。 + +```typescript +import { describe, test, afterAll } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" +import { store } from "@graphprotocol/graph-ts" + +afterAll(() => { + store.remove("Gravatar", "0x0") + ... +}) + +describe("handleNewGravatar, () => { + test("creates Gravatar with id 0x0", () => { + ... + }) +}) + +describe("handleUpdatedGravatar", () => { + test("updates Gravatar with id 0x0", () => { + ... + }) +}) +``` + +`afterAll`内のコードは、最初の記述ブロックのすべてのテストの後に一度だけ実行されます。 + +```typescript +import { describe, test, afterAll, clearStore } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar", () => { + afterAll(() => { + store.remove("Gravatar", "0x1") + ... + }) + + test("It creates a new entity with Id 0x0", () => { + ... + }) + + test("It creates a new entity with Id 0x1", () => { + ... + }) +}) + +describe("handleUpdatedGravatar", () => { + test("updates Gravatar with id 0x0", () => { + ... + }) +}) +``` + +--- + +### beforeEach() + +各テストの前にコードブロックを実行します。もし `beforeEach` が `describe` ブロックの中で宣言された場合、その `describe` ブロックの中の各テストの前に実行されます。 + +例 `beforeEach` 内のコードは、各テストの前に実行されます。 + +```typescript +import { describe, test, beforeEach, clearStore } from "matchstick-as/assembly/index" +import { handleNewGravatars } from "./utils" + +beforeEach(() => { + clearStore() // <-- clear the store before each test in the file +}) + +describe("handleNewGravatars, () => { + test("A test that requires a clean store", () => { + ... + }) + + test("Second that requires a clean store", () => { + ... + }) +}) + + ... +``` + +`beforeEach`内のコードは、その記述中の各テストの前にのみ実行されます。 + +```typescript +import { describe, test, beforeEach } from 'matchstick-as/assembly/index' +import { handleUpdatedGravatar, handleNewGravatar } from '../../src/gravity' + +describe('handleUpdatedGravatars', () => { + beforeEach(() => { + let gravatar = new Gravatar('0x0') + gravatar.displayName = 'First Gravatar' + gravatar.imageUrl = '' + gravatar.save() + }) + + test('Upates the displayName', () => { + assert.fieldEquals('Gravatar', '0x0', 'displayName', 'First Gravatar') + + // code that should update the displayName to 1st Gravatar + + assert.fieldEquals('Gravatar', '0x0', 'displayName', '1st Gravatar') + store.remove('Gravatar', '0x0') + }) + + test('Updates the imageUrl', () => { + assert.fieldEquals('Gravatar', '0x0', 'imageUrl', '') + + // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 + + assert.fieldEquals('Gravatar', '0x0', 'imageUrl', 'https://www.gravatar.com/avatar/0x0') + store.remove('Gravatar', '0x0') + }) +}) +``` + +--- + +### afterEach() + +各テストの後にコードブロックを実行します。もし `afterEach` が `describe` ブロックの中で宣言されていれば、その `describe` ブロックの中の各テストの後に実行されます。 + +例: + +`afterEach`内のコードは、各テスト終了後に実行されます。 + +```typescript +import { describe, test, beforeEach, afterEach } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" + +beforeEach(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = “First Gravatar” + gravatar.save() +}) + +afterEach(() => { + store.remove("Gravatar", "0x0") +}) + +describe("handleNewGravatar", () => { + ... +}) + +describe("handleUpdatedGravatar", () => { + test("Upates the displayName", () => { + assert.fieldEquals("Gravatar", "0x0", "displayName", "First Gravatar") + + // code that should update the displayName to 1st Gravatar + + assert.fieldEquals("Gravatar", "0x0", "displayName", "1st Gravatar") + }) + + test("Updates the imageUrl", () => { + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "") + + // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 + + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "https://www.gravatar.com/avatar/0x0") + }) +}) +``` + +`afterEach`内のコードは、その記述の各テストの後に実行されます。 + +```typescript +import { describe, test, beforeEach, afterEach } from "matchstick-as/assembly/index" +import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity" + +describe("handleNewGravatar", () => { + ... +}) + +describe("handleUpdatedGravatar", () => { + beforeEach(() => { + let gravatar = new Gravatar("0x0") + gravatar.displayName = "First Gravatar" + gravatar.imageUrl = "" + gravatar.save() + }) + + afterEach(() => { + store.remove("Gravatar", "0x0") + }) + + test("Upates the displayName", () => { + assert.fieldEquals("Gravatar", "0x0", "displayName", "First Gravatar") + + // code that should update the displayName to 1st Gravatar + + assert.fieldEquals("Gravatar", "0x0", "displayName", "1st Gravatar") + }) + + test("Updates the imageUrl", () => { + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "") + + // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 + + assert.fieldEquals("Gravatar", "0x0", "imageUrl", "https://www.gravatar.com/avatar/0x0") + }) +}) +``` + +## アサート + +```typescript +fieldEquals(entityType: string, id: string, fieldName: string, expectedVal: string) + +equals(expected: ethereum.Value, actual: ethereum.Value) + +notInStore(entityType: string, id: string) + +addressEquals(address1: Address, address2: Address) + +bytesEquals(bytes1: Bytes, bytes2: Bytes) + +i32Equals(number1: i32, number2: i32) + +bigIntEquals(bigInt1: BigInt, bigInt2: BigInt) + +booleanEquals(bool1: boolean, bool2: boolean) + +stringEquals(string1: string, string2: string) + +arrayEquals(array1: Array, array2: Array) + +tupleEquals(tuple1: ethereum.Tuple, tuple2: ethereum.Tuple) + +assertTrue(value: boolean) + +assertNull(value: T) + +assertNotNull(value: T) + +entityCount(entityType: string, expectedCount: i32) +``` + +## 単体テストを書く + +[Demo Subgraph](https://github.com/LimeChain/demo-subgraph/blob/main/src/gravity.ts) にある Gravatar の例を使って、簡単なユニットテストがどのように見えるか見てみましょう。 + +次のようなハンドラ関数があるとします(さらに、生活を便利にするための 2 つのヘルパー関数もあります)。 ```typescript export function handleNewGravatar(event: NewGravatar): void { @@ -120,7 +577,7 @@ export function createNewGravatarEvent( } ``` -We first have to create a test file in our project. This is an example of how that might look like: +まず、プロジェクト内にテストファイルを作成する必要があります。これは、そのような例です: ```typescript import { clearStore, test, assert } from 'matchstick-as/assembly/index' @@ -154,38 +611,38 @@ test('Next test', () => { }) ``` -That's a lot to unpack! First off, an important thing to notice is that we're importing things from `matchstick-as`, our AssemblyScript helper library (distributed as an npm module). You can find the repository [here](https://github.com/LimeChain/matchstick-as). `matchstick-as` provides us with useful testing methods and also defines the `test()` function which we will use to build our test blocks. The rest of it is pretty straightforward - here's what happens: +このように様々な形で紐解いてみました。まず最初に、重要なことは、AssemblyScript のヘルパーライブラリである `matchstick-as` からインポートしていることです (npm モジュールとして配布されています)。リポジトリは[こちら](https://github.com/LimeChain/matchstick-as)にあります。`matchstick-as` は便利なテストメソッドを提供し、テストブロックを構築するために使用する `test()` 関数を定義しています。残りの部分はとても簡単で、次のようなことが起こります。 -- 初期状態を設定し、カスタム Gravatar エンティティを 1 つ追加しています。 -- `createNewGravatarEvent()`関数を使って、2 つの`NewGravatar`イベントオブジェクトとそのデータを定義しています。 -- これらのイベントのハンドラ・メソッド`handleNewGravatars()`を呼び出し、カスタム・イベントのリストを渡しています。 -- ストアの状態をアサートしています。これはどのような仕組みなのでしょうか?- Entity タイプと id のユニークな組み合わせを渡しています。そして、その Entity の特定のフィールドをチェックして、期待する値を持っていることをアサートします。これは、ストアに追加した最初の Gravatar Entity と、ハンドラ関数が呼び出されたときに追加される 2 つの Gravatar Entity の両方に対して行っています。 +- 初期状態を設定し、カスタム Gravatar エンティティを 1 つ追加しています; +- `createNewGravatarEvent()` 関数を使用して、2 つの `NewGravatar` イベント オブジェクトとそれらのデータを定義します。 +- これらのイベントのハンドラメソッド - `handleNewGravatars()` を呼び出し、カスタムイベントのリストを渡しています; +- store の状態をアサートする場合、これはどのように行われるのでしょうか。- Entity の種類と id の一意の組み合わせを渡します。そして、その Entity の特定のフィールドをチェックし、期待通りの値を持っていることを表明します。これは store に追加した最初の Gravatar Entity と、ハンドラ関数が呼び出されたときに追加される 2 つの Gravatar Entity の両方に対して行っているのです。 - 最後に、`clearStore()`を使ってストアを掃除し、次のテストが新鮮で空のストア・オブジェクトで始められるようにしています。テストブロックは必要に応じていくつでも定義できます。 -There we go - we've created our first test! 👏 +これで最初のテストが完成しました! 👏 -Now in order to run our tests you simply need to run the following in your subgraph root folder: +テストを実行するには、サブグラフのルートフォルダで以下を実行する必要があります: -`graph test Gravity` +`gravityのテスト` -And if all goes well you should be greeted with the following: +すべてがうまくいくと、以下のメッセージが表示されます: -![Matchstick saying “All tests passed!”](/img/matchstick-tests-passed.png) +![「すべてのテストに合格しました!」というマッチ棒](/img/matchstick-tests-passed.png) -## Common test scenarios +## 一般的なテストシナリオ -### Hydrating the store with a certain state +### 特定の状態で店舗を潤す -Users are able to hydrate the store with a known set of entities. Here's an example to initialise the store with a Gravatar entity: +ユーザーは、既知のエンティティのセットでストアをハイドレートすることができます。ここでは、Gravatar のエンティティでストアを初期化する例を示します: ```typescript let gravatar = new Gravatar('entryId') gravatar.save() ``` -### Calling a mapping function with an event +### イベントを使ったマッピング関数の呼び出し -A user can create a custom event and pass it to a mapping function that is bound to the store: +ユーザーはカスタムイベントを作成し、それをストアにバインドされたマッピング関数に渡すことができます: ```typescript import { store } from 'matchstick-as/assembly/store' @@ -197,9 +654,9 @@ let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01 handleNewGravatar(newGravatarEvent) ``` -### Calling all of the mappings with event fixtures +### イベントフィクスチャですべてのマッピングを呼び出す -Users can call the mappings with test fixtures. +ユーザーはテストフィクスチャでマッピングを呼び出すことができます。 ```typescript import { NewGravatar } from '../../generated/Gravity/Gravity' @@ -221,9 +678,9 @@ export function handleNewGravatars(events: NewGravatar[]): void { } ``` -### Mocking contract calls +### コントラクトコールのモック -Users can mock contract calls: +ユーザーはコントラクトコールをモックすることができます: ```typescript import { addMetadata, assert, createMockedFunction, clearStore, test } from 'matchstick-as/assembly/index' @@ -243,9 +700,9 @@ let result = gravity.gravatarToOwner(bigIntParam) assert.equals(ethereum.Value.fromAddress(expectedResult), ethereum.Value.fromAddress(result)) ``` -As demonstrated, in order to mock a contract call and hardcore a return value, the user must provide a contract address, function name, function signature, an array of arguments, and of course - the return value. +このように、コントラクトの呼び出しと戻り値をハードコア化するために、ユーザーはコントラクトのアドレス、関数名、関数シグネチャ、引数の配列、そしてもちろん戻り値を提供する必要があります。 -Users can also mock function reverts: +また、関数の戻り値をモックすることもできます: ```typescript let contractAddress = Address.fromString('0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7') @@ -256,9 +713,9 @@ createMockedFunction(contractAddress, 'getGravatar', 'getGravatar(address):(stri ### Mocking IPFS files (from matchstick 0.4.1) -Users can mock IPFS files by using `mockIpfsFile(hash, filePath)` function. The function accepts two arguments, the first one is the IPFS file hash/path and the second one is the path to a local file. +`mockIpfsFile(hash, filePath)`関数を使用することにより、IPFS ファイルのモックを作成することができます。最初の引数は IPFS ファイルのハッシュ/パス、2 番目の引数はローカルファイルへのパスです。 -NOTE: When testing `ipfs.map/ipfs.mapJSON`, the callback function must be exported from the test file in order for matchstck to detect it, like the `processGravatar()` function in the test example bellow: +注意: `ipfs.map/ipfs.mapJSON` をテストするとき、下記のテスト例の `processGravatar()` 関数のように、コールバック関数は matchstck がそれを検出するためにテストファイルからエクスポートされなければなりません。 `.test.ts` file: @@ -297,7 +754,7 @@ test('ipfs.map', () => { }) ``` -`utils.ts` file: +`.utils.ts` file: ```typescript import { Address, ethereum, JSONValue, Value, ipfs, json, Bytes } from "@graphprotocol/graph-ts" @@ -345,9 +802,9 @@ export function gravatarFromIpfs(): void { } ``` -### Asserting the state of the store +### ストアの状態をアサートする -Users are able to assert the final (or midway) state of the store through asserting entities. In order to do this, the user has to supply an Entity type, the specific ID of an Entity, a name of a field on that Entity, and the expected value of the field. Here's a quick example: +ユーザーは、エンティティをアサートすることで、ストアの最終的な状態(または途中の状態)をアサートすることができます。これを実行するためには、ユーザーはエンティティタイプ、エンティティの特定の ID、フィールド名、フィールドの期待値を指定する必要があります。以下に例を示します: ```typescript import { assert } from 'matchstick-as/assembly/index' @@ -359,11 +816,11 @@ gravatar.save() assert.fieldEquals('Gravatar', 'gravatarId0', 'id', 'gravatarId0') ``` -Running the assert.fieldEquals() function will check for equality of the given field against the given expected value. The test will fail and an error message will be outputted if the values are **NOT** equal. Otherwise the test will pass successfully. +Assert.fieldEquals()関数を実行すると、指定されたフィールドが指定された期待値と等しいかどうかをチェックします。値が**等しくない** 場合は、テストは失敗し、エラーメッセージが出力されます。それ以外の場合は、テストは正常に通過します。 -### Interacting with Event metadata +### イベントメタデータとのやりとり -Users can use default transaction metadata, which could be returned as an ethereum.Event by using the `newMockEvent()` function. The following example shows how you can read/write to those fields on the Event object: +ユーザーは、`newMockEvent()`関数を使用して ethereum.Event として返されるデフォルトのトランザクションのメタデータを使用することができます。以下の例では、イベントオブジェクトのこれらのフィールドを読み書きする方法を示しています: ```typescript // Read @@ -374,23 +831,23 @@ let UPDATED_ADDRESS = '0xB16081F360e3847006dB660bae1c6d1b2e17eC2A' newGravatarEvent.address = Address.fromString(UPDATED_ADDRESS) ``` -### Asserting variable equality +### 変数の等値性の主張 ```typescript assert.equals(ethereum.Value.fromString("hello"); ethereum.Value.fromString("hello")); ``` -### Asserting that an Entity is **not** in the store +### エンティティがストアに**ない**ことをアサートする -Users can assert that an entity does not exist in the store. The function takes an entity type and an id. If the entity is in fact in the store, the test will fail with a relevant error message. Here's a quick example of how to use this functionality: +ユーザーは、あるエンティティがストアに存在しないことをアサートできます。この関数は、エンティティタイプと id を受け取ります。エンティティが実際にストア内にある場合、テストは関連するエラーメッセージを表示して失敗します。この機能を使った簡単な例をご紹介します: ```typescript assert.notInStore('Gravatar', '23') ``` -### Printing the whole store (for debug purposes) +### ストア全体を印刷する(デバッグ用) -You can print the whole store to the console using this helper function: +このヘルパー関数を使って、ストア全体をコンソールに出力することができます: ```typescript import { logStore } from 'matchstick-as/assembly/store' @@ -398,9 +855,9 @@ import { logStore } from 'matchstick-as/assembly/store' logStore() ``` -### Expected failure +### 予想される不具合 -Users can have expected test failures, using the shouldFail flag on the test() functions: +Test() 関数の shouldFail フラグを使用して、ユーザーがテストの失敗を予想することができます: ```typescript test( @@ -412,11 +869,11 @@ test( ) ``` -If the test is marked with shouldFail = true but DOES NOT fail, that will show up as an error in the logs and the test block will fail. Also, if it's marked with shouldFail = false (the default state), the test executor will crash. +ShouldFail = true とマークされているにもかかわらずテストが失敗した場合は、ログにエラーとして表示され、テストブロックは失敗します。また、shouldFail = false (デフォルトの状態) と設定されている場合は、テスト実行者がクラッシュします。 -### Logging +### ロギング -Having custom logs in the unit tests is exactly the same as logging in the mappings. The difference is that the log object needs to be imported from matchstick-as rather than graph-ts. Here's a simple example with all non-critical log types: +ユニットテストにカスタムログを持たせることは、マッピングにログを持たせることと全く同じです。違いは、ログオブジェクトを graph-ts ではなく matchstick-as からインポートする必要があることです。以下は、すべての非重要なログタイプを使った簡単な例です: ```typescript import { test } from "matchstick-as/assembly/index"; @@ -439,7 +896,7 @@ test("Warning", () => { }); ``` -Users can also simulate a critical failure, like so: +ユーザーは、このように致命的な失敗をシミュレートすることもできます: ```typescript test('Blow everything up', () => { @@ -447,11 +904,11 @@ test('Blow everything up', () => { }) ``` -Logging critical errors will stop the execution of the tests and blow everything up. After all - we want to make sure you're code doesn't have critical logs in deployment, and you should notice right away if that were to happen. +クリティカルエラーのログを取るとテストの実行が止まり、すべてが飛んでしまいます。コードに重要なログがデプロイされていないことを確認し、もし発生した場合にはすぐに気付く必要があります。 -### Testing derived fields +### 派生フィールドのテスト -Testing derived fields is a feature which (as the example below shows) allows the user to set a field in a certain entity and have another entity be updated automatically if it derives one of its fields from the first entity. Important thing to note is that the first entity needs to be reloaded as the automatic update happens in the store in rust of which the AS code is agnostic. +派生フィールドのテストは、(以下の例で示すように)ユーザーがあるエンティティにフィールドを設定し、それが最初のエンティティからフィールドの 1 つを派生している場合、別のエンティティが自動的に更新されるようにする機能です。重要なのは、自動更新は AS コードが不可知論である錆のストア内で行われるため、最初のエンティティは再ロードされる必要があることです。 ```typescript test('Derived fields example test', () => { @@ -474,9 +931,13 @@ test('Derived fields example test', () => { }) ``` -### Testing dynamic data sources +### 動的データソースのテスト + +動的なデータソースのテストは、dataSource 名前空間の `context()`, `address()`, `network()` 関数の戻り値をモックすることにより行うことができます。これらの関数は現在、以下のものを返しています。`context()` - 空の実体 (DataSourceContext) を返す、 `address()` - `0x000000000000000000000000` を返す、 `network()` - `mainnet` を返す、です。`create(...)`と`createWithContext(...)`関数は何もしないようにモックされているので、テストの中で呼ばれる必要は全くないでしょう。戻り値の変更は `matchstick-as` (version 0.3.0+) の `dataSourceMock` 名前空間の関数で行うことができます。 + +以下はその例です: -Testing dynamic data sources can be be done by mocking the return value of the context(), address() and network() functions of the dataSource namespace. These functions currently return the following: context - returns an empty entity (DataSourceContext), address - returns "0x0000000000000000000000000000000000000000", network - returns "mainnet". The create(...) and createWithContext(...) functions are mocked to do nothing so they don't need to be called in the tests at all. Changes to the return values can be done through the functions of the dataSourceMock namespace in matchstick-as (version 0.3.0+). Example below: First we have the following event handler (which has been intentionally repurposed to showcase datasource mocking): +まず、次のようなイベントハンドラを用意します (これはデータソースのモッキングを紹介するために意図的に再利用されています): ```typescript export function handleApproveTokenDestinations(event: ApproveTokenDestinations): void { @@ -492,7 +953,7 @@ export function handleApproveTokenDestinations(event: ApproveTokenDestinations): } ``` -And then we have the test using one of the methods in the dataSourceMock namespace to set a new return value for all of the dataSource functions: +そして、dataSourceMock namespace のメソッドの 1 つを使用して、すべての dataSource 関数に新しい戻り値を設定するテストがあります: ```typescript import { assert, test, newMockEvent, dataSourceMock } from 'matchstick-as/assembly/index' @@ -525,50 +986,50 @@ test('Data source simple mocking example', () => { }) ``` -Notice that dataSourceMock.resetValues() is called at the end. That's because the values are remembered when they are changed and need to be reset if you want to go back to the default values. +最後に dataSourceMock.resetValues()が呼び出されていることに注目してください。これは、値が変更されると記憶されるため、デフォルトの値に戻したい場合はリセットする必要があるからです。 -## Test Coverage +## テストカバレッジ -Using **Matchstick**, subgraph developers are able to run a script that will calculate the test coverage of the written unit tests. The tool only works on **Linux** and **MacOS**, but when we add support for Docker (see progress on that [here](https://github.com/LimeChain/matchstick/issues/222)) users should be able to use it on any machine and almost any OS. +**Matchstick** を使って、サブグラフの開発者は書かれたユニットテストのテストカバレッジを計算するスクリプトを実行することができるようになりました。このツールは**Linux** と **MacOS** 上でのみ動作しますが、Docker のサポートを追加すれば(その進捗は[ こちら](https://github.com/LimeChain/matchstick/issues/222))どんなマシンやほとんどの OS でも使用できるようになるはずです。 -The test coverage tool is really simple - it takes the compiled test `wasm` binaries and converts them to `wat` files, which can then be easily inspected to see whether or not the handlers defined in `subgraph.yaml` have actually been called. Since code coverage (and testing as whole) is in very early stages in AssemblyScript and WebAssembly, **Matchstick** cannot check for branch coverage. Instead we rely on the assertion that if a given handler has been called, the event/function for it have been properly mocked. +テストカバレッジツールはとてもシンプルで、コンパイルされたテストの `wasm` バイナリを取って `wat` ファイルに変換し、 `subgraph.yaml` で定義されたハンドラが実際に呼ばれたかどうかを簡単に検査することができます。AssemblyScript と WebAssembly では、コードカバレッジ (およびテスト全体) は非常に初期の段階なので、**Matchstick** はブランチカバレッジをチェックすることはできません。その代わりに、もし与えられたハンドラが呼ばれたなら、そのハンドラのためのイベント/関数が適切にモック化されているという主張に依存します。 ### 前提条件 -To run the test coverage functionality provided in **Matchstick**, there are a few things you need to prepare beforehand: +**Matchstick** で提供されているテストカバレッジ機能を実行するには、事前に準備しておくことがいくつかあります: -#### Export your handlers +#### ハンドラのエクスポート -In order for **Matchstick** to check which handlers are being run, those handlers need to be exported from the **test file**. So for instance in our example, in our gravity.test.ts file we have the following handler being imported: +**Matchstick** がどのハンドラが実行されているかをチェックするために、それらのハンドラは **test file** からエクスポートされる必要があります。例えばこの例では、gravity.test.ts ファイルに次のハンドラがインポートされています: -```ts +```typescript import { handleNewGravatar } from '../../src/gravity' ``` -In order for that function to be visible (for it to be included in the `wat` file **by name**) we need to also export it, like this: +その関数が見えるようにする(`wat`ファイル**名前**に含める)には、次のようにエクスポートも必要です。 -```ts +```typescript export { handleNewGravatar } ``` -### 使用方法 +### 使い方 -Once that's all set up, to run the test coverage tool, simply run: +設定が完了したら、テストカバレッジツールを実行するために実行します: ```sh graph test -- -c ``` -You could also add a custom `coverage` command to your `package.json` file, like so: +次のように、カスタムの `coverage` コマンドを `package.json` ファイルに追加することもできます。 -```ts +```typescript "scripts": { /.../ "coverage": "graph test -- -c" }, ``` -Hopefully that should execute the coverage tool without any issues. You should see something like this in the terminal: +こうすればカバレッジツールを問題なく実行できるはずです。ターミナルには、以下のようなメッセージが表示されます: ```sh $ graph test -c @@ -607,32 +1068,32 @@ Test coverage: 0.0% (0/6 handlers). Global test coverage: 22.2% (2/9 handlers). ``` -### Test run time duration in the log output +### ログ出力でのテスト実行時間の表示 -The log output includes the test run duration. Here's an example: +ログ出力にテスト実行時間が含まれるようになりました。以下はその例です: `[Thu, 31 Mar 2022 13:54:54 +0300] Program executed in: 42.270ms.` -## Common compiler errors +## 一般的なコンパイラーエラー -> Critical: Could not create WasmInstance from valid module with context: unknown import: wasi_snapshot_preview1::fd_write has not been defined +> Critical: 有効なモジュールから WasmInstance を作成できない。コンテキストが不明 インポート: wasi_snapshot_preview1::fd_write が定義されていない -This means you have used `console.log` in your code, which is not supported by AssemblyScript. Please consider using the [Logging API](/developing/assemblyscript-api/#logging-api) +これは、コード内で`console.log`を使用していることを意味し、AssemblyScript ではサポートされていません。[Logging API](/developing/assemblyscript-api/#logging-api) の利用をご検討ください。 -> ERROR TS2554: Expected ? arguments, but got ?. +> ERROR TS2554: 期待された引数は? > > return new ethereum.Block(defaultAddressBytes, defaultAddressBytes, defaultAddressBytes, defaultAddress, defaultAddressBytes, defaultAddressBytes, defaultAddressBytes, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt); > > in ~lib/matchstick-as/assembly/defaults.ts(18,12) > -> ERROR TS2554: Expected ? arguments, but got ?. +> ERROR TS2554: 期待された引数は? > > return new ethereum.Transaction(defaultAddressBytes, defaultBigInt, defaultAddress, defaultAddress, defaultBigInt, defaultBigInt, defaultBigInt, defaultAddressBytes, defaultBigInt); > > in ~lib/matchstick-as/assembly/defaults.ts(24,12) -The mismatch in arguments is caused by mismatch in `graph-ts` and `matchstick-as`. The best way to fix issues like this one is to update everything to the latest released version. +引数の不一致は、`graph-ts`と`matchstick-as`の不一致によって起こります。このような問題を解決する最善の方法は、すべてを最新のリリース版にアップデートすることです。 -## Feedback +## フィードバック -If you have any questions, feedback, feature requests or just want to reach out, the best place would be The Graph Discord where we have a dedicated channel for Matchstick, called 🔥| unit-testing. +質問、フィードバックなどがありましたら、The Graph Discord に Matchstick 専用のチャンネル 🔥| unit-testing がありますので、そちらにお問い合わせください。 diff --git a/website/pages/ja/docsearch.json b/website/pages/ja/docsearch.json index 8cfff967936d..16e3add9725a 100644 --- a/website/pages/ja/docsearch.json +++ b/website/pages/ja/docsearch.json @@ -1,42 +1,42 @@ { "button": { - "buttonText": "Search", - "buttonAriaLabel": "Search" + "buttonText": "検索", + "buttonAriaLabel": "検索" }, "modal": { "searchBox": { - "resetButtonTitle": "Clear the query", - "resetButtonAriaLabel": "Clear the query", - "cancelButtonText": "Cancel", - "cancelButtonAriaLabel": "Cancel" + "resetButtonTitle": "クエリのクリア", + "resetButtonAriaLabel": "クエリのクリア", + "cancelButtonText": "キャンセル", + "cancelButtonAriaLabel": "キャンセル" }, "startScreen": { - "recentSearchesTitle": "Recent", - "noRecentSearchesText": "No recent searches", - "saveRecentSearchButtonTitle": "Save this search", - "removeRecentSearchButtonTitle": "Remove this search from history", - "favoriteSearchesTitle": "Favorite", - "removeFavoriteSearchButtonTitle": "Remove this search from favorites" + "recentSearchesTitle": "最近", + "noRecentSearchesText": "最近の検索はありません", + "saveRecentSearchButtonTitle": "この検索を保存", + "removeRecentSearchButtonTitle": "この検索結果を履歴から削除", + "favoriteSearchesTitle": "お気に入り", + "removeFavoriteSearchButtonTitle": "この検索結果をお気に入りから削除" }, "errorScreen": { - "titleText": "Unable to fetch results", - "helpText": "You might want to check your network connection." + "titleText": "結果を取得することができません", + "helpText": "ネットワーク接続をご確認ください。" }, "footer": { - "selectText": "to select", - "selectKeyAriaLabel": "Enter key", - "navigateText": "to navigate", - "navigateUpKeyAriaLabel": "Arrow up", - "navigateDownKeyAriaLabel": "Arrow down", - "closeText": "to close", - "closeKeyAriaLabel": "Escape key", - "searchByText": "Search by" + "selectText": "選択", + "selectKeyAriaLabel": "エンターキー", + "navigateText": "ナビゲート", + "navigateUpKeyAriaLabel": "上矢印", + "navigateDownKeyAriaLabel": "下矢印", + "closeText": "閉じる", + "closeKeyAriaLabel": "エスケープキー", + "searchByText": "検索:" }, "noResultsScreen": { - "noResultsText": "No results for", - "suggestedQueryText": "Try searching for", - "reportMissingResultsText": "Believe this query should return results?", - "reportMissingResultsLinkText": "Let us know." + "noResultsText": "該当する結果なし:", + "suggestedQueryText": "検索してください:", + "reportMissingResultsText": "このクエリが結果を返すと信じていますか?", + "reportMissingResultsLinkText": "我々に教えてください" } } } diff --git a/website/pages/ja/firehose.mdx b/website/pages/ja/firehose.mdx new file mode 100644 index 000000000000..9075c7d46b30 --- /dev/null +++ b/website/pages/ja/firehose.mdx @@ -0,0 +1,11 @@ +--- +title: Firehose +--- + +Firehose は、ファイルベースかつストリーミングファーストのアプローチでブロックチェーンデータを処理します。 + +Firehose は、Ethereum(および多くの EVM チェーン)、NEAR、Solana、Cosmos、Arweave 向けに構築されており、現在も続々と開発中です。 + +グラフノードの統合は複数のチェーンに対して構築されているため、サブグラフは Firehose からデータをストリームし、パフォーマンスとスケーラビリティの高いインデックス作成を行うことができます。Firehose は、The Graph のコア開発者によって構築された新しい変換技術である[サブストリーム](/substreams)も強化します。 + +詳しくは、[firehose のドキュメント](https://firehose.streamingfast.io/)をご覧ください。 diff --git a/website/pages/ja/global.json b/website/pages/ja/global.json index a2809b13c1bf..e94e2c2443c8 100644 --- a/website/pages/ja/global.json +++ b/website/pages/ja/global.json @@ -1,26 +1,26 @@ { "navigation": { - "theGraphNetwork": "The Graph Network", - "subgraphs": "Subgraphs", - "developing": "Developing", - "deploying": "Deploying", - "publishing": "Publishing", - "managing": "Managing", - "querying": "Querying", - "cookbook": "Cookbook", - "indexing": "Indexing", - "releaseNotes": "Release Notes & Upgrade Guides" + "theGraphNetwork": "グラフネットワーク", + "subgraphs": "サブグラフ", + "developing": "現像", + "deploying": "展開する", + "publishing": "パブリッシング", + "managing": "管理します", + "querying": "クエリ", + "cookbook": "クックブック", + "indexing": "インデキシング", + "releaseNotes": "リリースノート&アップグレードガイド" }, - "collapse": "Collapse", - "expand": "Expand", - "previous": "Previous", - "next": "Next", - "editPage": "Edit page", - "pageSections": "Page Sections", - "linkToThisSection": "Link to this section", - "technicalLevelRequired": "Technical Level Required", - "notFoundTitle": "Oops! This page was lost in space...", + "collapse": "崩壊", + "expand": "拡大", + "previous": "前", + "next": "次", + "editPage": "ページを編集", + "pageSections": "ページ セクション", + "linkToThisSection": "このセクションへのリンク", + "technicalLevelRequired": "必要な技術レベル", + "notFoundTitle": "おっとっと!このページはスペースで失われました...", "notFoundSubtitle": "以下のリンクをクリックして、正しいアドレスを使用しているかどうかを確認し、また、ウェブサイトをご覧ください。", - "goHome": "Go Home", - "video": "Video" + "goHome": "家に帰れ", + "video": "ビデオ" } diff --git a/website/pages/ja/glossary.mdx b/website/pages/ja/glossary.mdx new file mode 100644 index 000000000000..368abf6d10e5 --- /dev/null +++ b/website/pages/ja/glossary.mdx @@ -0,0 +1,79 @@ +--- +title: 用語集 +--- + +- **The Graph**。データのインデックス(索引付け)とクエリ(問い合わせ)のための分散型プロトコル。 + +- **クエリ**:データに対する要求。The Graph の場合、クエリとは、インデクサーが回答するサブグラフのデータに対するリクエストのことです。 + +- **GraphQL**:API 用のクエリ言語であり、既存のデータでクエリを実行するためのランタイムです。グラフは、サブグラフのクエリに GraphQL を使用しています。 + +- **Subgraph**:[GraphQL](https://graphql.org/)を使ってクエリできる、ブロックチェーンデータ上に構築されたカスタム API です。開発者は、The Graph の分散型ネットワークにサブグラフを構築、デプロイ、公開することができます。その後、インデクサーはサブグラフのインデックス作成を開始し、サブグラフコンシューマーがクエリできるようにすることができます。 + +- **ホスティングサービス**:The Graph の分散型ネットワークが、サービスコスト、サービス品質、開発者体験を成熟させていく過程で、サブグラフの構築とクエリのための一時的な足場となるサービスです。 + +- **インデクサー**:ブロックチェーンからデータをインデックスし、GraphQL クエリを提供するためにインデックスノードを実行するネットワーク参加者です。 + +- **インデクサー報酬**:GRT では、インデクサー報酬は、クエリ料金のリベートとインデックスの報酬の 2 つの要素で成り立っています。 + + 1. **クエリ料**:ネットワーク上でクエリを提供するサブグラフ消費者から支払われます。 + + 2. **インデックス作成報酬**:インデクサーが、サブグラフのインデックス作成に対して受け取る報酬です。インデックス報酬は、毎年 3%の GRT を新規に発行することで発生します。 + +- **インデクサーのセルフステーク**:インデクサーが分散型ネットワークに参加するためにステークする GRT の金額です。最低額は 100,000GRT で、上限はありません。 + +- **デリゲーター**:GRT を所有し、その GRT をインデクサーに委任するネットワーク参加者です。これにより、インデクサーはネットワーク上のサブグラフへの出資比率を高めることができます。デリゲーターは、インデクサーがサブグラフを処理する際に受け取るインデクサー報酬の一部を受け取ります。 + +- **デリゲーション・タックス**。デリゲーターがインデクサーに GRT を委任する際に支払う 0.5%の手数料です。手数料の支払いに使われた GRT はバーンされます。 + +- **キュレーター**:質の高いサブグラフを特定し、キュレーションシェアと引き換えにそれらを「キュレーション」する(つまり、その上で GRT をシグナルする)ネットワーク参加者。インデクサーがサブグラフのクエリ料を請求すると、10%がそのサブグラフの Curator に分配されます。インデクサーは、サブグラフ上のシグナルに比例してインデックス作成報酬を得ます。GRT のシグナル量と、サブグラフのインデックスを作成するインデクサーの数には相関関係があります。 + +- **キュレーション税**。キュレーターがサブグラフに GRT のシグナルを送る際に支払う 1%の手数料。手数料を支払うために使用される GRT はバーンされます。 + +- **サブグラフ・コンシューマー**。消費者。サブグラフにクエリをするアプリケーションやユーザーが主となります。 + +- **サブグラフ・デベロッパー**:The Graph の分散型ネットワークにサブグラフを構築し、デプロイする開発者のことです。 + +- **Subgraph Manifest**:サブグラフの GraphQL スキーマ、データ ソース、およびその他のメタデータを記述する JSON ファイルです。[こちら](https://ipfs.io/ipfs/QmVQdzeGdPUiLiACeqXRpKAYpyj8Z1yfWLMUq7A7WundUf)がその例です。 + +- **リベート・プール**:サブグラフの消費者が支払ったクエリ料を、クエリ料のリベートとしてインデクサが請求できるまで保持する経済的な安全対策。残った GRT はバーンされます。 + +- **エポック**:ネットワークにおける時間の単位。1 エポックは現在 6,646 ブロック、約 1 日である。 + +- **アロケーション**:インデクサは、GRT のステーク(デリゲータのステークを含む)を、The Graph の分散型ネットワークで公開されているサブグラフに割り当てることができます。アロケーションは、4 つの段階のうちの 1 つです。 + + 1. **アクティブ**:アロケーションは、オンチェーンで作成されたときにアクティブとみなされます。これはアロケーションを開くと呼ばれ、インデクサーが特定のサブグラフのために積極的にインデックスを作成し、クエリを提供していることをネットワークに示しています。アクティブなアロケーションは、サブグラフ上のシグナルと割り当てられた GRT の量に比例してインデックス作成報酬を発生させます。 + + 2. **クローズド**:インデクサーは、最近の有効なインデックス証明(POI)を提出することで、与えられたサブグラフに発生したインデクサー報酬を請求することができます。これは、割り当てを終了することとして知られています。アロケーションを閉じるには、最低 1 エポック以上開いていなければなりません。最大割当期間は 28 エポックです。インデクサが 28 エポックを超えてアロケーションを開いたままにした場合、それはステイルアロケーションとして知られています。割り当てが**クローズド**状態にあるとき、フィッシャーはまだ、偽のデータを提供したインデクサーに異議を唱えるために紛争を開くことができます。 + + 3. **ファイナライズド**:紛争期間が終了し、インデクサーが請求できるクエリ料の払い戻しが可能となる段階。 + + 4. **請求済み**:割り当ての最終段階で、対象となるすべての報酬が配布され、そのクエリ料報酬が請求されている状態です。 + +- **Subgraph Studio**:サブグラフの構築、デプロイ、公開のための強力な DAP です。 + +- **漁師**: ネットワーク参加者は、インデクサーのクエリ応答と POI に異議を唱えることがあります。これを漁師といいます。 Fisherman に有利に解決された紛争は、Fisherman への裁定とともに、Indexer に金銭的ペナルティをもたらし、ネットワーク内の Indexer によって実行されるインデックス作成およびクエリ作業の整合性を奨励します。ペナルティ (スラッシュ) は現在、インデクサーのセルフ ステークの 2.5% に設定されており、削減された GRT の 50% がフィッシャーマンに、残りの 50% がバーンされます。 + +- **アービトレーター**:アービトレーターは、ガバナンスを介して設定されたネットワーク参加者です。アービトレーターの役割は、インデックス作成とクエリの論争の結果を決定することです。彼らの目標は、The Graph Network の実用性と信頼性を最大化することにあります。 + +- **スラッシング**: インデクサーは、不正確なインデックス証明(POI)を提供したり、不正確なデータを提供したりすると、賭けられた GRT をスラッシングされることがあります。スラッシングの割合はプロトコルパラメータで、現在はインデクサーのセルフステークの 2.5%に設定されています。削減された GRT の 50%は、不正確なデータまたは不正確な POI に異議を唱えたフィッシャーマンに支払われる。残りの 50%はバーンされます。 + +- **インデックス作成報酬**:インデクサーがサブグラフのインデックス作成に対して受け取る報酬です。インデックス作成報酬は GRT で分配されます。 + +- **デリゲーション報酬**:GRT をインデクサーにデリゲートすることでデリゲーターが受け取る報酬。デリゲーション報酬は GRT で分配されます。 + +- **GRT**: Graph のワークユーティリティトークン。GRT は、ネットワーク参加者にネットワークへの貢献に対する経済的インセンティブを提供します。 + +- **POI または Proof of Indexing**:インデクサーの割り当てが終了し、与えられたサブグラフで発生したインデクサー報酬を請求したい場合、有効かつ最新のインデクシング証明(POI)を提出しなければなりません。フィッシャーマンは、インデクサーの提供した POI に異議を唱えることができます。フィッシャーマン側に有利に解決された紛争は、そのインデクサーの削減をもたらします。 + +- **グラフノード**:Graph Node は、サブグラフにインデックスを付け、その結果得られたデータを GraphQL API を介してクエリに利用できるようにするコンポーネントです。そのため、インデクサースタックの中心であり、グラフノードの正しい動作は、成功するインデクサを実行するために重要です。 + +- **インデクサエージェント**:インデクサエージェントは、インデクサスタックの一部です。ネットワークへの登録、グラフノードへのサブグラフの展開の管理、割り当ての管理など、チェーン上でのインデクサーのインタラクションを促進します。 + +- **グラフクライアント**:GraphQL ベースの Dapps を分散的に構築するためのライブラリです。 + +- **グラフエクスプローラ**:ネットワーク参加者がサブグラフを探索し、プロトコルと対話するために設計された dapp です。 + +- **グラフ CLI**:The Graph を構築し、デプロイするためのコマンドラインインターフェースツールです。 + +- **クールダウン期間**:デリゲーションパラメータを変更したインデクサが再度デリゲーションできるようになるまでの残り時間。 diff --git a/website/pages/ja/index.json b/website/pages/ja/index.json index 2a69d5a015e2..5924b3db2a59 100644 --- a/website/pages/ja/index.json +++ b/website/pages/ja/index.json @@ -1,5 +1,5 @@ { - "title": "開始する", + "title": "始めましょう", "intro": "ブロックチェーンのデータにインデックスを付けたり、クエリを実行するための分散型プロトコル「The Graph」についてご紹介します。", "shortcuts": { "aboutTheGraph": { @@ -15,7 +15,7 @@ "description": "よくある質問と回答" }, "queryFromAnApplication": { - "title": "アプリケーションからのクエリ方法", + "title": "アプリケーションからのクエリ", "description": "アプリケーションからのクエリ方法を学ぶ" }, "createASubgraph": { @@ -28,7 +28,7 @@ } }, "networkRoles": { - "title": "ネットワークルール", + "title": "ネットワークの役割", "description": "The Graphのネットワークルールを学ぶ", "roles": { "developer": { @@ -36,20 +36,20 @@ "description": "サブグラフの作成及び既存のサブグラフを利用したdappの作成" }, "indexer": { - "title": "インデクシング", + "title": "インデクサー", "description": "ノードを稼働してデータインデックスを作成し、クエリサービスを提供する" }, "curator": { - "title": "キューレーティング", + "title": "学芸員", "description": "サブグラフのシグナリングによるデータの整理" }, "delegator": { - "title": "デリゲーティング", + "title": "委任者", "description": "保有GRTをインデクサーに委任することでネットワークの安全性を確保" } } }, - "readMore": "詳細", + "readMore": "続きを読む", "products": { "title": "プロダクト", "products": { @@ -62,16 +62,16 @@ "description": "サブグラフの探索とプロトコルとの対話" }, "hostedService": { - "title": "Hosted Service", + "title": "ホステッド サービス", "description": "ホストサービスでのサブグラフの作成と探索" } } }, "supportedNetworks": { - "title": "サポートネットワーク", + "title": "サポートされているネットワーク", "description": "The Graphでは、The Graph NetworkおよびHosted Serviceにおいて、以下のネットワークをサポートしています。", - "graphNetworkAndHostedService": "The Graph Network & Hosted Service", - "hostedService": "Hosted Service", - "betaWarning": "ネットワークはベータ版ですので慎重にご利用ください" + "graphNetworkAndHostedService": "グラフ ネットワークとホステッド サービス", + "hostedService": "ホステッド サービス", + "betaWarning": "ベータモードで" } } diff --git a/website/pages/ja/mips-faqs.mdx b/website/pages/ja/mips-faqs.mdx new file mode 100644 index 000000000000..18d3a285c353 --- /dev/null +++ b/website/pages/ja/mips-faqs.mdx @@ -0,0 +1,125 @@ +--- +title: MIPs FAQs +--- + +## イントロダクション + +The Graph エコシステムに参加するのはエキサイティングな時です。Graph Day 2022(https://thegraph.com/graph-day/2022/) で Yaniv Tal が[ホストサービスの終了](https://thegraph.com/blog/sunsetting-hosted-service/)を発表しましたが、これは The Graph エコシステムが何年も前から取り組んできた瞬間でした。 + +ホスティングサービスの終了と、そのすべての活動の分散型ネットワークへの移行をサポートするため、The Graph Foundation は[MIPs(Migration Infrastructure Providers)プログラム](https://thegraph.com/blog/mips-multi-chain-indexing-incentivized-program)を発表しています。 + +MIPs プログラムは、Ethereum メインネットを超えるチェーンをインデックスするためのリソースを提供し、The Graph プロトコルが分散型ネットワークをマルチチェーン基盤層に拡大することを支援する、インデクサーのためのインセンティブ・プログラムです。 + +MIPs プログラムは、GRT 供給量(75M GRT)の 0.75%を割り当て、0.5%をネットワークの起動に貢献したインデクサーへの報酬に、0.25%をマルチチェーンサブグラフを使用するサブグラフ開発者への移行補助金に割り当てています。 + +### 便利なリソース + +- [Indexer 2ools from Vincent (Victor) Taglia](https://indexer-2ools.vincenttaglia.com/#/) +- [How to Become an Effective Indexer on The Graph Network](https://thegraph.com/blog/how-to-become-indexer/) +- [Indexer Knowledge Hub](https://thegraph.academy/indexers/) +- [Allocation Optimiser](https://github.com/graphprotocol/allocationopt.jl) +- [Allocation Optimization Tooling](https://github.com/anyblockanalytics/thegraph-allocation-optimization/) + +### 1. サブグラフが破綻していても、有効な POI(Proof of Indexing)を生成することは可能ですか? + +はい、確かにそうです。 + +文脈上、arbitration charter [詳細はこちら](https://hackmd.io/@4Ln8SAS4RX-505bIHZTeRw/BJcHzpHDu#Abstract)は、失敗したサブグラフの POI を生成する方法を指定しています。 + +コミュニティメンバーの[SunTzu](https://github.com/suntzu93)が、arbitration charter の方法論に準拠してこのプロセスを自動化するスクリプトを作成しました。レポ [here](https://github.com/suntzu93/get_valid_poi_subgraph)をチェックしてください。 + +### 2. MIPs プログラムは、どのチェーンに最初にインセンティブを与えるのでしょうか? + +分散型ネットワークでサポートされる最初のチェーンは、Gnosis Chain です 以前は xDAI として知られていた Gnosis Chain は、EVM ベースのチェーンです。Gnosis Chain は、ノードの実行のしやすさ、Indexer の準備、The Graph との整合性、web3 での採用などを考慮して、最初のものとして選択されました。 + +### 3. MIPs プログラムに新しいチェーンはどのように追加されるのでしょうか? + +新しいチェーンは、インデクサーの準備、需要、コミュニティの感情に基づいて、MIPs プログラム全体を通して発表される予定です。チェーンはまずテストネットでサポートされ、その後、メインネットでそのチェーンをサポートするための GIP が可決されます。MIPs プログラムに参加するインデクサは、サポートするチェーンに興味があるものを選び、チェーンごとに報酬を得ることができます。MIPs 参加者は、そのパフォーマンス、ネットワークのニーズに応える能力、およびコミュニティのサポートに基づいて採点されます。 + +### 4. ネットワークが新しいチェーンに対応できるようになったら、どのように知ることができますか? + +グラフ財団は、QoS パフォーマンス指標、ネットワークパフォーマンス、コミュニティチャンネルを監視し、準備状況を最適に評価する予定です。優先順位は、ネットワークがマルチチェーン Dapps のサブグラフを移行するためのパフォーマンスニーズを満たすことを保証することです。 + +### 5. チェーンごとの報酬はどのように分配されますか? + +ノードを同期するための要件が ​​ チェーンごとに異なり、クエリの量と採用が異なることを考えると、チェーンごとの報酬は、すべてのフィードバックと学習が確実に取得されるように、そのチェーンのサイクルの最後に決定されます。ただし、チェーンがネットワークでサポートされると、いつでもインデクサーはクエリ料金とインデックス作成報酬を獲得することもできます。 + +### 6. MIPs プログラムのすべてのチェーンにインデックスを付ける必要がありますか、それとも 1 つのチェーンを選んでそのインデックスを付けることができますか? + +好きなチェーンにインデックスをつけることができます。MIPs プログラムの目標は、インデックス作成者に、彼らが望むチェーンにインデックスを作成し、彼らが興味を持つ Web3 エコシステムをサポートするためのツールと知識を提供することです。しかし、すべてのチェーンには、テストネットからメインネットまでの段階があります。インデックスを作成するチェーンについては、必ずすべてのフェーズを完了させてください。フェーズについては、[MIPs の概念ページ](https://thegraphfoundation.notion.site/MIPs-Home-911e1187f1d94d12b247317265f81059)を参照してください。 + +### 7. 報酬はいつ配布されるのですか? + +MIPs の報酬は、パフォーマンス指標が満たされ、移行されたサブグラフがそれらの Indexer によってサポートされると、チェーンごとに配布されます。チェーンごとの総報酬は、チェーンのサイクルの途中でお知らせします。 + +### 8. スコアリングの仕組み? + +インデックサーは、プログラム期間中のスコアに基づいて、リーダーボードで報酬を競うことになります。プログラムのスコアリングは、以下の項目に基づいて行われます。 + +**Subgraph Coverage** + +- チェーンごとにサブグラフの最大サポートを提供していますか? + +- MIP では、大規模な Indexer は、サポートするチェーンごとに 50%以上のサブグラフをステークすることが期待されます。 + +**Quality Of Service** + +- インデックサーは、サービス品質(レイテンシー、新鮮なデータ、アップタイムなど)が良い状態でチェーンにサービスを提供していますか? + +- インデクサーは、ダップ開発者のニーズに応えられるようなサポートをしていますか? + +インデクサーは効率的に割り当てられ、ネットワーク全体の健全性に寄与していますか? + +**Community Support** + +- インデクサーは、他のインデクサーの仲間と協力して、マルチチェーンに対応するためのセットアップを手伝っているのでしょうか? + +- インデクサーは、プログラムを通じてコア開発者にフィードバックしたり、フォーラムでインデクサーと情報を共有しているのでしょうか? + +### 9. Discord のロールはどのように割り振られるのでしょうか? + +数日中にモデレーターが役割を割り振る予定です。 + +### 10. テストネットでプログラムを開始し、その後メインネットに切り替えても問題ないでしょうか?私のノードを特定し、報酬を分配する際に考慮することは可能ですか? + +はい、実際にそうすることが期待されています。いくつかのフェーズが Görli にあり、1 つはメインネットにあります。 + +### 11. 参加者がメインネットのデプロイを追加するのはどの時点からでしょうか? + +フェーズ 3 では、メインネットインデクサーを持つことが要求されます。これに関する詳細な情報は、[近日中にこのコンセプトページで共有されます](https://thegraphfoundation.notion.site/MIPs-Home-911e1187f1d94d12b247317265f81059) + +### 12. 報酬は権利確定の対象になりますか? + +プログラム終了時に分配される割合は、権利確定に従うものとします。この詳細については、「インデクサー契約書」にて共有されます。 + +### 13. 複数のメンバーがいるチームの場合、チームメンバー全員に MIPs Discord のロールが与えられるのでしょうか? + +はい。 + +### 14. グラフキュレータープログラムでロックされたトークンを使って、MIPs テストネットに参加することは可能でしょうか? + +はい。 + +### 15. MIPs プログラム期間中、無効な POI に異議を唱える期間はあるのでしょうか? + +決定する予定です。このページで定期的に詳細をご確認いただくか、お急ぎの場合は info@thegraph.foundation までご連絡ください。 + +### 17. 2 つの権利確定コントラクトを組み合わせることは可能ですか? + +いいえ、選択肢としては、一方をもう一方にデリゲートするか、2 つの別々のインデクサーを稼働させるかです。 + +### 18. KYC に関する質問は? + +メールを info@thegraph.foundation までお寄せください。 + +### 19. Gnosis チェーンのインデックスの準備が出来ていないのですが、準備が出来たら他のチェーンからインデックスを開始しても良いですか? + +はい。 + +### 20. サーバーを稼働させる推奨地域はありますか? + +私たちは地域についての推奨はしていません。場所を選ぶ際には、暗号通貨の主要な市場がどこにあるのかを考えてみるとよいでしょう。 + +### 21. 「ハンドラーガスコスト」とは何ですか? + +ハンドラーを実行するコストの決定論的な尺度です。名前から想像されるのとは逆に、ブロックチェーン上のガスコストとは関係ありません。 diff --git a/website/pages/ja/network/curating.mdx b/website/pages/ja/network/curating.mdx index b8ea4b089d41..d36918ab159b 100644 --- a/website/pages/ja/network/curating.mdx +++ b/website/pages/ja/network/curating.mdx @@ -1,5 +1,5 @@ --- -title: キュレーター +title: キュレーティング --- キュレーターは、グラフの分散型経済にとって重要な存在です。 キューレーターは、web3 のエコシステムに関する知識を用いて、グラフネットワークがインデックスを付けるべきサブグラフを評価し、シグナルを送ります。 キュレーターはエクスプローラーを通じてネットワークのデータを見て、シグナルを出す判断をすることができます。グラフネットワークは、良質なサブグラフにシグナルを送ったキュレーターに、サブグラフが生み出すクエリフィーのシェアを与えます。 キュレーターには、早期にシグナルを送るという経済的なインセンティブが働きます。 キュレーターからのシグナルはインデクサーにとって非常に重要で、インデクサーはシグナルを受けたサブグラフからデータを処理したり、インデックスを作成したりすることができます。 @@ -10,7 +10,7 @@ title: キュレーター ## ボンディングカーブ 101 -順を追ってみていきましょう。 まず、各サブグラフにはボンディングカーブがあり、ユーザーがその曲線(カーブ)にシグナルを加えると、キュレーション・シェアが形成されます。 各サブグラフのボンディングカーブはユニークです。 ボンディングカーブは、サブグラフ上でキュレーション・シェアをミントするための価格が、ミントされるシェアの数に応じて直線的に増加するように設計されています。 +まず、一歩後退します。各サブグラフには結合曲線があり、ユーザーが曲線に**シグナルを追加**すると、キュレーション シェアが作成されます。各サブグラフの結合曲線は一意です。結合曲線は、サブグラフのキュレーション シェアを作成する価格が、作成されたシェアの数に比例して増加するように設計されています。 ![シェアあたりの価格](/img/price-per-share.png) @@ -27,13 +27,13 @@ title: キュレーター - 残りのキュレーターは、そのサブグラフのキュレーター・ロイヤリティーをすべて受け取ることになります。 もし彼らが自分のシェアをバーンして GRT を引き出す場合、彼らは 120,000GRT を受け取ることになります。 - **TLDR:** キュレーションシェアの GRT 評価はボンディングカーブによって決まるため、変動しやすいという傾向があります。 また、大きな損失を被る可能性があります。 早期にシグナリングするということは、1 つのシェアに対してより少ない GRT を投入することを意味します。 ひいては、同じサブグラフの後続のキュレーターよりも、GRT あたりのキュレーター・ロイヤリティーを多く得られることになります。 -一般的にボンディングカーブとは、トークンの供給量と資産価格の関係を定義する数学的な曲線のことです。 サブグラフのキュレーションという具体的なケースでは、サブグラフの各シェアの価格は、投資されたトークンごとに上昇し、販売されたトークンごとに減少します。 +一般に、結合曲線は、トークンの供給と資産価格の関係を定義する数学的曲線です。サブグラフ キュレーションの特定のケースでは、**各サブグラフ シェアの価格は投資されたトークンごとに上昇し**、**各シェアの価格は低下しますトークンが販売されるたびに。** The Graph の場合は、 [Bancor が実装しているボンディングカーブ式](https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA) を活用しています。 ## シグナルの出し方 -ボンディングカーブの仕組みについて基本的なことを説明しましたが、ここではサブグラフにシグナルを送る方法を説明します。 グラフ・エクスプローラーの「キュレーター」タブ内で、キュレーターはネットワーク・スタッツに基づいて特定のサブグラフにシグナルを送ることができるようになります。 エクスプローラーでの操作方法の概要はこちらをご覧ください。 +結合曲線がどのように機能するかについての基本を説明したので、これがサブグラフでシグナルを送信する方法です。グラフ エクスプローラーの [キュレーター] タブ内で、キュレーターは、ネットワーク統計に基づいて特定のサブグラフでシグナルを送信したり、シグナルを解除したりできます。 Explorer でこれを行う方法の段階的な概要については、[ここをクリック](/network/explorer)してください。 キュレーターは、特定のサブグラフのバージョンでシグナルを出すことも、そのサブグラフの最新のプロダクションビルドに自動的にシグナルを移行させることも可能ですます。 どちらも有効な戦略であり、それぞれに長所と短所があります。 @@ -61,7 +61,7 @@ The Graph の場合は、 [Bancor が実装しているボンディングカー 1. The Graph では、クエリ市場は本質的に歴史が浅く、初期の市場ダイナミクスのために、あなたの%APY が予想より低くなるリスクがあります。 2. キュレーション料 - キュレーターがサブグラフ上で GRT をシグナルすると、1%のキュレーション税が発生します。 この手数料はバーンされ、残りはボンディングカーブのリザーブサプライに預けられます。 -3. キュレーターが GRT を引き出すためにシェアをバーンすると、残りのシェアの GRT 評価額が下がります。 場合によっては、キュレーターが自分のシェアを一度にバーンすることを決めることがあるので注意が必要です。 このような状況は、dapp 開発者がサブグラフのバージョン管理や改良、クエリをやめた場合や、サブグラフが故障した場合によく見られます。 その結果、残ったキュレーターは当初の GRT の何分の一かしか引き出せないかもしれません。 リスクプロファイルの低いネットワークロールについては、\[Delegators\](/delegating)を参照してください。 +3. キュレーターが株式をバーンして GRT を撤回すると、残りの株式の GRT 評価額が引き下げられます。場合によっては、キュレーターが**一度にすべて**共有を破棄することを決定する場合があることに注意してください。この状況は、dApp 開発者がサブグラフのバージョン管理/改善とクエリを停止した場合、またはサブグラフが失敗した場合によく発生する可能性があります。その結果、残りのキュレーターは当初の GRT の一部しか引き出せない可能性があります。リスク プロファイルが低いネットワーク ロールについては、[委任者](/network/delegating)を参照してください。 4. サブグラフはバグで失敗することがあります。 失敗したサブグラフは、クエリフィーが発生しません。 結果的に、開発者がバグを修正して新しいバージョンを展開するまで待たなければならなくなります。 - サブグラフの最新バージョンに加入している場合、シェアはその新バージョンに自動移行します。 これには 0.5%のキュレーション税がかかります。 - 特定のサブグラフのバージョンでシグナリングしていて、それが失敗した場合は、手動でキュレーションシャイアをバーンする必要があります。 キュレーション・カーブに最初に預けた金額よりも多く、または少なく GRT を受け取る可能性があることに注意してください。 これはキュレーターとしてのリスクです。 そして、新しいサブグラフのバージョンにシグナルを送ることができ、1%のキュレーション税が発生します。 diff --git a/website/pages/ja/network/delegating.mdx b/website/pages/ja/network/delegating.mdx index ae68ff250e26..a0301c744719 100644 --- a/website/pages/ja/network/delegating.mdx +++ b/website/pages/ja/network/delegating.mdx @@ -1,14 +1,14 @@ --- -title: デリゲーティング +title: 委任 --- -デリゲーターは悪意の行動をしてもスラッシュされないが、デリゲーターにはデポジット税が課せられ、ネットワークの整合性を損なう可能性のある悪い意思決定を抑止します。 +委任者は、GRT を委任 (つまり、「ステーク」) して 1 つ以上のインデクサーに貢献するネットワーク参加者です。グラフ ノード自体を実行せずにネットワークを保護する委任者。 -このガイドでは、グラフネットワークで効果的なデリゲーターになるための方法を説明します。 デリゲーターは、デリゲートされたステークのすべてのインデクサーとともにプロトコルの収益を共有します。 デリゲーターは、複数の要素を考慮した上で、最善の判断でインデクサーを選ばなければなりません。 このガイドでは、メタマスクの適切な設定方法などについては説明しません。このガイドには 3 つのセクションがあります。 There are three sections in this guide: +インデクサーに委任することにより、委任者はインデクサーのクエリ料金と報酬の一部を獲得します。インデクサーが処理できるクエリの量は、インデクサー自身の (および委任された) ステークと、各クエリに対してインデクサーが請求する価格によって異なります。 ## デリゲーターガイド -以下に、本プロトコルでデリゲーターとなる場合の主なリスクを挙げます。 +このガイドでは、グラフ ネットワークで効果的な委任者になる方法について説明します。委任者は、委任されたステークに基づいて、すべてのインデクサーと一緒にプロトコルの収益を共有します。委任者は、複数の要因に基づいてインデクサーを選択するために最善の判断を下す必要があります。このガイドでは、Metamask の適切なセットアップなどの手順については説明しません。その情報はインターネットで広く入手できるためです。このガイドには、次の 3 つのセクションがあります: - グラフネットワークでトークンをデリゲートすることのリスク - デリゲーターとしての期待リターンの計算方法 @@ -16,21 +16,21 @@ title: デリゲーティング ## デリゲーションリスク -デリゲートするたびに、0.5%の手数料が発生します。 つまり、1000GRT を委任する場合は、自動的に 5GRT が消費されます。 +以下にリストされているのは、プロトコルで委任者になることの主なリスクです。 ### デリゲーション手数料 -つまり、安全のために、デリゲーターはインデクサーにデリゲートした場合のリターンを計算しておく必要があります。 例えば、デリゲーターは、自分のデリゲートに対する 0.5%のデポジット税を取り戻すのに何日かかるかを計算するとよいでしょう。 +デリゲーターは悪意の行動をしてもスラッシュされないが、デリゲーターにはデポジット税が課せられ、ネットワークの整合性を損なう可能性のある悪い意思決定を抑止します。 -デリゲーターが、デリゲーションを解除しようとすると、そのトークンは 28 日間のアンボンディング期間が設けられます。 つまり、28 日間はトークンの譲渡や報酬の獲得ができません。 +委任するたびに 0.5% が請求されることを理解することが重要です。これは、1000 GRT を委任する場合、自動的に 5 GRT を消費することを意味します。 -考慮すべき点は、インデクサーを賢く選ぶことです。 信頼できない、あるいは良い仕事をしていないインデクサーを選んだ場合、アンデリゲートしたくなるでしょう。 つまり、報酬を獲得する機会を大幅に失うことになり、GRT をバーンするのと同じくらいの負担となります。 +これは、安全を期すために、Delegator が Indexer に委譲することによって、リターンがどうなるかを計算する必要があることを意味します。たとえば、委任者は、委任に対する 0.5% の税金を取り戻すまでにかかる日数を計算する場合があります。 -### デリゲーションのアンボンディング期間 +### 委任期間無制限 -これは理解すべき重要な部分です。 まず、デリゲーションパラメータである 3 つの非常に重要な値について説明します。 +デリゲーターが、デリゲーションを解除しようとすると、そのトークンは 28 日間のアンボンディング期間が設けられます。 つまり、28 日間はトークンの譲渡や報酬の獲得ができません。 -インデキシング報酬カット - インデキシング報酬カットは、インデクサーが自分のために保持する報酬の部分です。 つまり、これが 100%に設定されていると、デリゲーターであるあなたは 0 のインデキシング報酬を得ることになります。 UI に 80%と表示されている場合は、デリゲーターとして 20%を受け取ることになります。 重要な注意点として、ネットワークの初期段階では、インデキシング報酬が報酬の大半を占めます。 +考慮すべき点は、インデクサーを賢く選ぶことです。 信頼できない、あるいは良い仕事をしていないインデクサーを選んだ場合、アンデリゲートしたくなるでしょう。 つまり、報酬を獲得する機会を大幅に失うことになり、GRT をバーンするのと同じくらいの負担となります。
デリゲーション UIの0.5%の手数料と、28日間のアンボンディング期間に注目してください。 @@ -38,18 +38,18 @@ title: デリゲーティング ### デリゲーターに公平な報酬を支払う信頼できるインデクサーの選択 -このように、適切なインデクサーを選択するためには、多くのことを考えなければなりません。 だからこそ、The Graph の Discord をリサーチして、社会的評価や技術的評価が高く、デリゲーターに安定して報酬を与えることができるインデクサーが誰なのかを見極めることを強くお勧めします。 多くのインデクサーは Discord で活発に活動しており、あなたの質問に喜んで答えてくれるでしょう。 彼らの多くはテストネットで何ヶ月もインデックスを作成しており、ネットワークの健全性と成功を向上させるために、デリゲーターが良いリターンを得られるように最善を尽くしています。 +これは理解しておくべき重要な部分です。最初に、委任パラメーターである 3 つの非常に重要な値について説明します。 -デリゲーターはリターンを決定する際に、多くの要素を考慮しなければなりません。 以下のとおりです: +インデキシング報酬カット - インデキシング報酬カットは、インデクサーが自分のために保持する報酬の部分です。 つまり、これが 100%に設定されていると、デリゲーターであるあなたは 0 のインデキシング報酬を得ることになります。 UI に 80%と表示されている場合は、デリゲーターとして 20%を受け取ることになります。 重要な注意点として、ネットワークの初期段階では、インデキシング報酬が報酬の大半を占めます。
- トップのインデクサーは、デリゲーターに90%の報酬を与えています。 The middle one is giving delegators 20%. The bottom - one is giving delegators ~83%.* + ![Indexing Reward Cut](/img/Indexing-Reward-Cut.png) ※上位インデクサーは委任者に90%の報酬を与えています。の + 中央のものは委任者に 20% を与えています。一番下のものは委任者に ~83% を与えています.*
- クエリーフィーカット - これはインデキシングリワードカットと全く同じ働きをします。 しかし、これは特に、インデクサーが収集したクエリフィーに対するリターンを対象としています。 ネットワークの初期段階では、クエリフィーからのリターンは、インデキシング報酬に比べて非常に小さいことに注意する必要があります。 ネットワーク内のクエリフィーがいつから大きくなり始めるのかを判断するために、ネットワークに注意を払うことをお勧めします。 -上記のセクションで説明したように、問い合わせ手数料カットとインデクシングフィーのカット設定について透明性が高く、誠実なインデクサーを選ぶべきです。 デリゲーターは、Parameters Cooldown の時間を見て、どれだけの時間的余裕があるかを確認する必要があります。 その後、デリゲーターが得ている報酬の額を計算するのはとても簡単です。 その式は以下のとおりです: +ご覧のとおり、適切なインデクサーを選択するには多くの考慮が必要です。これが、The Graph Discord を調べて、最高の社会的評判と技術的評判を持つインデクサーを特定し、委任者に報酬を与えることを強くお勧めする理由です。インデクサーの多くは Discord で非常に活発に活動しており、喜んで質問に答えてくれます。それらの多くは、テストネットで数か月間インデックスを作成しており、ネットワークの健全性と成功を改善するため、委任者が良いリターンを得るのを助けるために最善を尽くしています. ### デリゲーターの期待リターンを計算 @@ -60,38 +60,38 @@ title: デリゲーティング ### クエリフィーのカットとインデックスフィーのカットの検討 -デリゲーターが考慮しなければならないもう一つのことは、デリゲーションプールのどの割合を所有しているかということです。 全てのデリゲーション報酬は均等に分配され、デリゲーターがプールに入金した金額によって決まるプールの簡単なリバランスが行われます。 これにより、デリゲーターはプールのシェアを得ることができます。 +上記のセクションで説明したように、クエリ料金カットとインデックス作成料金カットの設定について透明性があり誠実なインデクサーを選択する必要があります。デリゲーターは、パラメーターのクールダウン時間も調べて、どれだけの時間バッファーがあるかを確認する必要があります。その後、委任者が受け取る報酬の額を計算するのは非常に簡単です。式は次のとおりです。 -![シェアの計算式](/img/Delegation-Reward-Formula.png) +![デリゲーション イメージ 3](/img/Delegation-Reward-Formula.png) ### インデクサーのデリゲーションプールを考慮する -したがって、デリゲーターは計算して、デリゲーターに 20%を提供しているインデクサーの方が、より良いリターンを提供していると判断することができます。 +委任者が考慮しなければならないもう 1 つのことは、自分が所有する委任プールの割合です。すべての委任報酬は均等に共有され、委任者がプールに入金した金額によって決定されるプールの単純なリバランスが行われます。これにより、委任者にプールのシェアが与えられます。 ![シェアの計算式](/img/Share-Forumla.png) -もうひとつ考慮しなければならないのが、デリゲーション能力です。 現在、デリゲーションレシオは 16 に設定されています。 これは、インデクサーが 1,000,000GRT をステークしている場合、そのデリゲーション容量はプロトコルで使用できる 16,000,000GRT のデリゲーショントークンであることを意味します。 この量を超えるデリゲートされたトークンは、全てのデリゲーター報酬を薄めてしまいます。 +この式を使うと、デリゲーターに対して 20%しか提供していないインデクサーが、デリゲーターに対して 90%提供しているインデクサーよりも、実際にデリゲーターにより良い報酬を提供できることがわかります。 -あるインデクサーが 100,000,000 GRT をデリゲートされていて、その容量が 16,000,000 GRT しかないと想像してみてください。 これは事実上、84,000,000 GRT トークンがトークンの獲得に使われていないことを意味します。 そして、すべてのデリゲーターとインデクサーは、本来得られるはずの報酬よりもずっと少ない報酬しか得られていません。 +したがって、委任者は計算を行って、委任者に 20% を提供するインデクサーがより良いリターンを提供していることを判断できます。 -### デリゲーション能力を考慮する +### デリゲーションの容量を考慮する -この式を使うと、デリゲーターに 20%しか提供していないインデクサーが、デリゲーターに 90%を提供しているインデクサーよりも、デリゲーターにさらに良い報酬を与えている可能性があることがわかります。 +もうひとつ考慮しなければならないのが、デリゲーション能力です。 現在、デリゲーションレシオは 16 に設定されています。 これは、インデクサーが 1,000,000GRT をステークしている場合、そのデリゲーション容量はプロトコルで使用できる 16,000,000GRT のデリゲーショントークンであることを意味します。 この量を超えるデリゲートされたトークンは、全てのデリゲーター報酬を薄めてしまいます。 -この式を使うと、デリゲーターに 20%しか提供していないインデクサーが、デリゲーターに 90%を提供しているインデクサーよりも、デリゲーターにさらに良い報酬を与えている可能性があることがわかります。 +あるインデクサーが 100,000,000 GRT をデリゲートされていて、その容量が 16,000,000 GRT しかないと想像してみてください。 これは事実上、84,000,000 GRT トークンがトークンの獲得に使われていないことを意味します。 そして、すべてのデリゲーターとインデクサーは、本来得られるはずの報酬よりもずっと少ない報酬しか得られていません。 したがって、デリゲーターはインデクサーのデリゲーション・キャパシティを常に考慮し、意思決定に反映させる必要があります。 -## Delegator FAQs and Bugs +## デリゲーターに関する FAQ と不具合 -### MetaMask "Pending Transaction" Bug +### MetaMask "Pending Transaction "バグ -**When I try to delegate my transaction in MetaMask appears as "Pending" or "Queued" for longer than expected. What should I do?** +**MetaMask のトランザクションをデリゲートしようとすると、"Pending "または "Queued "と表示され、予定より長く待たされることがあります。どうしたらよいでしょうか?** -At times, attempts to delegate to indexers via MetaMask can fail and result in prolonged periods of "Pending" or "Queued" transaction attempts. For example, a user may attempt to delegate with an insufficient gas fee relative to the current prices, resulting in the transaction attempt displaying as "Pending" in their MetaMask wallet for 15+ minutes. When this occurs, subsequent transactions can be attempted by a user, but these will not be processed until the initial transaction is mined, as transactions for an address must be processed in order. In such cases, these transactions can be cancelled in MetaMask, but the transactions attempts will accrue gas fees without any guarantee that subsequent attempts will be successful. A simpler resolution to this bug is restarting the browsesr (e.g., using "abort:restart" in the address bar), which will cancel all previous attempts without gas being subtracted from the wallet. Several users that have encountered this issue and have reported successful transactions after restarting their browser and attempting to delegate. +MetaMask を経由して indexer にデリゲートしようとすると、失敗して「Pending」または「Queued」トランザクションの試行が長時間続くことがあります。例えば、あるユーザーが現在の価格に対して不十分なガソリン代でデリゲートを試みた結果、そのユーザーの MetaMask ウォレットに 15 分以上「Pending」と表示されることがあります。このような場合、ユーザーは後続の取引を試みることができますが、アドレスに対する取引は順番に処理されなければならないため、最初の取引がマイニングされるまで処理されることはありません。このような場合、これらの取引は MetaMask でキャンセルすることができますが、その後の取引の試みが成功する保証はなく、ガス代が発生することになります。このバグに対するより簡単な解決策は、ブラウザを再起動することです(例:アドレスバーで "abort:restart" を使用)。この問題に遭遇した複数のユーザーが、ブラウザを再起動し、デリゲートを試みた後に取引が成功したと報告しています。 -## Video guide for the network UI +## ネットワーク UI のビデオガイド -This guide provides a full review of this document, and how to consider everything in this document while interacting with the UI. +このガイドでは、このドキュメントの完全なレビューと、UI を操作しながらこのドキュメントのすべてを検討する方法について説明します。 diff --git a/website/pages/ja/querying/distributed-systems.mdx b/website/pages/ja/querying/distributed-systems.mdx index 07bec072079d..cad66bf200f7 100644 --- a/website/pages/ja/querying/distributed-systems.mdx +++ b/website/pages/ja/querying/distributed-systems.mdx @@ -2,7 +2,7 @@ title: 分散システム --- -The Grap は、分散システムとして実装されたプロトコルです。 +グラフは、分散システムとして実装されたプロトコルです。 接続に失敗する。リクエストの順番が狂う。時計や状態が同期していない別のコンピュータが、関連するリクエストを処理する。サーバーが再起動する。リクエストとリクエストの間に「再衝突」が起こる。これらの問題は、すべての分散システムに固有のものですが、グローバルな規模で運用されているシステムでは、さらに悪化します。 diff --git a/website/pages/ja/querying/managing-api-keys.mdx b/website/pages/ja/querying/managing-api-keys.mdx index ee7c274bca10..65bba507fc93 100644 --- a/website/pages/ja/querying/managing-api-keys.mdx +++ b/website/pages/ja/querying/managing-api-keys.mdx @@ -1,26 +1,26 @@ --- -title: Managing your API keys +title: API キーの管理 --- -Regardless of whether you’re a dapp developer or a subgraph developer, you’ll need to manage your API keys. This is important for you to be able to query subgraphs because API keys make sure the connections between application services are valid and authorized. This includes authenticating the end user and the device using the application. +Dapp 開発者、サブグラフ開発者に関わらず、API キーを管理する必要があります。API キーは、アプリケーションサービス間の接続が有効で認証されていることを確認するため、サブグラフを照会できるようにするために重要です。これには、アプリケーションを使用するエンドユーザとデバイスの認証が含まれます。 -The Studio will list out existing API keys, which will give you the ability to manage or delete them. +スタジオでは、既存の API キーがリストアップされ、管理や削除が可能になります。 -1. The **Overview** section will allow you to: - - Edit your key name - - Regenerate API keys - - View the current usage of the API key with stats: - - Number of queries - - Amount of GRT spent -2. Under **Security**, you’ll be able to opt into security settings depending on the level of control you’d like to have over your API keys. In this section, you can: - - View and manage the domain names authorized to use your API key - - Assign subgraphs that can be queried with your API key -3. Under **Indexer Preference**, you’ll be able to set different preferences for Indexers who are indexing subgraphs that your API key is used for. You can assign up to 5 points for each of these: - - **Fastest Speed**: Time between the query and the response from an indexer. If you mark this as important we will optimize for fast indexers. - - **Lowest Price**: The amount paid per query. If you mark this as important we will optimize for the less expensive indexers. - - **Data Freshness**: How recent the latest block an indexer has processed for the subgraph you are querying. If you mark this as important we will optimize to find the indexers with the freshest data. - - **Economic Security**: The amount of GRT an indexer can lose if they respond incorrectly to your query. If you mark this as important we will optimize for indexers with a large stake. -4. Under **Budget**, you’ll be able to update the maximum price per query. Note that we have a dynamic setting for that that's based on a volume discounting algorithm. **We strongly recommend using the default settings unless you are experiencing a specific problem.** Otherwise, you can update it under "Set a custom maximum budget". On this page you can also view different KPIs (in GRT and USD): - - Average cost per query - - Failed queries over max price - - Most expensive query +1. **Overview**セクションでは、以下のことができます: + - キー名の編集 + - API キーの再生成 + - API キーの現在の使用状況を統計で表示: + - クエリの数 + - 使用した GRT の量 +2. **Security**では、API キーの管理レベルに応じて、セキュリティ設定を選択することができます。このセクションでは、次のことが可能です: + - API キーの使用を許可されたドメイン名の表示と管理 + - API キーでクエリ可能なサブグラフの割り当て +3. **インデクサー設定** では、API キーが使用されるサブグラフのインデックスを作成するインデクサーに対して、さまざまな設定を行うことができます。これらのそれぞれに最大 5 ポイントを割り当てることができます。 + - **Fastest Speed**: クエリからインデクサーの応答までの時間。これを重要視すると、高速なインデクサーのために最適化されます。 + - **Lowest Price**: クエリごとに支払われる金額。これを重要視すると、より安価なインデクサに最適化されます。 + - **Data Freshness**: クエリしようとしているサブグラフについて、インデクサーが処理した最新のブロックの鮮度。これを重要視すると、最も新しいデータを持つインデクサを見つけるよう最適化されます。 + - **Economic Security**: もしクエリに対して誤った応答をした場合、インデクサーが失う可能性のある GRT の量。これを重要としてマークすると、私たちは大きなステーク量を持つインデクサーのために最適化します。 +4. **Budget**では、クエリごとの最大価格を更新することができます。ボリュームディスカウントのアルゴリズムに基づいた動的な設定があることに注意してください。**特定の問題が発生しない限り、デフォルトの設定を使用することを強くお勧めします。**それ以外の場合は、「カスタム最高予算の設定」で更新できます。このページでは、さまざまな KPI を表示することもできます(GRT と USD 単位)。 + - クエリあたりの平均コスト + - 最大価格以上のクエリの失敗 + - 最も高価なクエリ diff --git a/website/pages/ja/querying/querying-best-practices.mdx b/website/pages/ja/querying/querying-best-practices.mdx index 237316ef494f..a8d0ea7100d5 100644 --- a/website/pages/ja/querying/querying-best-practices.mdx +++ b/website/pages/ja/querying/querying-best-practices.mdx @@ -1,22 +1,22 @@ --- -title: Querying Best Practices +title: クエリのベストプラクティス --- -The Graph provides a decentralized way to query data from blockchains. +The Graph は、ブロックチェーンのデータをクエリするための分散化された方法を提供します。 -The Graph network's data is exposed through a GraphQL API, making it easier to query data with the GraphQL language. +The Graph のネットワークのデータは GraphQL API で公開され、GraphQL 言語によるデータクエリーが容易になります。 -This page will guide you through the essential GraphQL language rules and GraphQL queries best practices. +このページでは、GraphQL の言語ルールと GraphQL クエリのベストプラクティスに必要不可欠な情報をご案内しています。 --- -## Querying a GraphQL API +## GraphQL API のクエリ -### The anatomy of a GraphQL query +### GraphQL クエリの構造 -Unlike REST API, a GraphQL API is built upon a Schema that defines which queries can be performed. +REST API とは異なり、GraphQL API は実行可能なクエリを定義する Schema をベースに構築されています。 -For example, a query to get a token using the `token` query will look as follows: +例えば、`token`クエリを使ってトークンを取得するクエリは次のようになります。 ```graphql query GetToken($id: ID!) { @@ -27,7 +27,7 @@ query GetToken($id: ID!) { } ``` -which will return the following predictable JSON response (_when passing the proper `$id` variable value_): +以下のような予測可能な JSON レスポンスが返ってきます(_適切な`$id`変数値を渡す場合_)。 ```json { @@ -38,9 +38,9 @@ which will return the following predictable JSON response (_when passing the pro } ``` -GraphQL queries use the GraphQL language, which is defined upon [a specification](https://spec.graphql.org/). +GraphQL クエリは、[仕様](https://spec.graphql.org/)で定義されている GraphQL 言語を使用します。 -The above `GetToken` query is composed of multiple language parts (replaced below with `[...]` placeholders): +上記の `GetToken` クエリは、複数の言語部分で構成されています (以下では `[...]` プレースホルダーに置き換えられています)。 ```graphql query [operationName]([variableName]: [variableType]) { @@ -52,28 +52,41 @@ query [operationName]([variableName]: [variableType]) { } ``` -While the list of syntactic do's and don'ts is long, here are the essential rules to keep in mind when it comes to writing GraphQL queries: +構文の「やるべきこと」「やってはいけないこと」を挙げればきりがありませんが、ここでは GraphQL クエリを書く際に覚えておきたい基本的なルールを紹介します: -- Each `queryName` must only be used once per operation. -- Each `field` must be used only once in a selection (we cannot query `id` twice under `token`) -- Some `field`s or queries (like `tokens`) return complex types that require a selection of sub-field. Not providing a selection when expected (or providing one when not expected - for example, on `id`) will raise an error. To know a field type, please refer to [The Graph Explorer](/network/explorer). -- Any variable assigned to an argument must match its type. -- In a given list of variables, each of them must be unique. -- All defined variables must be used. +- 各`queryName`は、1 回の操作で 1 回だけ使用しなければなりません。 +- 各`フィールド`は、選択の中で一度だけ使用しなければなりません(`トークン`の下に`id`を二度照会することはできません)。 +- いくつかの `field` やクエリ (`tokens` など) は、サブフィールドの選択を必要とする複雑な型を返します。期待されたときに選択を提供しない(あるいは期待されていないときに提供する-たとえば`id`の場合)ことは、エラーを発生させます。フィールドタイプを知るには、[The Graph Explorer](/network/explorer)を参照してください。 +- 引数に代入される変数は、その型と一致しなければなりません。 +- 与えられた変数のリストにおいて、各変数は一意でなければなりません。 +- 定義された変数はすべて使用する必要があります。 -Failing to follow the above rules will end with an error from the Graph API. +上記のルールに従わない場合、Graph API からエラーが発生します。 -For a complete list of rules with code examples, please look at our GraphQL Validations guide. +ルールの完全なリストとコード例については、GraphQL Validations ガイドをご覧ください。
-### Sending a query to a GraphQL API +### GraphQL API へのクエリの送信 -GraphQL is a language and set of conventions that transport over HTTP. +GraphQL は、HTTP で転送する言語と規約のセットです。 -It means that you can query a GraphQL API using standard `fetch` (natively or via `cross-undici-fetch` or `isomorphic-fetch`) as follows: +標準の `fetch` (ネイティブまたは `@whatwg-node/fetch` や `isomorphic-fetch`) を使って GraphQL API にクエリできることを意味します。 + +ただし、[「アプリケーションからの問い合わせ」](/querying/querying-from-an-application)にあるように、独自の機能をサポートする`graph-client`を使用することをお勧めします。 + +- クロスチェーンのサブグラフ処理:1 回のクエリで複数のサブグラフからクエリを実行可能 +- [自動ブロック追跡](https://github.com/graphprotocol/graph-client/blob/main/packages/block-tracking/README.md) +- [自動ページング](https://github.com/graphprotocol/graph-client/blob/main/packages/auto-pagination/README.md) +- 完全なタイプ付け結果 + +
+ +ここでは、`graph-client`を使用して、The Graph に問い合わせる方法を説明します。 ```tsx +import { execute } from '../.graphclient' + const query = ` query GetToken($id: ID!) { token(id: $id) { @@ -84,67 +97,28 @@ query GetToken($id: ID!) { ` const variables = { id: '1' } -const fetchResult = await fetch('http://example.com/graphql', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ query, variables }), -}) -const result = await fetchResult.json() -``` - -Another lightweight alternative, best for back-end use-cases, is the famous [`graphql-request` library](https://github.com/prisma-labs/graphql-request). - -This lightweight GraphQL client comes with the essential features to query a GraphQL API: - -- Mutations validation -- Support for file upload -- Batching -- Promise-based API -- TypeScript support - -
- -A complete GraphQL client is [URQL](https://formidable.com/open-source/urql/) which is available within Node.js, React/Preact, Vue, Svelte environments, with more advanced features: - -- Flexible cache system -- Extensible design (easing adding new capabilities on top of it) -- Lightweight bundle (~5x lighter than Apollo Client) -- Support for file uploads and offline mode - -
- -In the React ecosystem, [React Query](https://react-query.tanstack.com/graphql) brings a lightweight and agnostic solution for GraphQL. - -React Query is a great candidate if you are looking for an easy-to-use and lightweight multipurpose client (GraphQL-capable) that provides essential features such as: - -- Powerful cache (background refresh, window-focus refreshing) -- Advanced querying pattern (parallel queries, dependent queries, prefetching) -- UX patterns: optimistic updates, scroll restoration -- Great dev tools - -
- -Finally, Apollo Client is the ubiquitous GraphQL client on the front-end ecosystem. +async function main() { + const result = await execute(query, variables) + // `result` is fully typed! + console.log(result) +} -Available for React, Angular, Vue, Ember, iOS, and Android, Apollo Client, although the heaviest clients, brings many features to build advanced UI on-top of GraphQL: +main() +``` -- advanced error handling -- pagination -- data prefetching -- optimistic UI -- local state management +GraphQL クライアントの他の選択肢については、["Querying from an Application"](/querying/querying-from-an-application) で説明しています。
-Now that we covered the basic rules of GraphQL queries syntax, let's now look at the best practices of GraphQL query writing. +GraphQL クエリの構文に関する基本的なルールを説明したところで、次は GraphQL クエリの書き方に関するベストプラクティスを見ていきましょう。 --- -## Writing GraphQL queries +## GraphQL クエリの作成 -### Always write static queries +### 常に静的なクエリを記述 -A common (bad) practice is to dynamically build query strings as follows: +一般的な(悪い)習慣として、以下のように動的にクエリ文字列を構築することがあります。 ```tsx const id = params.id @@ -160,14 +134,14 @@ query GetToken { // Execute query... ``` -While the above snippet produces a valid GraphQL query, **it has many drawbacks**: +上記のスニペットは有効な GraphQL クエリを生成しますが、** これには多くの欠点**があります: -- it makes it **harder to understand** the query as a whole -- developers are **responsible for safely sanitizing the string interpolation** -- not sending the values of the variables as part of the request parameters **prevent possible caching on server-side** -- it **prevents tools from statically analyzing the query** (ex: Linter, or type generations tools) +- クエリ全体を**理解するのが難しくなります**。 +- 開発者は、**文字列補間を安全にサニタイズする責任がある**ということです。 +- リクエストパラメータの一部として変数の値を送信しないでください。**サーバー側でのキャッシュの可能性を防止** +- それは ** ツールがクエリを静的に分析するのを防ぐ** (例: Linter、またはタイプ生成ツール) です。 -For this reason, it is recommended to always write queries as static strings: +このため、クエリは常に静的な文字列として記述することが推奨されます: ```tsx import { execute } from 'your-favorite-graphql-client' @@ -189,18 +163,18 @@ const result = await execute(query, { }) ``` -Doing so brings **many advantages**: +そうすることで、**多くの利点**を得ることができます。 -- **Easy to read and maintain** queries -- The GraphQL **server handles variables sanitization** -- **Variables can be cached** at server-level -- **Queries can be statically analyzed by tools** (more on this in the following sections) +- **読みやすく、メンテナンスしやすい**クエリ +- GraphQL の**サーバーは、変数のサニタイズを処理します** +- サーバーレベルで**変数がキャッシュできます**。 +- **ツールでクエリを静的に分析できる**(これについては、次のセクションで詳しく説明します。) -**Note: How to include fields conditionally in static queries** +**参考:静的クエリに条件付きでフィールドを含める方法** -We might want to include the `owner` field only on a particular condition. +特定の条件下でのみ`owner`フィールドを含めたいと思うかもしれません。 -For this, we can leverage the `@include(if:...)` directive as follows: +そのためには、次のように`@include(if:...)`指令を活用します。 ```tsx import { execute } from 'your-favorite-graphql-client' @@ -223,23 +197,23 @@ const result = await execute(query, { }) ``` -Note: The opposite directive is `@skip(if: ...)`. +注:反対の指示は `@skip(if: ...)` です。
-### Performance tips +### パフォーマンスに関するヒント **"Ask for what you want"** -GraphQL became famous for its "Ask for what you want" tagline. +GraphQL は「Ask for what you want」というキャッチフレーズで有名になりました。 -For this reason, there is no way, in GraphQL, to get all available fields without having to list them individually. +このため、GraphQL では、利用可能なすべてのフィールドを個別にリストアップすることなく取得する方法はありません。 -When querying GraphQL APIs, always think of querying only the fields that will be actually used. +GraphQL API にクエリを行う際は、常に実際に使用されるフィールドのみをクエリするように考えてください。 -A common cause of over-fetching is collections of entities. By default, queries will fetch 100 entities in a collection, which is usually much more than what will actually be used, e.g., for display to the user. Queries should therefore almost always set first explicitly, and make sure they only fetch as many entities as they actually need. This applies not just to top-level collections in a query, but even more so to nested collections of entities. +過剰フェッチの一般的な原因は、エンティティのコレクションです。デフォルトでは、クエリはコレクション内の 100 個のエンティティをフェッチしますが、これは通常、ユーザへの表示など、実際に使用される数よりもはるかに多い数です。このため、クエリはほとんどの場合、最初に明示的に設定し、実際に必要な数だけのエンティティをフェッチするようにしなければなりません。これは、クエリのトップレベル・コレクションだけでなく、エンティティのネストされたコレクションにも当てはまります。 -For example, in the following query: +例えば、以下のようなクエリの場合: ```graphql query listTokens { @@ -254,13 +228,13 @@ query listTokens { } ``` -The response could contain 100 transactions for each of the 100 tokens. +レスポンスには、100 個のトークンごとに 100 個のトランザクションが含まれる可能性があります。 -If the application only needs 10 transactions, the query should explicitly set `first: 10` on the transactions field. +アプリケーションが 10 トランザクションしか必要としない場合、クエリは transactions フィールドに`first: 10`を明示的に設定する必要があります。 -**Combining multiple queries** +**複数のクエリを組み合わせる** -Your application might require querying multiple types of data as follows: +アプリケーションでは、次のように複数の種類のデータをクエリする必要があるかもしれません: ```graphql import { execute } from "your-favorite-graphql-client" @@ -290,9 +264,9 @@ const [tokens, counters] = Promise.all( ) ``` -While this implementation is totally valid, it will require two round trips with the GraphQL API. +この実装は全く有効ですが、GraphQL API と 2 往復する必要があります。 -Fortunately, it is also valid to send multiple queries in the same GraphQL request as follows: +幸いなことに、以下のように同じ GraphQL リクエストで複数のクエリを送信することも有効です: ```graphql import { execute } from "your-favorite-graphql-client" @@ -309,19 +283,17 @@ query GetTokensandCounters { } } ` - -const { result: { tokens, counters } } = execute(query) ``` -This approach will **improve the overall performance** by reducing the time spent on the network (saves you a round trip to the API) and will provide a **more concise implementation**. +このアプローチは、ネットワークに費やす時間を減らすことで**全体のパフォーマンスを向上させ**、**より簡潔な実装**を提供します:
-### Leverage GraphQL Fragments +### GraphQL フラグメントの活用 -A helpful feature to write GraphQL queries is GraphQL Fragment. +GraphQL のクエリを書くのに便利な機能として、GraphQL Fragment があります。 -Looking at the following query, you will notice that some fields are repeated across multiple Selection-Sets (`{ ... }`): +以下のクエリを見ると、いくつかのフィールドが複数の Selection-Sets にまたがって繰り返されていることに気づきます(`{ ... }`)。 ```graphql query { @@ -341,12 +313,12 @@ query { } ``` -Such repeated fields (`id`, `active`, `status`) bring many issues: +このように繰り返されるフィールド(`id`, `active`, `status`)は多くの問題を引き起こします。 -- harder to read for more extensive queries -- when using tools that generate TypeScript types based on queries (_more on that in the last section_), `newDelegate` and `oldDelegate` will result in two distinct inline interfaces. +- より広範囲なクエリに対応するために読みにくくなります +- クエリに基づいて TypeScript 型を生成するツールを使用する場合 (_前のセクションで詳しく説明します_)、`newDelegate` および `oldDelegate` は、2 つの異なるインライン インターフェイスになります。 -A refactored version of the query would be the following: +クエリをリファクタリングすると、次のようになります: ```graphql query { @@ -370,17 +342,17 @@ fragment DelegateItem on Transcoder { } ``` -Using GraphQL `fragment` will improve readability (especially at scale) but also will result in better TypeScript types generation. +GraphQL の`fragment`を使用すると、可読性が向上しますが(特に大規模な場合)、TypeScript の型の生成もうまくいくようになります。 -When using the types generation tool, the above query will generate a proper `DelegateItemFragment` type (_see last "Tools" section_). +ジェネレーションツールを使うと、上記のクエリは適切な`DelegateItemFragment`タイプを生成します (_see last "Tools" section_).
-### GraphQL Fragment do's and don'ts +### GraphQL フラグメントの注意点 -**Fragment base must be a type** +**フラグメントのベースは、以下のタイプでなければなりません。** -A Fragment cannot be based on a non-applicable type, in short, **on type not having fields**: +フラグメントは適用不可能なタイプ、つまり**フィールドを持たないタイプ**に基づくことはできません。 ```graphql fragment MyFragment on BigInt { @@ -388,13 +360,13 @@ fragment MyFragment on BigInt { } ``` -`BigInt` is a **scalar** (native "plain" type) that cannot be used as a fragment's base. +`BigInt` は **scalar** (ネイティブの "plain" 型) で、フラグメントのベースとして使用することはできません。 -**How to spread a Fragment** +**フラグメントの拡散方法** -Fragments are defined on specific types and should be used accordingly in queries. +フラグメントは特定の型に定義されており、クエリではそれに応じて使用する必要があります。 -Example: +例: ```graphql query { @@ -415,20 +387,20 @@ fragment VoteItem on Vote { } ``` -`newDelegate` and `oldDelegate` are of type `Transcoder`. +`newDelegate` と `oldDelegate` は `Transcoder` 型です。 -It is not possible to spread a fragment of type `Vote` here. +ここで`Vote`型のフラグメントを広げることはできません。 -**Define Fragment as an atomic business unit of data** +**フラグメントをデータの原子的なビジネスユニットとして定義する** -GraphQL Fragment must be defined based on their usage. +GraphQL Fragment は、その用途に応じて定義する必要があります。 -For most use-case, defining one fragment per type (in the case of repeated fields usage or type generation) is sufficient. +ほとんどのユースケースでは、1 つの型につき 1 つのフラグメントを定義すれば十分です(フィールドの使用や型の生成が繰り返される場合)。 -Here is a rule of thumb for using Fragment: +Fragment の使い方の目安を紹介します。 -- when fields of the same type are repeated in a query, group them in a Fragment -- when similar but not the same fields are repeated, create multiple fragments, ex: +- 同じ型のフィールドがクエリ内で繰り返される場合、それらを Fragment でグループ化します。 +- 同じフィールドが繰り返される場合、複数のフラグメントを作成します。 ```graphql # base fragment (mostly used in listing) @@ -451,121 +423,55 @@ fragment VoteWithPoll on Vote { --- -## The essential tools +## 必須ツール -### GraphQL web-based explorers +### GraphQL ウェブベースのエクスプローラ -Iterating over queries by running them in your application can be cumbersome. For this reason, don't hesitate to use [The Graph Explorer](https://thegraph.com/explorer) to test your queries before adding them to your application. The Graph Explorer will provide you a preconfigured GraphQL playground to test your queries. +アプリケーションでクエリを実行して繰り返し実行することは、面倒なことです。このため、アプリケーションにクエリを追加する前に、[The Graph Explorer](https://thegraph.com/explorer) を使用してクエリをテストすることをためらわないでください。Graph Explorer は、クエリをテストするためにあらかじめ設定された GraphQL プレイグラウンドを提供します。 -If you are looking for a more flexible way to debug/test your queries, other similar web-based tools are available such as [Altair](https://altair.sirmuel.design/) and [GraphiQL](https://graphiql-online.com/graphiql). +クエリのデバッグやテストをもっと柔軟に行いたい場合は、[Altair](https://altair.sirmuel.design/) や [GraphiQL](https://graphiql-online.com/graphiql) など、同様のウェブベースツールが利用できます。
### GraphQL Linting -In order to keep up with the mentioned above best practices and syntactic rules, it is highly recommended to use the following workflow and IDE tools. +上記のベストプラクティスと構文ルールを維持するために、以下のワークフローと IDE ツールを使用することを強く推奨します。 **GraphQL ESLint** -[GraphQL ESLint](https://github.com/dotansimha/graphql-eslint) will help you stay on top of GraphQL best practices with zero effort. +[GraphQL ESLint](https://github.com/dotansimha/graphql-eslint) は、労力をかけずに GraphQL のベストプラクティスを把握できるようにします。 -[Setup the "operations-recommended"](https://github.com/dotansimha/graphql-eslint#available-configs) config will enforce essential rules such as: +[「operations-recommended」](https://github.com/dotansimha/graphql-eslint#available-configs)の設定により、以下のような本質的なルールが実施されます: -- `@graphql-eslint/fields-on-correct-type`: is a field used on a proper type? -- `@graphql-eslint/no-unused variables`: should a given variable stay unused? -- and more! +- `@graphql-eslint/fields-on-correct-type`: フィールドは適切なタイプで使用されているか? +- `@graphql-eslint/no-unused variables`: 与えられた変数は未使用のままであるべきか? +- ともっと -This will allow you to **catch errors without even testing queries** on the playground or running them in production! +これにより、プレイグラウンドで**クエリをテストしたり、本番環境で実行したりすることなく、エラーをキャッチ**できます!
### IDE plugins -**VSCode and GraphQL** +**VSCode と GraphQL** -The [GraphQL VSCode extension](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) is an excellent addition to your development workflow to get: +[GraphQL VSCode 拡張機能](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql)は、開発ワークフローに次の機能を追加する優れた機能です。 -- syntax highlighting -- autocomplete suggestions -- validation against schema +- 構文の強調表示 +- オートコンプリートの提案 +- スキーマに対する検証 - snippets -- go to definition for fragments and input types +- フラグメントと入力タイプの定義に移動 -If you are using `graphql-eslint`, the [ESLint VSCode extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) is a must-have to visualize errors and warnings inlined in your code correctly. +`graphql-eslint`を使用している場合、[ESLint VSCode extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)は、コードにインライン化されたエラーや警告を正しく視覚化するための必需品です。 -**WebStorm/Intellij and GraphQL** +**WebStorm/Intellij と GraphQL** -The [JS GraphQL plugin](https://plugins.jetbrains.com/plugin/8097-graphql/) will significantly improve your experience while working with GraphQL by providing: +[JS GraphQL plugin](https://plugins.jetbrains.com/plugin/8097-graphql/) は、GraphQL を使用する際の体験を大幅に向上させるものです: -- syntax highlighting -- autocomplete suggestions -- validation against schema +- 構文の強調表示 +- オートコンプリートの提案 +- スキーマに対する検証 - snippets -More information on this [WebStorm article](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/) that showcases all the plugin's main features. - -
- -### TypeScript types generation - -Finally, the best GraphQL experience is reached when the TypeScript data types are generated from the defined GraphQL queries, as follows: - -```tsx -import { execute } from 'your-favorite-graphql-client' -import { GetTokenQuery } from './generated.' - -const id = params.id -const query = ` -query GetToken($id: ID!) { - token(id: $id) { - id - owner - } -} -` - -const result: GetTokenQuery = await execute(query, { - variables: { - id, - }, -}) - -// `result` is typed! -``` - -Such a setup can be easily achieved by installing and configuring [GraphQL Code Generator](https://www.graphql-code-generator.com/docs/getting-started) as follows: - -```bash -yarn add graphql @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations -``` - -Then update your `package.json` (or similar script configuration setup) as follows: - -```tsx -{ - // ... - "scripts": { - // ... - "generate": "graphql-codegen", - // ... - } - // ... -} -``` - -Add the following configuration file to your project: - -```tsx -schema: "" -documents: './src/**/*.ts' -generates: - ./generated.ts: - plugins: - - typescript - - typescript-operations -``` - -Finally, by simply running the configured script (`yarn generate`), GraphQL Code Generator will generate the proper TypeScript types in the `generated.ts` file: - -- Each query will get a corresponding `[QueryName]Query` type (ex: `GetToken` → `GetTokenQuery` type -- Each fragment will get a corresponding `[FragmentName]Fragment` type (ex: `DelegateItem` → `DelegateItemFragment` type +詳細は、この[WebStorm の記事](https://blog.jetbrains.com/webstorm/2019/04/featured-plugin-js-graphql/)で、プラグインの主な機能をすべて紹介しています。 diff --git a/website/pages/ja/querying/querying-the-hosted-service.mdx b/website/pages/ja/querying/querying-the-hosted-service.mdx index 3c9cff855dd9..f21fb25ae19e 100644 --- a/website/pages/ja/querying/querying-the-hosted-service.mdx +++ b/website/pages/ja/querying/querying-the-hosted-service.mdx @@ -1,5 +1,5 @@ --- -title: ホステッドサービスのクエリ +title: ホスティングサービスのクエリ --- サブグラフがデプロイされた状態で、[Graph Explorer](https://thegraph.com/hosted-service/)にアクセスすると、[GraphiQL](https://github.com/graphql/graphiql)インターフェースが表示され、サブグラフにデプロイされた GraphQL API を探索して、クエリを発行したり、スキーマを表示したりすることができます。 @@ -8,7 +8,7 @@ title: ホステッドサービスのクエリ #### 例 -このクエリは、マッピングが作成したすべてのカウンターを一覧表示します。 作成するのは 1 つだけなので、結果には 1 つの`デフォルトカウンター +このクエリは、マッピングによって作成されたすべてのカウンターを一覧表示します。 1 つしか作成しないため、結果には 1 つの `default-counter` のみが含まれます。 ```graphql { diff --git a/website/pages/ja/release-notes/assemblyscript-migration-guide.mdx b/website/pages/ja/release-notes/assemblyscript-migration-guide.mdx index 2e78fa232b69..bec5abd80ef4 100644 --- a/website/pages/ja/release-notes/assemblyscript-migration-guide.mdx +++ b/website/pages/ja/release-notes/assemblyscript-migration-guide.mdx @@ -77,7 +77,7 @@ npm install --save @graphprotocol/graph-ts@latest ## 変更点 -### Nullability +### ヌル可能性 古いバージョンの AssemblyScript では、以下のようなコードを作ることができました: @@ -151,9 +151,9 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i if (decimals === null) { ``` -これは、==ではなく!=の場合も同様です。 +== の代わりに != を実行している場合も同様です。 -### キャスト +### 鋳造 以前の一般的なキャストの方法は、次のように`as`キーワードを使うだけでした。 @@ -238,7 +238,7 @@ if (previousBalance != null) { let newBalance = new AccountBalance(balanceId) ``` -Nullability については、[nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks)を利用することをお勧めします。 +Nullability については、[nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks)を利用することをお勧めします。それはあなたのコードをよりきれいにします 🙂 また、キャストを容易にするために、いくつかの型にスタティックメソッドを追加しました。 @@ -306,7 +306,7 @@ let somethingOrElse: string = data :) ### プロパティアクセスによるオペレーターオーバーロード -アセンブリスクリプトのコンパイラは、値の片方が nullable であることを警告するコンパイル時のエラーを出さずに、ただ黙ってコンパイルするので、実行時にコードが壊れる可能性があります。 +たとえば、(プロパティ アクセスからの) null 許容型と null 非許容型を合計しようとすると、AssemblyScript コンパイラは、値の 1 つが null 許容であるというコンパイル時のエラー警告を表示する代わりに、黙ってコンパイルします。実行時にコードが壊れる可能性を与えます。 ```typescript class BigInt extends Uint8Array { @@ -394,7 +394,7 @@ if (total === null) { total.tokens = total.tokens + BigInt.fromI32(1) ``` -あるいは、このプロパティに nullable 型を使用しないように GraphQL スキーマを変更することもできます。そうすれば、`コード生成`の段階でゼロとして初期化されます。 +あるいは、このプロパティに nullable 型を使用しないように GraphQL スキーマを変更することもできます。そうすれば、`コード生成`の段階でゼロとして初期化されます。😉 ```graphql type Total @entity { @@ -520,5 +520,5 @@ type MyEntity @entity { - Classes initialized from object literals can no longer define a constructor ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) - The result of a `**` binary operation is now the common denominator integer if both operands are integers. Previously, the result was a float as if calling `Math/f.pow` ([v0.11.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.11.0)) - Coerce `NaN` to `false` when casting to `bool` ([v0.14.9](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.9)) -- When shifting a small integer value of type `i8`/`u8` or `i16`/`u16`, only the 3 respectively 4 least significant bits of the RHS value affect the result, analogous to the result of an `i32.shl` only being affected by the 5 least significant bits of the RHS value. Example: `someI8 << 8` previously produced the value `0`, but now produces `someI8` due to masking the RHS as `8 & 7 = 0` (3 bits) ([v0.17.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.0)) +- タイプ `i8`/`u8` または `i16`/`u16` の小さな整数値をシフトする場合、最小の 3 つ、それぞれ 4 つだけ RHS 値の上位 5 ビットのみが影響を受ける `i32.shl` の結果と同様に、RHS 値の有効ビットが結果に影響します。例: `someI8 << 8` は以前は値 `0` を生成していましたが、RHS を `8 & 7 = 0` としてマスクするため、`someI8` を生成するようになりました。(3 ビット) ([v0.17.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.0)) - Bug fix of relational string comparisons when sizes differ ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) diff --git a/website/pages/ko/cookbook/cosmos.mdx b/website/pages/ko/cookbook/cosmos.mdx deleted file mode 120000 index 66acfa28a317..000000000000 --- a/website/pages/ko/cookbook/cosmos.mdx +++ /dev/null @@ -1 +0,0 @@ -../../en/cookbook/cosmos.mdx \ No newline at end of file diff --git a/website/pages/ru/cookbook/arweave.mdx b/website/pages/ru/cookbook/arweave.mdx index 806006eb0c8b..775b015d2868 100644 --- a/website/pages/ru/cookbook/arweave.mdx +++ b/website/pages/ru/cookbook/arweave.mdx @@ -1,5 +1,5 @@ --- -title: Создание сабграфов на Arweave +title: Создание Субграфов на Arweave --- > Airweave поддерживается в Graph Node и на размещенном в режиме в бета-версии: пожалуйста, свяжитесь с нами в [Discord](https://discord.gg/rC8rBuRtbH) по любым вопросам о построении сабграфов на Arweave! diff --git a/website/pages/ru/cookbook/base-testnet.mdx b/website/pages/ru/cookbook/base-testnet.mdx new file mode 100644 index 000000000000..ae49fa88d92a --- /dev/null +++ b/website/pages/ru/cookbook/base-testnet.mdx @@ -0,0 +1,110 @@ +--- +title: Создание сабграфов на Base +--- + +Это руководство быстро познакомит вас с тем, как инициализировать, создать и развернуть ваш сабграф в тестовой сети Base. + +Вам понадобятся: + +- Адрес контракта сети Base +- Крипто-кошелек (например, MetaMask или Coinbase Wallet) + +## Subgraph Studio + +### 1. Установка the Graph CLI + +The Graph CLI (>=v0.41.0) написан на JavaScript, и для его использования вам потребуется установить либо `npm`, либо `yarn`. + +```sh +# NPM +npm install -g @graphprotocol/graph-cli + +# Yarn +yarn global add @graphprotocol/graph-cli +``` + +### 2. Создание сабграфа в Subgraph Studio + +Перейдите на [Subgraph Studio](https://thegraph.com/studio/) и подключите ваш крипто-кошелек. + +После подключения, нажмите "Create a Subgraph" и введите имя вашего сабграфа. + +Выберите "Base (testnet)" в качестве индексируемого блокчейна и нажмите "Создать Сабграф". + +### 3. Инициализация вашего Сабграфа + +> Вы можете найти конкретные команды для вашего сабграфа в Subgraph Studio. + +Убедитесь, что graph-cli обновлен до последней версии (выше 0.41.0) + +```sh +graph --version +``` + +Инициализируйте свой подграф из существующего контракта. + +```sh +graph init --studio +``` + +Ваш сабграф slug - это идентификатор для вашего сабграфа. Инструмент CLI проведет вас по шагам создания сабграфа, включая: + +- Протокол: ethereum +- Сабграф slug: `` +- Каталог для создания сабграфа в: `` +- Сеть Ethereum: base-testnet \_ Contract address: `` +- Стартовый блок (необязательно) +- Имя контракта: `` +- Да / нет для событий индексации (да означает, что ваш сабграф будет загружен объектами в схеме и простыми сопоставлениями для отправленных событий) + +### 3. Создание вашего Подграфа + +> Если исходящие события - это единственное, что вы хотите проиндексировать, то никакой дополнительной работы не требуется, и вы можете перейти к следующему шагу. + +Предыдущая команда создает сабграф scaffold, который вы можете использовать в качестве отправной точки для построения вашего сабграфа. При внесении изменений в сабграф вы будете в основном работать с тремя файлами: + +- Манифест (subgraph.yaml) - Манифест определяет, какие источники данных будут индексироваться вашими сабграфами. Обязательно добавьте `base-testnet` в качестве имени сети в файле манифеста, чтобы развернуть свой сабграф в базовой тестовой сети. +- Схема (schema.graphql) - Схема GraphQL определяет, какие данные вы хотите извлечь из подграфа. +- Сопоставления сценариев сборки (mapping.ts) - это код, который преобразует данные из ваших источников данных в объекты, определенные в схеме. + +Если вы хотите проиндексировать дополнительные данные, вам нужно будет расширить манифест, схему и сопоставления. + +Для получения дополнительной информации о том, как написать свой сабграф, см. [Создание сабграфа](/developing/creating-a-subgraph). + +### 4. Развертывание в Subgraph Studio + +Прежде чем вы сможете развернуть свой сабграф, вам необходимо будет пройти аутентификацию в Subgraph Studio. Вы можете сделать это, выполнив следующую команду: + +Аутентифицируйте сабграф в studio + +``` +graph auth --studio +``` + +Затем войдите в свой каталог сабграфов. + +``` + cd +``` + +Создайте свой сабграф с помощью следующей команды: + +```` +``` +graph codegen && graph build +``` +```` + +Наконец, вы можете развернуть свой сабграф с помощью этой команды: + +``` +graph deploy --studio +``` + +### 5. Запросите свой сабграф + +Как только ваш сабграф будет развернут, вы можете запросить его из своего приложения, используя "URL запроса разработки" в Subgraph Studio. + +Примечание - Скорость работы Studio API ограничена. Следовательно, предпочтительно использовать для разработки и тестирования. + +Чтобы узнать больше о запросе данных из вашего сабграфа, смотрите страницу [Запрос сабграфа](/querying/querying-the-graph). diff --git a/website/pages/ru/deploying/deploying-a-subgraph-to-studio.mdx b/website/pages/ru/deploying/deploying-a-subgraph-to-studio.mdx new file mode 100644 index 000000000000..05d9acdd1f0a --- /dev/null +++ b/website/pages/ru/deploying/deploying-a-subgraph-to-studio.mdx @@ -0,0 +1,70 @@ +--- +title: Развертывание сабграфа в Subgraph Studio +--- + +> Убедитесь, что сеть, из которой Ваш сабграф индексирует данные, [поддерживается](/developing/supported-chains) в децентрализованной сети. + +Вот шаги для развертывания Вашего сабграфа в Subgraph Studio: + +- Установите The Graph CLI (либо с помощью yarn, либо с npm) +- Создайте свой сабграф в Subgraph Studio +- Аутентифицируйте свою учетную запись с помощью CLI +- Развертывание сабграфа в Subgraph Studio + +## Установка Graph CLI + +Мы используем тот же CLI для развертывания сабграфов в нашем [размещенный сервис](https://thegraph.com/hosted-service/) и к [Subgraph Studio](https://thegraph.com/studio/).. Вот команды для установки graph-cli. Это можно сделать с помощью npm или yarn. + +**Установка с помощью yarn:** + +```bash +yarn global add @graphprotocol/graph-cli +``` + +**Установка с помозью npm:** + +```bash +npm install -g @graphprotocol/graph-cli +``` + +## Создайте ваш сабграф в Subgraph Studio + +Перед развертыванием вашего фактического сабграфа вам необходимо создать сабграф в [Subgraph Studio](https://thegraph.com/studio/). Мы рекомендуем вам ознакомиться с нашей [документацией Studio](/deploying/subgraph-studio), чтобы узнать больше об этом. + +## Инициализация вашего сабграфа + +Как только ваш сабграф будет создан в Subgraph Studio, вы можете инициализировать код сабграфа с помощью этой команды: + +```bash +graph init --studio +``` + +Значение `` можно найти на странице сведений о вашем сабграфе в Subgraph Studio: + +![Subgraph Studio - Slug](/img/doc-subgraph-slug.png) + +После запуска `graph init` вам будет предложено ввести адрес контракта, сеть и ABI, которые вы хотите запросить. Выполнение этого приведет к созданию новой папки на вашем локальном компьютере с некоторым базовым кодом для начала работы над вашим сабграфом. Затем вы можете доработать свой сабграф, чтобы убедиться, что он работает должным образом. + +## Аутентификация в Graph + +Прежде чем вы сможете развернуть свой сабграф в Subgraph Studio, вам необходимо войти в свою учетную запись в CLI. Для этого вам понадобится ваш ключ развертывания, который вы можете найти на своей странице "My Subgraphs" или на странице сведений о вашем сабграфе. + +Вот команда, которую вам нужно использовать для аутентификации из CLI: + +```bash +graph auth --studio +``` + +## Развертывание сабграфа в Subgraph Studio + +Как только вы будете готовы, вы можете развернуть свой сабграф в Subgraph Studio. Это не приведет к публикации вашего сабграфа в децентрализованной сети, а только к его развертыванию в вашей учетной записи Studio, где вы сможете протестировать его и обновить метаданные. + +Вот команда CLI, которую вам нужно использовать для развертывания вашего сабграфа. + +```bash +graph deploy --studio +``` + +После выполнения этой команды CLI запросит метку версии, вы можете назвать ее так, как хотите, вы можете использовать такие метки, как `0.1` и `0.2` или также использовать буквы, такие как `uniswap-v2-0.1`. Эти метки будут видны в Graph Explorer и могут быть использованы кураторами, чтобы решить, хотят ли они показывать эту версию или нет, поэтому выбирайте их с умом. + +После развертывания вы можете протестировать свой сабграф в Subgraph Studio с помощью playground, при необходимости развернуть другую версию, обновить метаданные и, когда будете готовы, опубликовать свой сабграф в Graph Explorer. diff --git a/website/pages/ru/querying/distributed-systems.mdx b/website/pages/ru/querying/distributed-systems.mdx new file mode 100644 index 000000000000..5e1639be8f83 --- /dev/null +++ b/website/pages/ru/querying/distributed-systems.mdx @@ -0,0 +1,134 @@ +--- +title: Распределенные системы +--- + +The Graph - это протокол, реализованный в виде распределенной системы. + +Соединения терпят неудачу. Запросы поступают не по порядку. Разные компьютеры с несинхронизированными часами и состояниями обрабатывают связанные запросы. Серверы перезапускаются. Реорганизации происходят между запросами. Эти проблемы присущи всем распределенным системам, но усугубляются в системах, работающих в глобальном масштабе. + +Рассмотрим этот пример того, что может произойти, если клиент запрашивает у Индексатора последние данные во время реорганизации. + +1. Индексатор обрабатывает блок 8 +2. Запрос, отправленный клиенту для блока 8 +3. Индексатор обрабатывает блок 9 +4. Индексатор обрабатывает блок 10A +5. Запрос, отправленный клиенту для блока 10A +6. Индексатор обнаруживает реорганизацию на 10B и откатывается на 10A +7. Запрос, отправленный клиенту для блока 9 +8. Индексатор обрабатывает блок 10B +9. Индексатор обрабатывает блок 11 +10. Запрос, отправленный клиенту для блока 11 + +С точки зрения Индексатора, все логично продвигается вперед. Время движется вперед, хотя нам и пришлось откатить незавершенный блок и воспроизвести консенсусный блок поверх него. Попутно индексатор обслуживает запросы, используя последнее состояние, о котором ему известно на данный момент. + +Однако с точки зрения клиента все выглядит хаотично. Клиент замечает, что ответы были для блоков 8, 10, 9 и 11 в таком порядке. Мы называем это проблемой "колебания блока". Когда клиент испытывает колебания блока, со временем может показаться, что данные противоречат сами себе. Ситуация ухудшается, если учесть, что не все Индексаторы принимают последние блоки одновременно, и ваши запросы могут быть перенаправлены нескольким Индексаторам. + +Клиент и сервер несут ответственность за совместную работу по предоставлению пользователю согласованных данных. Необходимо использовать различные подходы в зависимости от желаемой согласованности, поскольку не существует единой правильной программы для каждой проблемы. + +Рассуждать о последствиях распределенных систем сложно, но исправления может и не быть! Мы создали API и шаблоны, чтобы помочь вам ориентироваться в некоторых распространенных вариантах использования. Следующие примеры иллюстрируют эти шаблоны, но по-прежнему исключают детали, требуемые производственным кодом (например, обработку ошибок и отмену), чтобы не запутывать основные идеи. + +## Опрос для получения обновленных данных + +The Graph предоставляет API `block: { number_gte: $minBlock }`, который гарантирует, что ответ для одного блока равен или выше `$minBlock`. Если запрос сделан к экземпляру `graph-node`, а основной блок еще не синхронизирован, `graph-node` покажет ошибку. Если `graph-node` синхронизировал минимальный блок, он запустит ответ для последнего блока. Если запрос сделан к краю & Node Gateway, шлюз отфильтрует всех Индексаторов, которые еще не синхронизировали минимальный блок, и отправит запрос на последний блок, синхронизированный Индексатором. + +Мы можем использовать `number_gte`, чтобы гарантировать, что время никогда не движется вспять при опросе данных в цикле. Вот пример: + +```javascript +/// Updates the protocol.paused variable to the latest +/// known value in a loop by fetching it using The Graph. +async function updateProtocolPaused() { + // It's ok to start with minBlock at 0. The query will be served + // using the latest block available. Setting minBlock to 0 is the + // same as leaving out that argument. + let minBlock = 0 + + for (;;) { + // Schedule a promise that will be ready once + // the next Ethereum block will likely be available. + const nextBlock = new Promise((f) => { + setTimeout(f, 14000) + }) + + const query = ` + query GetProtocol($minBlock: Int!) { + protocol(block: { number_gte: $minBlock } id: "0") { + paused + } + _meta { + block { + number + } + } + }` + + const variables = { minBlock } + const response = await graphql(query, variables) + minBlock = response._meta.block.number + + // TODO: Do something with the response data here instead of logging it. + console.log(response.protocol.paused) + + // Sleep to wait for the next block + await nextBlock + } +} +``` + +## Выборка набора связанных элементов + +Другим вариантом использования является извлечение большого набора или, в более общем плане, извлечение связанных элементов по нескольким запросам. В отличие от случая опроса (где желаемая согласованность заключалась в продвижении вперед во времени), желаемая согласованность относится к одному моменту времени. + +Здесь мы будем использовать аргумент `block: { hash: $blockHash }`, чтобы привязать все наши результаты к одному и тому же блоку. + +```javascript +/// Gets a list of domain names from a single block using pagination +async function getDomainNames() { + // Set a cap on the maximum number of items to pull. + let pages = 5 + const perPage = 1000 + + // The first query will get the first page of results and also get the block + // hash so that the remainder of the queries are consistent with the first. + const listDomainsQuery = ` + query ListDomains($perPage: Int!) { + domains(first: $perPage) { + name + id + } + _meta { + block { + hash + } + } + }` + + let data = await graphql(listDomainsQuery, { perPage }) + let result = data.domains.map((d) => d.name) + let blockHash = data._meta.block.hash + + let query + // Continue fetching additional pages until either we run into the limit of + // 5 pages total (specified above) or we know we have reached the last page + // because the page has fewer entities than a full page. + while (data.domains.length == perPage && --pages) { + let lastID = data.domains[data.domains.length - 1].id + query = ` + query ListDomains($perPage: Int!, $lastID: ID!, $blockHash: Bytes!) { + domains(first: $perPage, where: { id_gt: $lastID }, block: { hash: $blockHash }) { + name + id + } + }` + + data = await graphql(query, { perPage, lastID, blockHash }) + + // Accumulate domain names into the result + for (domain of data.domains) { + result.push(domain.name) + } + } + return result +} +``` + +Обратите внимание, что в случае реорганизации клиент должен будет повторить попытку с первого запроса, чтобы обновить хэш блока до необработанного блока. diff --git a/website/pages/uk/global.json b/website/pages/uk/global.json index b053e3a3a086..5a9a1e01dabc 100644 --- a/website/pages/uk/global.json +++ b/website/pages/uk/global.json @@ -1,7 +1,7 @@ { "navigation": { "theGraphNetwork": "Graph мережа", - "subgraphs": "Субграфи", + "subgraphs": "Підграфи", "developing": "Розробка", "deploying": "Запуск", "publishing": "Публікація", diff --git a/website/pages/uk/network/curating.mdx b/website/pages/uk/network/curating.mdx index 47652a280b5d..f3380af13f96 100644 --- a/website/pages/uk/network/curating.mdx +++ b/website/pages/uk/network/curating.mdx @@ -2,15 +2,15 @@ title: Кураторство --- -Куратори мають вирішальне значення для децентралізованої економіки Graph. Вони використовують свої знання екосистеми web3 для оцінки та сигналізування про субграфи, які повинні бути проіндексовані мережею Graph. За допомогою експлорера куратори можуть переглядати дані мережі для прийняття відповідних рішень. The Graph Network нагороджує кураторів, які повідомляють про якісні субграфи, відсотком від комісії за запити, які генеруються субграфами. Куратори економічно зацікавлені у своєчасному поданні сигналів. Ці сигнали від кураторів важливі для індексаторів, адже потім індексатори можуть обробляти або індексувати дані з позначених субграфів. +Куратори мають вирішальне значення для децентралізованої економіки Graph. Вони використовують свої знання екосистеми web3 для оцінки та сигналізування про підграфів, які повинні бути проіндексовані мережею Graph. За допомогою експлорера куратори можуть переглядати дані мережі для прийняття відповідних рішень. The Graph Network нагороджує кураторів, які повідомляють про якісні підграфи, відсотком від комісії за запити, які генеруються підграфами. Куратори економічно зацікавлені у своєчасному поданні сигналів. Ці сигнали від кураторів важливі для індексаторів, адже потім індексатори можуть обробляти або індексувати дані з позначених субграфів. -При сигналізації куратори можуть прийняти рішення повідомляти про конкретну версію субграфа або повідомляти за допомогою автоміграції. При сигналізації за допомогою автоміграції частки куратора завжди будуть оновлені до останньої версії, опублікованої розробником. Якщо ви вирішите замість цього сигналізувати про конкретну версію, частки будуть залишатися відповідно до конкретної версії. +При сигналізації куратори можуть прийняти рішення повідомляти про конкретну версію підграфа або повідомляти за допомогою автоміграції. При сигналізації за допомогою автоміграції частки куратора завжди будуть оновлені до останньої версії, опублікованої розробником. Якщо ви вирішите замість цього сигналізувати про конкретну версію, частки будуть залишатися відповідно до конкретної версії. -Пам'ятайте, що кураторство є ризикованою справою. Будь ласка, зробіть все можливе, щоб переконатися, що ви займаєтеся кураторством тих субграфів, яким ви довіряєте. Створення субграфів не вимагає дозволу, тому люди можуть створювати субграфи та називати їх будь-якими іменами, які їм подобаються. Щоб дізнатися більше про ризики, пов'язані з кураторством, перегляньте [Видання від Graph Academy.](https://thegraph.academy/curators/) +Пам'ятайте, що кураторство є ризикованою справою. Будь ласка, зробіть все можливе, щоб переконатися, що ви займаєтеся кураторством тих підграфів, яким ви довіряєте. Створення підграфів не вимагає дозволу, тому люди можуть створювати підграфи та називати їх будь-якими іменами, які їм подобаються. Щоб дізнатися більше про ризики, пов'язані з кураторством, перегляньте [Видання від Graph Academy.](https://thegraph.academy/curators/) ## Крива зв'язування 101 -Спочатку зробимо крок назад. Кожен субграф має криву зв'язування, на якій мінтяться кураторські частки, коли користувач додає сигнал **на** криву. Крива зв'язування кожного субграфа є унікальною. Криві зв'язування побудовані таким чином, що ціна мінту кураторської частки на субграфі зростає лінійно, в залежності від кількості випущених часток. +Спочатку зробимо крок назад. Кожен підграф має криву зв'язування, на якій мінтяться кураторські частки, коли користувач додає сигнал **на** криву. Крива зв'язування кожного підграфа є унікальною. Криві зв'язування побудовані таким чином, що ціна мінту кураторської частки на підграфі зростає лінійно, в залежності від кількості випущених часток. ![Ціна за частку](/img/price-per-share.png) @@ -18,78 +18,78 @@ title: Кураторство ![Крива зв'язування](/img/bonding-curve.png) -Уявімо, що у нас є два куратори, які мінтять частки для субграфа: +Уявімо, що у нас є два куратори, які мінтять частки для підграфа: -- Куратор А першим подає сигнал на субграф. Додавши до кривої 120 000 GRT, вони можуть змінтити 2000 штук. -- Сигнал куратора Б з'являється на субграфі через деякий час після цього. Щоб отримати таку саму кількість часток, як і куратор А, він мав би додати до кривої 360 000 GRT. +- Куратор А першим подає сигнал на підграфа. Додавши до кривої 120 000 GRT, вони можуть змінтити 2000 штук. +- Сигнал куратора Б з'являється на підграфі через деякий час після цього. Щоб отримати таку саму кількість часток, як і куратор А, він мав би додати до кривої 360 000 GRT. - Оскільки обидва куратори володіють половиною загальної кількості кураторських часток, вони отримають рівну суму винагороди за кураторство. - Якби хтось із кураторів зараз спалив свої 2000 кураторських часток, то отримав би 360 000 GRT. -- Куратор, що залишився, тепер отримає всю кураторську винагороду за цей субграф. Якби вони продали свої частки, щоб вивести GRT, вони б отримали лише 120 000 GRT. -- **TLDR:** Оцінка кількості GRT кураторських часток визначається кривою зв'язування і може бути волатильною. Існує потенціал для зазнання значних втрат. Сигналізація на ранній стадії означає, що ви вкладаєте менше GRT на кожну частку. Це означає, що ви заробляєте більше винагороди, як куратор за кожний GRT токен, ніж пізніші куратори за один і той самий субграф. +- Куратор, що залишився, тепер отримає всю кураторську винагороду за цей підграф. Якби вони продали свої частки, щоб вивести GRT, вони б отримали лише 120 000 GRT. +- **TLDR:** Оцінка кількості GRT кураторських часток визначається кривою зв'язування і може бути волатильною. Існує потенціал для зазнання значних втрат. Сигналізація на ранній стадії означає, що ви вкладаєте менше GRT на кожну частку. Це означає, що ви заробляєте більше винагороди, як куратор за кожний GRT токен, ніж пізніші куратори за один і той самий підграф. -Загалом, крива зв'язування — це математична крива, яка визначає взаємозв'язок між пропозицією токенів і ціною активу. У конкретному випадку курації субграфа **ціна кожної частки субграфа збільшується з кожним інвестованим токеном**, натомість **ціна кожної частки зменшується з кожним проданим токеном.** +Загалом, крива зв'язування — це математична крива, яка визначає взаємозв'язок між пропозицією токенів і ціною активу. У конкретному випадку курації підграфа **ціна кожної частки підграфа збільшується з кожним інвестованим токеном**, натомість **ціна кожної частки зменшується з кожним проданим токеном.** У випадку з Graph, застосовується, [впроваджена Bancor](https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA), формула кривої зв'язування. ## Як сигналізувати -Тепер, коли ми розглянули основи того, як працює крива зв'язування, ось як ви будете подавати сигнали на субграфи. На вкладці "Куратор" в Graph експлорері куратори зможуть подавати та скасовувати сигнали на певних субграфах на основі статистичних даних всередині мережі. Для покрокового огляду того, як це зробити в експлорері, [натискайте тут.](/network/explorer) +Тепер, коли ми розглянули основи того, як працює крива зв'язування, ось як ви будете подавати сигнали на підграфи. На вкладці "Куратор" в Graph експлорері куратори зможуть подавати та скасовувати сигнали на певних підграфах на основі статистичних даних всередині мережі. Для покрокового огляду того, як це зробити в експлорері, [натискайте тут.](/network/explorer) -Куратор може обрати подання сигналу на певну версію субграфа, або ж він може обрати автоматичне перенесення сигналу на найновішу версію цього субграфа. Обидва варіанти є прийнятними і мають свої плюси та мінуси. +Куратор може обрати подання сигналу на певну версію підграфа, або ж він може обрати автоматичне перенесення сигналу на найновішу версію цього підграфа. Обидва варіанти є прийнятними та мають свої плюси та мінуси. -Подача сигналу на конкретну версію, є особливо корисною функцією, коли один субграф використовують декілька dApps. Одному dApp може знадобитися регулярно оновлювати субграф новими функціями. Інший dApp може віддати перевагу використанню старої, добре перевіреної версії субграфа. При первинній курації стягується стандартний відсоток у розмірі 1%. +Подача сигналу на конкретну версію, є особливо корисною функцією, коли один підграф використовує декілька dApps. Одному dApp може знадобитися регулярно оновлювати підграф новими функціями. Інший dApp може віддати перевагу використанню старої, добре перевіреної версії підграфа. При первинній курації стягується стандартний відсоток у розмірі 1%. Автоматичне переміщення вашого сигналу на найновішу версію може бути корисним для того, щоб ви продовжували нараховувати комісію за запити. Кожного разу, коли ви здійснюєте кураторську роботу, стягується плата за в розмірі 1%. Ви також сплачуєте 0,5% за кураторство, за кожну міграцію. Розробникам підграфів не рекомендується часто публікувати нові версії - вони повинні сплачувати 0.5% кураторам за всі автоматично переміщені частки кураторів. -> **Примітка:** Перша адреса, яка подала сигнал на певний субграф, вважається першим куратором і йому доведеться здійснити набагато більше витрат на газ, ніж іншим наступним кураторам, оскільки перший куратор ініціалізує токени частки кураторства, ініціалізує криву зв'язування, а також передає токени в Graph proxy. +> **Примітка:** Перша адреса, яка подала сигнал на певний підграф, вважається першим куратором і йому доведеться здійснити набагато більше витрат на газ, ніж іншим наступним кураторам, оскільки перший куратор ініціалізує токени частки кураторства, ініціалізує криву зв'язування, а також передає токени в Graph proxy. ## Що означає Сигналізація для мережі Graph? -Для того, щоб кінцеві користувачі могли робити запити до субграфа, цей субграф повинен бути спочатку проіндексований. Індексування — це процес, під час якого файли, дані та метадані переглядаються, класифікуються, а потім індексуються, щоб результати можна було знайти швидше. Для того, щоб дані субграфа були придатні для пошуку, вони повинні бути впорядковані. +Для того, щоб кінцеві користувачі могли робити запити до підграфа, цей підграф повинен бути спочатку проіндексований. Індексування — це процес, під час якого файли, дані та метадані переглядаються, класифікуються, а потім індексуються, щоб результати можна було знайти швидше. Для того, щоб дані підграфа були придатні для пошуку, вони повинні бути впорядковані. -Отже, якби індексатори повинні були здогадуватися, які субграфи їм слід індексувати, була б низька ймовірність того, що вони будуть отримувати високі винагороди за запити, оскільки у них не було б способу перевірити, які субграфи є якісними. Введіть кураторство. +Отже, якби індексатори повинні були здогадуватися, які підграфи їм слід індексувати, була б низька ймовірність того, що вони будуть отримувати високі винагороди за запити, оскільки у них не було б способу перевірити, які підграфи є якісними. Введіть кураторство. -Куратори роблять мережу The Graph ефективною, а сигналізація - це процес, за допомогою якого куратори повідомляють індексаторам про те, що субграф може бути проіндексований, де GRT додається до кривої зв'язування для субграфа. Індексатори можуть довіряти сигналу від куратора, оскільки після сигналізації куратори мінтять кураторську частку для субграфа, що дає їм право на отримання частини від майбутніх комісії за запити, які генерує субграф. Сигнал куратора представлений у вигляді токенів ERC20, які називаються Graph Curation Shares (GCS). Куратори, які хочуть заробити більше комісій за запити, повинні надсилати свої GRT субграфам, які, за їхніми прогнозами, будуть генерувати сильний потік комісій в мережу. Куратори не можуть бути звільнені за погану поведінку, але існує депозитний внесок для кураторів, щоб позбавити їх стимулів до прийняття поганих рішень, які можуть зашкодити цілісності мережі. Куратори також заробляють менше комісійних за запити, якщо вони вирішили займатися низькоякісним субграфом, оскільки буде менше запитів для обробки або менше індексаторів, які будуть обробляти ці запити. Перегляньте діаграму нижче! +Куратори роблять мережу The Graph ефективною, а сигналізація - це процес, за допомогою якого куратори повідомляють індексаторам про те, що підграф може бути проіндексований, де GRT додається до кривої зв'язування для підграфа. Індексатори можуть довіряти сигналу від куратора, оскільки після сигналізації куратори мінтять кураторську частку для підграфа, що дає їм право на отримання частини від майбутніх комісії за запити, які генерує підграф. Сигнал куратора представлений у вигляді токенів ERC20, які називаються Graph Curation Shares (GCS). Куратори, які хочуть заробити більше комісій за запити, повинні надсилати свої GRT підграфам, які, за їхніми прогнозами, будуть генерувати сильний потік комісій в мережу. Куратори не можуть бути звільнені за погану поведінку, але існує депозитний внесок для кураторів, щоб позбавити їх стимулів до прийняття поганих рішень, які можуть зашкодити цілісності мережі. Куратори також заробляють менше комісійних за запити, якщо вони вирішили займатися низькоякісним підграфом, оскільки буде менше запитів для обробки або менше індексаторів, які будуть обробляти ці запити. Перегляньте діаграму нижче! ![Схема сигналізації](/img/curator-signaling.png) -Індексатори можуть знаходити субграфи для індексування на основі сигналів від кураторів, які вони бачать в Graph експлорері (знімок з екрана нижче). +Індексатори можуть знаходити підграфи для індексування на основі сигналів від кураторів, які вони бачать в Graph експлорері (знімок з екрана нижче). -![Дослідження субграфів](/img/explorer-subgraphs.png) +![Дослідження підграфів](/img/explorer-subgraphs.png) ## Ризики 1. Ринок запитів за своєю суттю молодий в Graph, і існує ризик того, що ваш %APY може бути нижчим, ніж ви очікуєте, через динаміку ринку, що зароджується. -2. Кураторська комісія - коли куратор сигналізує внесенням GRT токенів на субграф, він сплачує 1% кураторського внеску. Цей збір спалюється, а решта вноситься до резервного запасу кривої зв'язування. -3. Коли куратори спалюють свої частки, щоб отримати токени GRT, вартість GRT часток, що залишились, буде зменшеною. Майте на увазі, що в деяких випадках куратори можуть вирішити спалити свої частки **усі відразу**. Така ситуація може бути поширеною, якщо розробник dApp припиняє оновлювати версії, проваджувати покращення, тим самим провокує зменшення кількості запитів з субграфу або якщо субграф виходить з ладу. В результаті, куратори, що залишилися, можуть мати можливість зняти лише частину свого початкового GRT. Для отримання інформації про роль в мережі з меншим рівнем ризику див. розділ [Делегати](/network/delegating). -4. Субграф може не працювати через різноманітні помилки (баги). Субграф, що не працює не стягує комісію за запити. В результаті вам доведеться почекати, поки розробник виправить усі помилки й випустить нову версію. - - Якщо ви підключені до найновішої версії субграфу, ваші частки будуть автоматично перенесені до цієї нової версії. При цьому буде стягуватися податок на в розмірі 0,5%. - - Якщо ви подали сигнал на певну версію субграфа, а він не спрацював, вам доведеться власноруч спалювати свої частки. Зверніть увагу, що ви можете отримати більше або менше GRT, ніж ви початково внесли в криву, що є ризиком, пов'язаним з тим, що ви є куратором. Потім ви можете подати сигнал вже на нову версію субграфа, таким чином зазнавши 1% комісії, згідно з кураторською роботою. +2. Кураторська комісія - коли куратор сигналізує внесенням GRT токенів на підграф, він сплачує 1% кураторського внеску. Цей збір спалюється, а решта вноситься до резервного запасу кривої зв'язування. +3. Коли куратори спалюють свої частки, щоб отримати токени GRT, вартість GRT часток, що залишились, буде зменшеною. Майте на увазі, що в деяких випадках куратори можуть вирішити спалити свої частки **усі відразу**. Така ситуація може бути поширеною, якщо розробник dApp припиняє оновлювати версії, проваджувати покращення, тим самим провокує зменшення кількості запитів з підграфа або якщо підграф виходить з ладу. В результаті, куратори, що залишилися, можуть мати можливість зняти лише частину свого початкового GRT. Для отримання інформації про роль в мережі з меншим рівнем ризику див. розділ [Делегати](/network/delegating). +4. Підграф може не працювати через різноманітні помилки (баги). Підграф, що не працює не стягує комісію за запити. В результаті вам доведеться почекати, поки розробник виправить усі помилки й випустить нову версію. + - Якщо ви підключені до найновішої версії підграфу, ваші частки будуть автоматично перенесені до цієї нової версії. При цьому буде стягуватися податок на в розмірі 0,5%. + - Якщо ви подали сигнал на певну версію підграфа, а він не спрацював, вам доведеться власноруч спалювати свої частки. Зверніть увагу, що ви можете отримати більше або менше GRT, ніж ви початково внесли в криву, що є ризиком, пов'язаним з тим, що ви є куратором. Потім ви можете подати сигнал вже на нову версію підграфа, таким чином зазнавши 1% комісії, згідно з кураторською роботою. ## Часті запитання про кураторство ### 1. Який % від комісії за запити отримують куратори? -Подаючи сигнал на субграф, ви заробляєте частку від усіх комісій за запити, які генерує цей субграф. 10% від усіх комісії за запити отримують куратори пропорційно до їхніх часток. Ці 10% підлягають розподілу. +Подаючи сигнал на підграфа, ви заробляєте частку від усіх комісій за запити, які генерує цей підграф. 10% від усіх комісії за запити отримують куратори пропорційно до їхніх часток. Ці 10% підлягають розподілу. -### 2. Як вирішити, які субграфи є якісними для подачі сигналу? +### 2. Як вирішити, які підграфи є якісними для подачі сигналу? -Пошук найякісніших субграфів є складним завданням, але до нього можна підійти різними способами. Як куратор, ви хочете шукати надійні субграфи, які сприяють збільшенню обсягу запитів. Надійний субграф може бути цінним, якщо він є повноцінним, чітким і відповідає потребам dApp в інформації. Погано організований субграф може потребувати перегляду або повторної редакції, а також може в кінцевому підсумку виявитися неефективним. Для кураторів дуже важливо переглянути інфраструктуру або код субграфа, щоб оцінити, чи є він цінним. Як результат: +Пошук найякісніших підграфів є складним завданням, але до нього можна підійти різними способами. Як куратор, ви хочете шукати надійні підграфи, які сприяють збільшенню обсягу запитів. Надійний підграф може бути цінним, якщо він є повноцінним, чітким і відповідає потребам dApp в інформації. Погано організований підграф може потребувати перегляду або повторної редакції, а також може в кінцевому підсумку виявитися неефективним. Для кураторів дуже важливо переглянути інфраструктуру або код підграфа, щоб оцінити, чи є він цінним. Як результат: -- Куратори можуть використовувати своє бачення мережі, щоб спробувати передбачити, як окремий субграф може генерувати більший або менший обсяг запитів у майбутньому -- Куратори також повинні розбиратися в показниках, які доступні через Graph експлорер. Такі, як обсяг попередніх запитів і хто є розробником субграфа, можуть допомогти визначити, чи варто сигналізувати про нього, чи ні. +- Куратори можуть використовувати своє бачення мережі, щоб спробувати передбачити, як окремий підграф може генерувати більший або менший обсяг запитів у майбутньому +- Куратори також повинні розбиратися в показниках, які доступні через Graph Explorer. Такі, як обсяг попередніх запитів і хто є розробником підграфа, можуть допомогти визначити, чи варто сигналізувати про нього, чи ні. -### 3. Скільки коштує зміна субграфу? +### 3. Скільки коштує покращення підграфу? -При перенесенні ваших часток на нову версію субграфа стягується збір у розмірі 1%. Куратори можуть вибрати варіант підписки на найновішу версію субграфа. Коли частки будуть автоматично перенесені на нову версію, куратори також сплачуватимуть половину збору, тобто 0,5%, оскільки оновлення субграфу є мережевою операцією, яка потребує витрат на газ. +При перенесенні ваших часток на нову версію підграфа стягується збір у розмірі 1%. Куратори можуть вибрати варіант підписки на найновішу версію підграфа. Коли частки будуть автоматично перенесені на нову версію, куратори також сплачуватимуть половину збору, тобто 0,5%, оскільки оновлення підграфу є мережевою операцією, яка потребує витрат на газ. -### 4. Як часто я можу оновлювати свій субграф? +### 4. Як часто я можу оновлювати свій підграф? -Рекомендується не змінювати субграфи занадто часто. Для більш детальної інформації дивіться питання вище. +Рекомендується не змінювати підграфа занадто часто. Для більш детальної інформації дивіться питання вище. ### 5. Чи можу я продати свої частки куратора? -Частки кураторства не можуть бути "куплені" або "продані", як інші токени ERC20, з якими ви можете бути ознайомлені. Їх можна тільки мінтити (створювати) або спалювати (знищувати) уздовж кривої зв'язування для конкретного субграфа. Кількість GRT, необхідна для мінту нового сигналу, і кількість GRT, яку ви отримаєте при спалюванні наявного сигналу, визначаються цією кривою зв'язування. Як куратор, ви повинні знати, що коли ви спалюєте свої частки, щоб отримати GRT, ви можете в кінцевому підсумку отримати більше або менше GRT, ніж ви внесли початково. +Частки кураторства не можуть бути "куплені" або "продані", як інші токени ERC20, з якими ви можете бути ознайомлені. Їх можна тільки мінтити (створювати) або спалювати (знищувати) уздовж кривої зв'язування для конкретного підграфа. Кількість GRT, необхідна для мінту нового сигналу, і кількість GRT, яку ви отримаєте при спалюванні наявного сигналу, визначаються цією кривою зв'язування. Як куратор, ви повинні знати, що коли ви спалюєте свої частки, щоб отримати GRT, ви можете в кінцевому підсумку отримати більше або менше GRT, ніж ви внесли початково. Все ще спантеличені? Перегляньте нашу відео інструкцію нижче: diff --git a/website/pages/ur/arbitrum-faq.mdx b/website/pages/ur/arbitrum-faq.mdx new file mode 100644 index 000000000000..26e333523e50 --- /dev/null +++ b/website/pages/ur/arbitrum-faq.mdx @@ -0,0 +1,80 @@ +--- +title: آربٹرم اکثر پوچھے گئے سوالات +--- + +اگر آپ آربٹرم بلنگ کے اکثر پوچھے گئے سوالات پر جانا چاہتے ہیں تو [یہاں](#billing-on-arbitrum-faqs) کلک کریں. + +## عمومی سوالات + +### گراف ایک L2 حل کیوں نافذ کر رہا ہے؟ + +L2 پر گراف کو سکیل کرنے سے، نیٹ ورک کے شرکاء توقع کر سکتے ہیں: + +- گیس فیس پر 26 گنا بچت + +- تیز تر ٹرانزیکشن کی رفتار + +- ایتھریم کی طرف سے محفوظ + +پروٹوکول نیٹ ورک کے شرکاء کو گیس فیس میں کم قیمت پر زیادہ کثرت سے بات چیت کرنے کی اجازت دیتا ہے۔ یہ انڈیکسرز کو زیادہ تعداد میں سب گرافس کو انڈیکس کرنے کے قابل بناتا ہے، ڈویلپرز کو سب گرافس کو زیادہ آسانی کے ساتھ تعینات کرنے اور اپ گریڈ کرنے کی اجازت دیتا ہے، ڈیلیگیٹرز کو زیادہ سے زیادہ فریکوئنسی کے ساتھ GRT کو ڈیلیگیٹ کرنے کے قابل بناتا ہے، اور کیوریٹرز کو سب گراف کی ایک بڑی تعداد میں سگنل شامل کرنے کی صلاحیت فراہم کرتا ہے. + +گراف کمیونٹی نے گزشتہ سال آربٹرم کے ساتھ آگے بڑھنے کا [فیصلہ کیا](https://forum.thegraph.com/t/gip-0031-arbitrum-grt-bridge/3305). + +### گراف کو L2 پر استعمال کرنے کے لیے مجھے کیا کرنے کی ضرورت ہے؟ + +صارفین مندرجہ ذیل طریقوں میں سے ایک کا استعمال کرتے ہوئے اپنے GRT اور ETH کو ملاتے ہیں: + +- [آربٹرم پر گراف بریج](https://bridge.arbitrum.io/?l2ChainId=42161) +- [کی طرف بھیجنا](https://transferto.xyz/swap) +- [کونیکسٹ بریج](https://bridge.connext.network/) +- [ہاپ ایکسچینج](https://app.hop.exchange/#/send?token=ETH) + +L2 پر گراف استعمال کرنے کا فائدہ اٹھانے کے لیے، چینز کے درمیان ٹوگل کرنے کے لیے اس ڈراپ ڈاؤن سوئچر کا استعمال کریں. + +{/* ایک تصویر داخل کریں */} ![آربٹرم کو ٹوگل کرنے کے لیے ڈراپ ڈاؤن سوئچر](/img/arbitrum-screenshot-toggle.png) + +### بطور سب گراف ڈویلپر، ڈیٹا کنزیومر، انڈیکسر، کیوریٹر، یا ڈیلیگیٹر، مجھے اب کیا کرنے کی ضرورت ہے؟ + +فوری کارروائی کی ضرورت نہیں ہے. + +بنیادی ڈویلپر ٹیمیں مائیگریشن مددگار بنانے کے لیے کام کر رہی ہیں جو ڈیلیگیشن، کیوریشن، اور سب گراف کو آربٹرم میں منتقل کرنے میں نمایاں طور پر آسان بنائے گی۔ نیٹ ورک کے شرکاء اپریل 2023 میں مائیگریشن کے مددگاروں کے دستیاب ہونے کی توقع کر سکتے ہیں. + +گراف کمیونٹی فروری یا مارچ 2023 میں آربٹرم پر انڈیکسنگ انعامات کے فعال ہونے کی بھی توقع کر سکتی ہے. + +### اگر میں L2 پر نیٹ ورک میں حصہ لینا چاہتا ہوں تو مجھے کیا کرنا چاہیے؟ + +براہ کرم L2 پر [نیٹ ورک کی جانچ](https://testnet.thegraph.com/explorer) میں مدد کریں اور [ڈسکورڈ](https://discord. gg/vtvv7FP میں اپنے تجربے کے بارے میں تاثرات کی اطلاع دیں۔). + +### کیا نیٹ ورک کو L2 کرنے سے متعلق کوئی خطرہ ہے؟ + +تمام سمارٹ کنٹریکٹس کا اچھی طرح سے [آڈٹ کیا گیا ہے](https://github.com/graphprotocol/contracts/blob/dev/audits/OpenZeppelin/2022-07-graph-arbitrum-bridge-audit.pdf). + +ہر چیز کی اچھی طرح جانچ کی گئی ہے، اور ایک محفوظ اور ہموار منتقلی کو یقینی بنانے کے لیے ایک ہنگامی منصوبہ تیار کیا گیا ہے۔ تفصیلات دیکھی جا سکتی ہیں [یہاں](https://forum.thegraph.com/t/gip-0037-the-graph-arbitrum-deployment-with-linear-rewards-minted-in-l2/3551#risks-and -security-considerations-20). + +### کیا ایتھریم پر موجودہ سب گراف کام کرتے رہیں گے؟ + +جی ہاں، گراف نیٹ ورک کے کنٹریکٹس ایتھریم اور آربٹرم دونوں پر متوازی طور پر کام کریں گے جب تک کہ بعد کی تاریخ میں مکمل طور پر آربٹرم میں منتقل نہ ہو جائیں. + +### کیا GRT کے پاس آربٹرم پر ایک نیا سمارٹ کنٹریکٹ تعینات ہوگا؟ + +ہاں، GRT کے پاس ایک اضافی [آربٹرم پر سمارٹ معاہدہ ہے](https://arbiscan.io/address/0x9623063377ad1b27544c965ccd7342f7ea7e88c7)۔ تاہم، ایتھریم مینیٹ [GRT کنٹریکٹ](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) جاری رہے گا. + +## آربٹرم اکثر پوچھے گئے سوالات پر بلنگ + +### مجھے اپنے بلنگ بیلنس میں GRT کے بارے میں کیا کرنے کی ضرورت ہے? + +کچھ نہیں! آپ کے GRT کو محفوظ طریقے سے آربٹرم میں منتقل کر دیا گیا ہے اور اسے پڑھتے ہی کیوریز کی ادائیگی کے لیے استعمال کیا جا رہا ہے. + +### میں کیسے جان سکتا ہوں کہ میرے فنڈز محفوظ طریقے سے آربٹرم میں منتقل ہو گئے ہیں؟ + +تمام GRT بلنگ بیلنس پہلے ہی کامیابی کے ساتھ آربٹرم میں منتقل ہو چکے ہیں۔ آپ آربٹرم پر بلنگ کا معاہدہ [یہاں](https://arbiscan.io/address/0x1B07D3344188908Fb6DEcEac381f3eE63C48477a) دیکھ سکتے ہیں. + +### میں کیسے جان سکتا ہوں کہ آربٹرم بریج محفوظ ہے؟ + +تمام صارفین کے لیے حفاظت اور تحفظ کو یقینی بنانے کے لیے اس بریج کا [بہت زیادہ آڈٹ](https://code4rena.com/contest/2022-10-the-graph-l2-bridge-contest) کیا گیا ہے. + +### اگر میں اپنے ایتھریم مینیٹ والیٹ سے تازہ GRT شامل کر رہا ہوں تو مجھے کیا کرنے کی ضرورت ہے؟ + +اپنے آربٹرم بلنگ بیلنس میں GRT شامل کرنا [سب گراف اسٹوڈیو](https://thegraph.com/studio/) میں ایک کلک کے تجربے کے ساتھ کیا جا سکتا ہے۔ آپ آسانی سے اپنے GRT کو آربٹرم تک پہنچا سکیں گے اور ایک ٹرانزیکشن میں اپنی API کیز کو بھر سکیں گے. + +GRT شامل کرنے، واپس لینے یا حاصل کرنے کے بارے میں مزید تفصیلی ہدایات کے لیے [بلنگ صفحہ](https://thegraph.com/docs/en/billing/) دیکھیں. diff --git a/website/pages/ur/cookbook/base-testnet.mdx b/website/pages/ur/cookbook/base-testnet.mdx new file mode 100644 index 000000000000..35871a21f70f --- /dev/null +++ b/website/pages/ur/cookbook/base-testnet.mdx @@ -0,0 +1,112 @@ +--- +title: سب گرافس کو بیس پر بنانا +--- + +یہ گائیڈ آپ کو تیزی سے لے جائے گا کہ بیس ٹیسٹ نیٹ پر اپنے سب گراف کو کس طرح شروع کرنا، تخلیق کرنا اور تعینات کرنا ہے. + +آپ کو کیا ضرورت ہو گی: + +- ایک بیس ٹیسٹ نیٹ کنٹریکٹ ایڈریس +- ایک کرپٹو والیٹ (مثلاً میٹاماسک یا کوائن بیس والیٹ) + +## سب گراف اسٹوڈیو + +### ۱. گراف CLI انسٹال کریں + +گراف CLI (>=v0.41.0) جاوا اسکریپٹ میں لکہی گئ ہے اور اسے استعمال کرنے کے لیے آپ کو یا تو `npm` یا `yarn` انسٹال کرنے کی ضرورت ہوگی. + +```sh +# NPM +npm install -g @graphprotocol/graph-cli + +# Yarn +yarn global add @graphprotocol/graph-cli +``` + +### 2. اپنا سب گراف سب گراف سٹوڈیو میں بنائیں + +[سب گراف اسٹوڈیو](https://thegraph.com/studio/) پر جائیں اور اپنے کریپٹو والیٹ کو جوڑیں. + +ایک بار منسلک ہونے کے بعد، "سب گراف بنائیں" پر کلک کریں اور اپنے سب گراف کے لیے ایک نام درج کریں. + +"بیس (ٹیسٹ نیٹ)" کو بطور انڈیکس شدہ بلاکچین منتخب کریں اور سب گراف بنائیں پر کلک کریں. + +### 3. اپنا سب گراف شروع کریں + +> آپ سب گراف اسٹوڈیو میں اپنے سب گراف کے لیے مخصوص کمانڈز تلاش کر سکتے ہیں. + +یقینی بنائیں کہ گراف-cli کو تازہ ترین (0.41.0 سے اوپر) پر اپ ڈیٹ کیا گیا ہے + +```sh +گراف -- ورژن +``` + +اپنے سب گراف کو موجودہ کنٹریکٹ سے شروع کریں. + +```sh +graph init --studio +``` + +آپ کا سب گراف سلگ آپ کے سب گراف کا شناخت کنندہ ہے۔ CLI ٹول آپ کو سب گراف بنانے کے مراحل سے گزرے گا، بشمول: + +- پروٹوکول: ایتھریم +- سب گراف سلگ: `` +- سب گراف بنانے کے لیے ڈائرکٹری: `` +- ایتھریم نیٹ ورک: بیس-ٹیسٹ نیٹ \_ معاہدہ کا پتہ: `` +- اسٹارٹ بلاک (اختیاری) +- کنٹریکٹ کا نام: `` +- انڈیکسنگ کے واقعات کے لیے ہاں/نہیں (ہاں کا مطلب ہے کہ آپ کے سب گراف کو اسکیما میں موجود اداروں کے ساتھ بوٹسٹریپ کیا جائے گا اور خارج ہونے والے واقعات کے لیے سادہ نقشہ جات) + +### ۳. اپنا سب گراف لکھیں + +> اگر خارج ہونے والے واقعات صرف وہی ہیں جو آپ انڈیکس کرنا چاہتے ہیں، پھر کسی اضافی کام کی ضرورت نہیں ہے، اور آپ اگلے مرحلے پر جا سکتے ہیں. + +پچھلی کمانڈز ایک سکیفولڈ سب گراف بناتی ہیں جسے آپ اپنے سب گراف کی تعمیر کے لیے نقطہ آغاز کے طور پر استعمال کر سکتے ہیں۔ سب گراف میں تبدیلی کرتے وقت، آپ بنیادی طور پر تین فائلوں کے ساتھ کام کریں گے: + +- مینی فیسٹ (subgraph.yaml) - مینی فیسٹ اس بات کی وضاحت کرتا ہے کہ آپ کے سب گراف کس ڈیٹا سورسز کو انڈیکس کریں گے۔ بیس ٹیسٹ نیٹ پر اپنا سب گراف لگانے کے لیے مینی فیسٹ فائل میں نیٹ ورک کے نام کے طور پر `base-testnet` شامل کرنا یقینی بنائیں. +- سکیما (schema.graphql) - گراف کیو ایل سکیما اس بات کی وضاحت کرتا ہے کہ آپ سب گراف سے کون سا ڈیٹا حاصل کرنا چاہتے ہیں. +- اسمبلی اسکرپٹ میپنگ (mapping.ts) - یہ وہ کوڈ ہے جو آپ کے ڈیٹا سورس سے ڈیٹا کو اسکیما میں بیان کردہ اداروں میں ترجمہ کرتا ہے. + +اگر آپ اضافی ڈیٹا کو انڈیکس کرنا چاہتے ہیں، تو آپ کو مینی فیسٹ، اسکیما اور میپنگ میں توسیع کی ضرورت ہوگی. + +اپنا سب گراف لکھنے کے طریقے کے بارے میں مزید معلومات کے لیے، دیکھیں [سب گراف بنانا](/developing/creating-a-subgraph). + +### ۴. سب گراف سٹوڈیو پر تعینات کریں + +اس سے پہلے کہ آپ اپنا سب گراف تعینات کر سکیں، آپ کو سب گراف اسٹوڈیو سے تصدیق کرنی ہوگی۔ آپ درج ذیل کمانڈ کو چلا کر ایسا کر سکتے ہیں: + +سٹوڈیو پر سب گراف کی تصدیق کریں + +``` +graph auth --studio +``` + +اگلا، اپنے سب گراف کی ڈائرکٹری درج کریں. + +``` + cd +``` + +مندرجہ ذیل کمانڈ کے ساتھ اپنا سب گراف بنائیں: + +```` +``` +graph codegen && graph build +``` +```` + +آخر میں، آپ اس کمانڈ کا استعمال کرتے ہوئے اپنے سب گراف کو تعینات کر سکتے ہیں: + +```` +``` +graph deploy --studio +``` +```` + +### ۶. اپنے سب گراف کو کیوری کریں + +ایک بار آپ کا سب گراف تعینات ہو جانے کے بعد، آپ سب گراف اسٹوڈیو میں `ترقیاتی سوال URL` کا استعمال کرتے ہوئے اپنے ڈیپ سے استفسار کر سکتے ہیں. + +نوٹ - اسٹوڈیو API شرح محدود ہے۔ اس لیے ترجیحی طور پر ترقی اور جانچ کے لیے استعمال کیا جانا چاہیے. + +اپنے سب گراف سے کیوری کرنے والے ڈیٹا کے بارے میں مزید جاننے کے لیے، [سب گراف سے سوال کرنا](/querying/querying-the-graph) صفحہ دیکھیں. diff --git a/website/pages/ur/cookbook/migrating-a-subgraph.mdx b/website/pages/ur/cookbook/migrating-a-subgraph.mdx index 6e74fe949fa4..f916affce804 100644 --- a/website/pages/ur/cookbook/migrating-a-subgraph.mdx +++ b/website/pages/ur/cookbook/migrating-a-subgraph.mdx @@ -4,18 +4,20 @@ title: موجودہ سب گراف کو گراف نیٹورک پر منتقل ک ## تعارف -یہ آپ کے سب گراف کو ہوسٹڈ سروس سے گراف کے ڈیسینٹرالائزڈ نیٹ ورک میں منتقل کرنے کے بارے میں ایک گائیڈ ہے۔ گراف نیٹ ورک میں منتقلی Opyn، UMA، mStable، Audius، PoolTogether، Livepeer، RAI، Enzyme، DODO، Pickle اور BadgerDAO جیسے پروجیکٹس کے لیے کامیاب رہی ہے، یہ سبھی نیٹ ورک پر انڈیکسرز کے فراہم کردہ ڈیٹا پر انحصار کر رہے ہیں۔ گراف کے ڈیسینٹرالائزڈ نیٹ ورک پر اب 600 سے زیادہ سب گراف براہ راست ہیں، کیوری کی فیس پیدا کر رہے ہیں اورweb3 ڈیٹا کو فعال طور پر انڈیکس کر رہے ہیں. +یہ آپ کے سب گراف کو ہوسٹڈ سروس سے دی گراف کے ڈیسینٹرالائزڈ نیٹ ورک میں منتقل کرنے کے بارے میں ایک گائیڈ ہے۔ گراف نیٹ ورک میں منتقلی Opyn، UMA، mStable، Audius، PoolTogether، Livepeer، RAI، Enzyme، DODO، Pickle، اور BadgerDAO جیسے پروجیکٹس کے لیے کامیاب رہی ہے، یہ سبھی نیٹ ورک پر انڈیکسرز کے فراہم کردہ ڈیٹا پر انحصار کر رہے ہیں۔ دی گراف کے ڈیسینٹرالائزڈ نیٹ ورک پر اب 700 سے زیادہ سب گراف براہ راست ہیں، کیوری کی فیس پیدا کر رہے ہیں اور ویب 3 ڈیٹا کو فعال طور پر انڈیکس کر رہے ہیں. منتقلی کا عمل تیز ہوتا ہے اور آپ کا سب گراف ہمیشہ ایسے اعتبار اور کارکردگی سے فائدہ اٹہاۓ گا جو آپ کو صرف گراف نیٹورک ہی دے سکتا ہے. ### مفروضے - آپ نے پہلے ہی ھوسٹڈ سروس پر سب گراف تعینات کر دیا ہے. -- سب گراف ایتھیریم مین نیٹ کو ترتیب دے رہا ہے. +- سب گراف دی گراف نیٹ ورک پر دستیاب (یا بیٹا میں دستیاب) چین کو ترتیب دے رہا ہے. - سب گراف میں IPFS یا مکمل متن کی تلاش پر انحصار نہیں ہے (یہ ابھی تک decentralized نیٹ ورک پر مکمل طور پر تعاون یافتہ نہیں ہیں). ## موجودہ سب گراف کو گراف نیٹورک پر منتقل کرنا +> آپ اپنے سب گراف کے لیے مخصوص کمانڈز [سب گراف اسٹوڈیو](https://thegraph.com/studio/) میں تلاش کر سکتے ہیں. + 1. گراف-cli کا جدید ورژن انسٹال کریں: ```sh @@ -26,7 +28,7 @@ npm install -g @graphprotocol/graph-cli yarn global add @graphprotocol/graph-cli ``` -یہ بھی یقینی بنائیں کہ subgraph.yaml میں آپ کا `apiVersion` `0.0.5` یا اس سے زیادہ ہے. +یہ یقینی بنائیں کہ subgraph.yaml میں آپ کا `apiVersion` `0.0.5` یا اس سے زیادہ ہے. 2. سب گراف کے مرکزی پروجیکٹ کے ذخیرے کے اندر، سٹوڈیو پر تعینات اور تعمیر کرنے کے لیے سب گراف کی تصدیق کریں: @@ -67,8 +69,8 @@ graph deploy --studio 6. اس وقت، آپ کا سب گراف اب سب گراف اسٹوڈیو پر تعینات ہے، لیکن ابھی تک ڈیسینٹرالائزڈ نیٹ ورک پر شائع نہیں ہوا ہے۔ اب آپ سب گراف کی جانچ کر سکتے ہیں تاکہ یہ یقینی بنایا جا سکے کہ یہ عارضی کیوری کے URL کا استعمال کرتے ہوئے جیسا کہ اوپر دائیں کالم کے اوپر دیکھا گیا ہے کام کر رہا ہے۔ جیسا کہ یہ نام پہلے ہی تجویز کرتا ہے، یہ ایک عارضی URL ہے اور اسے پروڈکشن میں استعمال نہیں کیا جانا چاہیے. -- یاد رکھیں کہ اشاعت ایک آن چین ایکشن ہے اور اس کے لیے ایتھیریم میں گیس کی ادائیگی کی ضرورت ہوگی - [یہاں](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b) ایک مثالی ٹرانزیکشن دیکھیں. قیمتیں 100 gwei پر تقریباً 0.0425 ETH ہیں. -- جب بھی آپ کو اپنا سب گراف اپ گریڈ کرنے کی ضرورت ہو، آپ سے اپ گریڈ فیس وصول کی جائے گی۔ یاد رکھیں، اپ گریڈ کرنا صرف آپ کے موجودہ سب گراف آن چین کا دوسرا ورژن شائع کرنا ہے۔ چونکہ اس پر لاگت آتی ہے، اس لیے مین نیٹ پر تعینات کرنے سے پہلے اپنے سب گراف کو Goerli پر تعینات کرنے اور جانچنے کی انتہائی سفارش کی جاتی ہے۔ اگر اس سب گراف پر کوئی سگنل نہیں ہے تو اسے، بعض صورتوں میں، کچھ GRT کی بھی ضرورت پڑ سکتی ہے۔ اس سب گراف ورژن پر سگنل/کیوریشن ہونے کی صورت میں (آٹو مائیگریٹ کا استعمال کرتے ہوئے)، ٹیکس تقسیم ہو جائیں گے. +- اشاعت ایک آن چین ایکشن ہے اور اس کے لیے ایتھیریم میں گیس کی ادائیگی کی ضرورت ہوگی - [یہاں](https://etherscan.io/tx/0xd0c3fa0bc035703c9ba1ce40c1862559b9c5b6ea1198b3320871d535aa0de87b) ایک مثالی ٹرانزیکشن دیکھیں. قیمتیں 100 gwei پر تقریباً 0.0425 ETH ہیں. +- جب آپ کو اپنا سب گراف اپ گریڈ کرنے کی ضرورت ہو، آپ سے اپ گریڈ فیس وصول کی جائے گی۔ یاد رکھیں، اپ گریڈ کرنا صرف آپ کے موجودہ سب گراف آن چین کا دوسرا ورژن شائع کرنا ہے۔ چونکہ اس پر لاگت آتی ہے، اس لیے مین نیٹ پر تعینات کرنے سے پہلے اپنے سب گراف کو Goerli پر تعینات کرنے اور جانچنے کی انتہائی سفارش کی جاتی ہے۔ اگر اس سب گراف پر کوئی سگنل نہیں ہے تو اسے، بعض صورتوں میں، کچھ GRT کی بھی ضرورت پڑ سکتی ہے۔ اس سب گراف ورژن پر سگنل/کیوریشن ہونے کی صورت میں (آٹو مائیگریٹ کا استعمال کرتے ہوئے)، ٹیکس تقسیم ہو جائیں گے. 7. "شائع کریں" کے بٹن کو دبا کر گراف کے decentralized نیٹ ورک پر سب گراف کو شائع کریں. @@ -201,7 +203,7 @@ _جبکہ یہ طریقہ کار فی الہال نیٹورک پر لایؤ ہے جب آپ اپنے استفسار کے بجٹ کا فیصلہ کرتے ہیں، تو اس بات کی کوئی گارنٹی نہیں ہے کہ انڈیکسر اس قیمت پر سوالات پیش کرنے کے لیے تیار ہوگا۔ اگر کوئی گیٹ وے آپ کو کسی ایسے انڈیکسر سے ملا سکتا ہے جو آپ کی قیمت پر یا اس سے کم قیمت پر سوال پیش کرنے کے لیے تیار ہے، تو آپ اپنے بجٹ کا ڈیلٹا/فرق ادا کریں گے **اور** ان کی قیمت. نتیجے کے طور پر، کم استفسار کی قیمت آپ کے لیے دستیاب انڈیکسرز کے پول کو کم کر دیتی ہے، جو آپ کو موصول ہونے والی سروس کے معیار کو متاثر کر سکتی ہے۔ استفسار کی زیادہ فیس لینا فائدہ مند ہے، کیونکہ یہ آپ کے سب گراف میں کیوریشن اور بڑے نام کے انڈیکسرز کو راغب کر سکتا ہے. -یاد رکہیں کہ یہ متحرک اور بڑھتی مارکیٹ ہے، لیکن آپ کیسے اس کے ساتہ تعامل کرتے ہیں یہ آپ کے اختیار میں ہے. پروٹوکول یا گیٹ ویز میں کوئی زیادہ سے زیادہ یا کم از کم قیمت نہیں بتائی گئی ہے. مثال کے طور پر، آپ ذیل میں نیٹ ورک پر (فی ہفتہ کی بنیاد پر) چند ڈیپ کے ذریعے ادا کی گئی قیمت کو دیکھ سکتے ہیں۔ آخری کالم دیکھیں، جو GRT میں استفسار کی فیس دکھاتا ہے۔ مثال کے طور پر، [Pickle Finance](https://www.pickle.finance/) کے پاس فی سیکنڈ 8 درخواستیں ہیں اور ایک ہفتے کے لیے 2.4 GRT ادا کیے گئے ہیں. +یاد رکھیں کہ یہ ایک متحرک اور بڑھتی ہوئی مارکیٹ ہے، لیکن آپ اس کے ساتھ کیسے تعامل کرتے ہیں یہ آپ کے اختیار میں ہے۔ پروٹوکول یا گیٹ ویز میں کوئی زیادہ سے زیادہ یا کم از کم قیمت نہیں بتائی گئی ہے۔ مثال کے طور پر، آپ ذیل میں نیٹ ورک پر (فی ہفتہ کی بنیاد پر) چند ڈیپ کے ذریعے ادا کی گئی قیمت کو دیکھ سکتے ہیں۔ آخری کالم دیکھیں، جو GRT میں کیوری کی فیس دکھاتا ہے. ![QueryFee](/img/QueryFee.png) diff --git a/website/pages/ur/cookbook/near.mdx b/website/pages/ur/cookbook/near.mdx index 7728c939991a..856b8bebf540 100644 --- a/website/pages/ur/cookbook/near.mdx +++ b/website/pages/ur/cookbook/near.mdx @@ -50,7 +50,7 @@ $ graph build # generates Web Assembly from the AssemblyScript files, and prepar ### سب گراف مینی فیسٹ کی تعریف -سب گراف مینی فیسٹ (`subgraph.yaml`) سب گراف کے لیے ڈیٹا کے ذرائع، دلچسپی کے محرکات، اور ان افعال کی نشاندہی کرتا ہے جو ان محرکات کے جواب میں چلائے جانے چاہئیں۔ NEAR سب گراف کے لیے ذیل میں ذیل میں سب گراف مینی فیسٹ کی مثال دیکھیں:: +سب گراف مینی فیسٹ (`subgraph.yaml`) سب گراف کے لیے ڈیٹا کے ذرائع، دلچسپی کے محرکات، اور ان افعال کی نشاندہی کرتا ہے جو ان محرکات کے جواب میں چلائے جانے چاہئیں۔ NEAR سب گراف کے لیے ذیل میں ذیل میں سب گراف مینی فیسٹ کی مثال دیکھیں: ```yaml specVersion: 0.0.2 diff --git a/website/pages/ur/cookbook/subgraph-uncrashable.mdx b/website/pages/ur/cookbook/subgraph-uncrashable.mdx new file mode 100644 index 000000000000..3d1722e0babe --- /dev/null +++ b/website/pages/ur/cookbook/subgraph-uncrashable.mdx @@ -0,0 +1,29 @@ +--- +title: محفوظ سب گراف کوڈ جنریٹر +--- + +[سب گراف ان کریش ایبل](https://float-capital.github.io/float-subgraph-uncrashable/) ایک کوڈ جنریشن ٹول ہے جو کسی پروجیکٹ کے graphql اسکیما سے مددگار فنکشنز کا ایک سیٹ تیار کرتا ہے۔. یہ یقینی بناتا ہے کہ آپ کے سب گراف میں موجود اداروں کے ساتھ تمام تعاملات مکمل طور پر محفوظ اور مستقل ہوں. + +### سب گراف ان کریش ایبل کے ساتھ کیوں ضم کیا جائے؟ + +- **مسلسل اپ ٹائم**۔ غلط ہستیوں کی وجہ سے سب گراف کریش ہو سکتے ہیں، جو گراف پر منحصر منصوبوں کے لیے خلل ڈال سکتے ہیں۔ اپنے سب گراف کو "ناقابل شکست" بنانے اور کاروبار کے تسلسل کو یقینی بنانے کے لیے مددگار فنکشنز ترتیب دیں. + +- **مکمل طور پر محفوظ**۔ سب گراف ڈیولپمنٹ میں جو عام مسائل نظر آتے ہیں وہ غیر متعینہ ہستیوں کو لوڈ کرنے، اداروں کی تمام قدروں کو ترتیب دینے یا شروع نہ کرنے، اور اداروں کو لوڈ کرنے اور بچانے پر ریس کے حالات ہیں۔ یقینی بنائیں کہ اداروں کے ساتھ تمام تعاملات مکمل طور پر جوہری ہیں. + +- **صارف قابل ترتیب** پہلے سے طے شدہ اقدار کو سیٹ کریں اور حفاظتی جانچ کی سطح کو ترتیب دیں جو آپ کے انفرادی پروجیکٹ کی ضروریات کے مطابق ہو۔ انتباہی لاگز ریکارڈ کیے جاتے ہیں جو اس بات کی نشاندہی کرتے ہیں کہ ڈیٹا کی درستگی کو یقینی بنانے کے لیے مسئلے کو پیچ کرنے میں مدد کرنے کے لیے سب گراف کی منطق کی کہاں خلاف ورزی ہوئی ہے. + +**اہم خصوصیات** + +- کوڈ جنریشن ٹول **تمام** سب گراف کی اقسام کو ایڈجسٹ کرتا ہے اور صارفین کے لیے قدروں پر سمجھدار ڈیفالٹس سیٹ کرنے کے لیے قابل ترتیب ہے۔ کوڈ جنریشن اس کنفیگریشن کو مددگار فنکشنز جنریٹ کرنے کے لیے استعمال کرے گی جو صارفین کی تفصیلات کے لیے ہیں. + +- فریم ورک میں ہستی متغیرات کے گروپس کے لیے حسب ضرورت، لیکن محفوظ، سیٹر فنکشنز بنانے کا ایک طریقہ (کنفگ فائل کے ذریعے) بھی شامل ہے۔ اس طرح صارف کے لیے کسی باسی گراف ہستی کو لوڈ/استعمال کرنا ناممکن ہے اور فنکشن کے لیے مطلوبہ متغیر کو محفوظ کرنا یا سیٹ کرنا بھولنا بھی ناممکن ہے. + +- انتباہی لاگز کو لاگز کے طور پر ریکارڈ کیا جاتا ہے جو اس بات کی نشاندہی کرتے ہیں کہ ڈیٹا کی درستگی کو یقینی بنانے کے لیے مسئلے کو پیچ کرنے میں مدد کے لیے سب گراف کی منطق کی خلاف ورزی کہاں ہے۔ یہ لاگز 'لاگز' سیکشن کے تحت دی گراف کی میزبانی کی ہوسٹڈ میں دیکھے جا سکتے ہیں. + +گراف CLI کوڈجن کمانڈ کا استعمال کرتے ہوئے سب گراف ان کریش ایبل کو اختیاری پرچم کے طور پر چلایا جا سکتا ہے. + +```sh +گراف کوڈجن -u [اختیارات] [] +``` + +[سب گراف ان کریش ایبل دستاویزات](https://float-capital.github.io/float-subgraph-uncrashable/docs/) دیکھیں یا اسے دیکھیں [ویڈیو ٹیوٹوریل](https://float- capital.github.io/float-subgraph-uncrashable/docs/tutorial) مزید جاننے اور محفوظ سب گراف تیار کرنے کے ساتھ شروع کرنے کے لیے. diff --git a/website/pages/ur/deploying/deploying-a-subgraph-to-studio.mdx b/website/pages/ur/deploying/deploying-a-subgraph-to-studio.mdx index 2d175a3ebc63..0caed434389a 100644 --- a/website/pages/ur/deploying/deploying-a-subgraph-to-studio.mdx +++ b/website/pages/ur/deploying/deploying-a-subgraph-to-studio.mdx @@ -2,17 +2,11 @@ title: سب گراف سٹوڈیو پر سب گراف تعینات کرنا --- -## سپورٹڈ نیٹ ورکس +> یقینی بنائیں کہ آپ کا سب گراف جس نیٹ ورک سے ڈیٹا انڈیکس کر رہا ہے وہ ڈیسینٹرالائزڈ نیٹ ورک پر [تعاون یافتہ](/developing/supported-chains) ہے. -گراف نیٹ ورک ذیلی چین کو ترتیب دینے والے سب گراف کو سپورٹ کرتا ہے: +اپنے سب گراف کو سب گراف سٹوڈیو میں تعینات کرنے کے یہ اقدامات ہیں: -### ایتھریم - -- `mainnet` - -سب گراف کو سب گراف سٹوڈیو میں تعینات کرنا کافی آسان ہے. یہ آپ کو مندرجہ ذیل مراحل میں لے جائے گا: - -- Graph CLI کو انسٹال کریں(دونو yarn اور npm سے) +- گراف CLI انسٹال کریں (یارن یا این پی ایم کے ساتھ) - اپنا سب گراف سب گراف سٹوڈیو میں بنائیں - CLI سے اپنے اکاؤنٹ کی تصدیق کریں - سب گراف سٹوڈیو پر سب گراف تعینات کرنا diff --git a/website/pages/ur/deploying/subgraph-studio-faqs.mdx b/website/pages/ur/deploying/subgraph-studio-faqs.mdx index 61d84bed85f1..74908585bf0e 100644 --- a/website/pages/ur/deploying/subgraph-studio-faqs.mdx +++ b/website/pages/ur/deploying/subgraph-studio-faqs.mdx @@ -8,7 +8,7 @@ title: سب گراف اسٹوڈیو کے اکثر پوچھے گئے سوالات ### 2. میں ایک API کلید کیسے بنا سکتا ہوں؟ -سب گراف اسٹوڈیو میں، آپ ضرورت کے مطابق API کیز بنا سکتے ہیں اور ان میں سے ہر ایک میں سیکیورٹی کی ترتیبات شامل کر سکتے ہیں. +API بنانے کے لیے، سب گراف اسٹوڈیو پر جائیں اور اپنے والیٹ کو جوڑیں۔ آپ سب سے اوپر API کیز ٹیب پر کلک کر سکیں گے۔ وہاں، آپ ایک API کیز بنانے کے قابل ہو جائیں گے. ### 3. کیا میں ایک سے زیادہ API کیز بنا سکتا ہوں؟ diff --git a/website/pages/ur/developing/assemblyscript-api.mdx b/website/pages/ur/developing/assemblyscript-api.mdx index f0cc7998be6d..62b9529ca537 100644 --- a/website/pages/ur/developing/assemblyscript-api.mdx +++ b/website/pages/ur/developing/assemblyscript-api.mdx @@ -762,3 +762,10 @@ if (value.kind == JSONValueKind.BOOL) { - `getBytes(key: string): Bytes` - `getBoolean(key: string): boolean` - `getBigDecimal(key: string): BigDecimal` + +### مشترکہ اسمبلی سکرپٹ کے مسائل + +کچھ [اسمبلی اسکرپٹ](https://github.com/AssemblyScript/assemblyscript) کے مسائل ہیں جو سب گراف کی ترقی کے دوران عام ہیں۔ وہ ڈیبگ کی دشواری میں ہیں، تاہم، ان کے بارے میں آگاہ ہونے سے مدد مل سکتی ہے۔ مندرجہ ذیل ان مسائل کی ایک غیر مکمل فہرست ہے: + +- `Private` کلاس متغیرات کو [اسمبلی اسکرپٹ](https://www.assemblyscript.org/status.html#language-features) میں نافذ نہیں کیا جاتا ہے۔ کلاس کے متغیرات کو کلاس آبجیکٹ سے براہ راست تبدیل ہونے سے بچانے کا کوئی طریقہ نہیں ہے. +- دائرہ کار [کلوژر فنکشنز](https://www.assemblyscript.org/status.html#on-closures) میں وراثت میں نہیں ملا ہے، یعنی بندش کے فنکشنز سے باہر اعلان کردہ متغیرات کو استعمال نہیں کیا جا سکتا۔ [ڈیولپر ہائی لائٹس #3](https://www.youtube.com/watch?v=1-8AW-lVfrA&t=3243s) میں وضاحت. diff --git a/website/pages/ur/developing/unit-testing-framework.mdx b/website/pages/ur/developing/unit-testing-framework.mdx index 0d8aed22f365..447dfe80c866 100644 --- a/website/pages/ur/developing/unit-testing-framework.mdx +++ b/website/pages/ur/developing/unit-testing-framework.mdx @@ -24,6 +24,12 @@ yarn add --dev matchstick-as brew install postgresql ``` +تازہ ترین libpq.5.lib کا ایک سملنک بنائیں _آپ کو پہلے یہ ڈائر بنانے کی ضرورت پڑسکتی ہے_ `/usr/local/opt/postgresql/lib/` + +```sh +ln -sf /usr/local/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib /usr/local/opt/postgresql/lib/libpq.5.dylib +``` + #### Linux پوسٹگریس انسٹالیشن کمانڈ (آپ کے ڈسٹرو پر منحصر ہے): @@ -52,7 +58,7 @@ static BYTES = Symbol("Bytes") SyntaxError: Unexpected token = sudo apt-get install libpq-dev ``` -اور آخر میں، `graph test` استعمال نہ کریں (جو آپ کے گراف-cli کی عالمی تنصیب کا استعمال کرتا ہے اور کسی وجہ سے ایسا لگتا ہے کہ یہ WSL پر فی الحال ٹوٹا ہوا ہے)، اس کے بجائے ` Yarn test` استعمال کریں۔ یا `npm رن ٹیسٹ` (جو گراف-cli کی مقامی، پروجیکٹ لیول مثال استعمال کرے گا، جو ایک جادو کی طرح کام کرتا ہے۔ اس کے لیے یقیناً آپ کو اپنی `package.json` فائل میں ایک `"test"` اسکرپٹ کی ضرورت ہوگی جو اتنی ہی آسان ہوسکتی ہے +اور آخر میں، `گراف ٹیسٹ` کا استعمال نہ کریں (جو آپ کے گراف-کلی کی عالمی تنصیب کا استعمال کرتا ہے اور کسی وجہ سے ایسا لگتا ہے کہ یہ فی الحال WSL پر ٹوٹ گیا ہے)، اس کے بجائے `yarn test` کا استعمال کریں۔ یا `npm run test` (جو گراف-cli کی مقامی، پروجیکٹ لیول مثال استعمال کرے گا، جو ایک دلکش کی طرح کام کرتا ہے)۔ اس کے لیے یقیناً آپ کو اپنی `package.json` فائل میں ایک `"test"` اسکرپٹ کی ضرورت ہوگی جو اتنی ہی آسان ہوسکتی ہے ```json { diff --git a/website/pages/vi/cookbook/cosmos.mdx b/website/pages/vi/cookbook/cosmos.mdx deleted file mode 120000 index 66acfa28a317..000000000000 --- a/website/pages/vi/cookbook/cosmos.mdx +++ /dev/null @@ -1 +0,0 @@ -../../en/cookbook/cosmos.mdx \ No newline at end of file diff --git a/website/pages/zh/cookbook/cosmos.mdx b/website/pages/zh/cookbook/cosmos.mdx deleted file mode 120000 index 66acfa28a317..000000000000 --- a/website/pages/zh/cookbook/cosmos.mdx +++ /dev/null @@ -1 +0,0 @@ -../../en/cookbook/cosmos.mdx \ No newline at end of file diff --git a/website/pages/zh/docsearch.json b/website/pages/zh/docsearch.json index 8cfff967936d..2d334ea4c629 100644 --- a/website/pages/zh/docsearch.json +++ b/website/pages/zh/docsearch.json @@ -1,42 +1,42 @@ { "button": { - "buttonText": "Search", - "buttonAriaLabel": "Search" + "buttonText": "搜索", + "buttonAriaLabel": "搜索" }, "modal": { "searchBox": { - "resetButtonTitle": "Clear the query", - "resetButtonAriaLabel": "Clear the query", - "cancelButtonText": "Cancel", - "cancelButtonAriaLabel": "Cancel" + "resetButtonTitle": "清除查询", + "resetButtonAriaLabel": "清除查询", + "cancelButtonText": "取消", + "cancelButtonAriaLabel": "取消" }, "startScreen": { - "recentSearchesTitle": "Recent", - "noRecentSearchesText": "No recent searches", - "saveRecentSearchButtonTitle": "Save this search", - "removeRecentSearchButtonTitle": "Remove this search from history", - "favoriteSearchesTitle": "Favorite", - "removeFavoriteSearchButtonTitle": "Remove this search from favorites" + "recentSearchesTitle": "最近", + "noRecentSearchesText": "无最近搜索", + "saveRecentSearchButtonTitle": "保存此次搜索", + "removeRecentSearchButtonTitle": "从历史中删除这条搜索", + "favoriteSearchesTitle": "收藏", + "removeFavoriteSearchButtonTitle": "从收藏中移除此条搜索" }, "errorScreen": { - "titleText": "Unable to fetch results", - "helpText": "You might want to check your network connection." + "titleText": "无法获取结果", + "helpText": "请检查网络连接" }, "footer": { - "selectText": "to select", - "selectKeyAriaLabel": "Enter key", - "navigateText": "to navigate", - "navigateUpKeyAriaLabel": "Arrow up", - "navigateDownKeyAriaLabel": "Arrow down", - "closeText": "to close", - "closeKeyAriaLabel": "Escape key", - "searchByText": "Search by" + "selectText": "选择", + "selectKeyAriaLabel": "回车键", + "navigateText": "导览", + "navigateUpKeyAriaLabel": "向上", + "navigateDownKeyAriaLabel": "向下", + "closeText": "关闭", + "closeKeyAriaLabel": "退出键", + "searchByText": "搜索" }, "noResultsScreen": { - "noResultsText": "No results for", - "suggestedQueryText": "Try searching for", - "reportMissingResultsText": "Believe this query should return results?", - "reportMissingResultsLinkText": "Let us know." + "noResultsText": "无结果", + "suggestedQueryText": "搜索", + "reportMissingResultsText": "觉得这个搜索应该有结果?", + "reportMissingResultsLinkText": "联系我们" } } } diff --git a/website/pages/zh/global.json b/website/pages/zh/global.json index f611d5fddab9..964dbc99fe93 100644 --- a/website/pages/zh/global.json +++ b/website/pages/zh/global.json @@ -1,26 +1,26 @@ { "navigation": { - "theGraphNetwork": "The Graph Network", - "subgraphs": "Subgraphs", - "developing": "Developing", - "deploying": "Deploying", - "publishing": "Publishing", - "managing": "Managing", - "querying": "Querying", - "cookbook": "Cookbook", - "indexing": "Indexing", - "releaseNotes": "Release Notes & Upgrade Guides" + "theGraphNetwork": "Graph网络", + "subgraphs": "子图", + "developing": "开发", + "deploying": "部署", + "publishing": "发布", + "managing": "管理", + "querying": "查询", + "cookbook": "导览", + "indexing": "索引", + "releaseNotes": "发布说明&更新向导" }, - "collapse": "崩溃", - "expand": "扩展", - "previous": "以前的", - "next": "下一个", - "editPage": "编辑页面", - "pageSections": "页面部分", - "linkToThisSection": "链接到本节", - "technicalLevelRequired": "技术水平要求", - "notFoundTitle": "哎呀! 这个页面丢失了...", - "notFoundSubtitle": "检查您是否使用了正确的地址或通过单击下面的链接浏览我们的网站。", - "goHome": "返回主页", - "video": "Video" + "collapse": "收起", + "expand": "打开", + "previous": "上页", + "next": "下页", + "editPage": "编辑", + "pageSections": "页面分节", + "linkToThisSection": "链到本节", + "technicalLevelRequired": "技术要求", + "notFoundTitle": "哦! 这个页面丢失了...", + "notFoundSubtitle": "检查您是否使用正确地址或通过单击以下链接浏览网站。", + "goHome": "主页", + "video": "视频" } diff --git a/website/pages/zh/index.json b/website/pages/zh/index.json index 7d12eab6526d..367b3d0d2bb1 100644 --- a/website/pages/zh/index.json +++ b/website/pages/zh/index.json @@ -1,17 +1,17 @@ { "title": "开始", - "intro": "了解The Graph,一个用于索引和查询区块链数据的去中心化的协议。", + "intro": "了解Graph,一个用于索引和查询区块链数据的去中心化的协议。", "shortcuts": { "aboutTheGraph": { - "title": "关于 The Graph", - "description": "了解有关The Graph的更多信息" + "title": "关于 Graph", + "description": "关于Graph的更多信息" }, "quickStart": { "title": "快速开始", - "description": "加入并从 The Graph 开始" + "description": "加入并从Graph 开始" }, "developerFaqs": { - "title": "开发常见问题", + "title": "开发者常见问题", "description": "常见问题" }, "queryFromAnApplication": { @@ -20,32 +20,32 @@ }, "createASubgraph": { "title": "创建子图", - "description": "使用工作室来创建子图" + "description": "在子图工作室中创建子图" }, "migrateFromHostedService": { "title": "从托管服务中迁移", - "description": "将子图迁移到The Graph网络上" + "description": "将子图迁移到Graph网络上" } }, "networkRoles": { "title": "网络角色", - "description": "了解The Graph的网络角色。", + "description": "了解Graph的网络角色", "roles": { "developer": { "title": "开发者", - "description": "创建一个子图或在一个去中心化应用中使用现有的子图" + "description": "创建子图或在去中心化应用中使用现有子图" }, "indexer": { - "title": "索引", - "description": "操作节点以索引数据并提供查询" + "title": "索引人", + "description": "通过节点索引数据并提供查询服务" }, "curator": { - "title": "策展", - "description": "通过在子图上发出信号来组织数据" + "title": "策展人", + "description": "通过子图标识结果来组织数据" }, "delegator": { - "title": "委托", - "description": "通过将 GRT 委托给索引人来保护网络" + "title": "委托者", + "description": "通过将 GRT 委托给索引人来维护网络" } } }, @@ -69,9 +69,9 @@ }, "supportedNetworks": { "title": "支持的网络", - "description": "The Graph支持The Graph网络和托管服务的以下网络。", - "graphNetworkAndHostedService": "The Graph网络和托管服务", + "description": "Graph支持在Graph网络和托管服务上的以下网络。", + "graphNetworkAndHostedService": "Graph网络和托管服务", "hostedService": "托管服务", - "betaWarning": "网络正处于测试阶段。请谨慎使用。" + "betaWarning": "网络正处于测试阶段" } } diff --git a/website/route-lockfile.txt b/website/route-lockfile.txt index 5e33c2801200..cf6a7dfcdca3 100644 --- a/website/route-lockfile.txt +++ b/website/route-lockfile.txt @@ -89,15 +89,17 @@ /es/ /es/404/ /es/about/ +/es/arbitrum-faq/ /es/billing/ /es/cookbook/arweave/ -/es/cookbook/cosmos/ +/es/cookbook/base-testnet/ /es/cookbook/grafting/ /es/cookbook/migrating-a-subgraph/ /es/cookbook/multisig/ /es/cookbook/near/ /es/cookbook/quick-start/ /es/cookbook/subgraph-debug-forking/ +/es/cookbook/subgraph-uncrashable/ /es/deploying/deploying-a-subgraph-to-hosted/ /es/deploying/deploying-a-subgraph-to-studio/ /es/deploying/hosted-service/ @@ -108,8 +110,11 @@ /es/developing/defining-a-subgraph/ /es/developing/developer-faqs/ /es/developing/unit-testing-framework/ +/es/firehose/ +/es/glossary/ /es/managing/deprecating-a-subgraph/ /es/managing/transferring-subgraph-ownership/ +/es/mips-faqs/ /es/network-transition-faq/ /es/network/curating/ /es/network/delegating/ @@ -135,16 +140,23 @@ /fr/publishing/publishing-a-subgraph/ /fr/querying/querying-the-hosted-service/ /fr/substreams/ +/hi/cookbook/grafting/ +/hi/cookbook/migrating-a-subgraph/ +/hi/cookbook/subgraph-uncrashable/ +/hi/deploying/subgraph-studio-faqs/ /ja/ /ja/404/ /ja/about/ +/ja/arbitrum-faq/ /ja/cookbook/arweave/ -/ja/cookbook/cosmos/ +/ja/cookbook/base-testnet/ +/ja/cookbook/grafting/ /ja/cookbook/migrating-a-subgraph/ /ja/cookbook/multisig/ /ja/cookbook/near/ /ja/cookbook/quick-start/ /ja/cookbook/subgraph-debug-forking/ +/ja/cookbook/subgraph-uncrashable/ /ja/deploying/deploying-a-subgraph-to-hosted/ /ja/deploying/deploying-a-subgraph-to-studio/ /ja/deploying/hosted-service/ @@ -155,8 +167,11 @@ /ja/developing/defining-a-subgraph/ /ja/developing/developer-faqs/ /ja/developing/unit-testing-framework/ +/ja/firehose/ +/ja/glossary/ /ja/managing/deprecating-a-subgraph/ /ja/managing/transferring-subgraph-ownership/ +/ja/mips-faqs/ /ja/network/curating/ /ja/network/delegating/ /ja/network/explorer/ @@ -210,25 +225,31 @@ /ko/querying/querying-the-hosted-service/ /ko/release-notes/assemblyscript-migration-guide/ /ru/cookbook/arweave/ +/ru/cookbook/base-testnet/ /ru/cookbook/quick-start/ /ru/cookbook/subgraph-debug-forking/ /ru/cookbook/subgraph-uncrashable/ +/ru/deploying/deploying-a-subgraph-to-studio/ /ru/deploying/hosted-service/ /ru/firehose/ +/ru/querying/distributed-systems/ /ru/tokenomics/ /uk/network/benefits/ /uk/network/curating/ /uk/network/delegating/ /uk/network/developing/ /ur/about/ +/ur/arbitrum-faq/ /ur/billing/ /ur/cookbook/arweave/ +/ur/cookbook/base-testnet/ /ur/cookbook/cosmos/ /ur/cookbook/grafting/ /ur/cookbook/migrating-a-subgraph/ /ur/cookbook/near/ /ur/cookbook/quick-start/ /ur/cookbook/subgraph-debug-forking/ +/ur/cookbook/subgraph-uncrashable/ /ur/deploying/deploying-a-subgraph-to-hosted/ /ur/deploying/deploying-a-subgraph-to-studio/ /ur/deploying/hosted-service/