diff --git a/pages/ar/about/introduction.mdx b/pages/ar/about/introduction.mdx index 5f840c040400..64f253a7995b 100644 --- a/pages/ar/about/introduction.mdx +++ b/pages/ar/about/introduction.mdx @@ -1,47 +1,47 @@ --- -title: Introduction +title: مقدمة --- -This page will explain what The Graph is and how you can get started. +هذه الصفحة ستشرح The Graph وكيف يمكنك أن تبدأ. -## What The Graph Is +## ما هو The Graph -The Graph is a decentralized protocol for indexing and querying data from blockchains, starting with Ethereum. It makes it possible to query data that is difficult to query directly. +The Graph هو بروتوكول لامركزي وذلك لفهرسة البيانات والاستعلام عنها من blockchains ، بدءًا من Ethereum. حيث يمكننا من الاستعلام عن البيانات والتي من الصعب الاستعلام عنها بشكل مباشر. -Projects with complex smart contracts like [Uniswap](https://uniswap.org/) and NFTs initiatives like [Bored Ape Yacht Club](https://boredapeyachtclub.com/) store data on the Ethereum blockchain, making it really difficult to read anything other than basic data directly from the blockchain. +المشاريع ذات العقود الذكية المعقدة مثل [ Uniswap ](https://uniswap.org/) و NFTs مثل [ Bored Ape Yacht Club ](https://boredapeyachtclub.com/) تقوم بتخزين البيانات على Ethereum blockchain ، مما يجعل من الصعب قراءة أي شيء بشكل مباشر عدا البيانات الأساسية من blockchain. -In the case of Bored Ape Yacht Club, we can perform basic read operations on [the contract](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) like getting the owner of a certain Ape, getting the content URI of an Ape based on their ID, or the total supply, as these read operations are programmed directly into the smart contract, but more advanced real-world queries and operations like aggregation, search, relationships, and non-trivial filtering are not possible. For example, if we wanted to query for apes that are owned by a certain address, and filter by one of its characteristics, we would not be able to get that information by interacting directly with the contract itself. +في حالة Bored Ape Yacht Club ، يمكننا إجراء قراءات أساسية على [ العقد ](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) مثل الحصول على مالك Ape معين ،أو الحصول على محتوى URI لـ Ape وذلك بناء على ال ID الخاص به، أو إجمالي العرض ، حيث تتم برمجة عمليات القراءة هذه بشكل مباشر في العقد الذكي ، ولكن في العالم الحقيقي هناك استعلامات وعمليات أكثر تقدمًا غير ممكنة مثل التجميع والبحث والعلاقات والفلترة الغير بسيطة. فمثلا، إذا أردنا الاستعلام عن Apes مملوكة لعنوان معين ،وفلترته حسب إحدى خصائصه، فلن نتمكن من الحصول على تلك المعلومات من خلال التفاعل بشكل مباشر مع العقد نفسه. -To get this data, you would have to process every single [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) event ever emitted, read the metadata from IPFS using the Token ID and IPFS hash, and then aggregate it. Even for these types of relatively simple questions, it would take **hours or even days** for a decentralized application (dapp) running in a browser to get an answer. +للحصول على هذه البيانات، يجب معالجة كل [`التحويلات`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) التي حدثت، وقراءة البيانات الوصفية من IPFS باستخدام Token ID و IPFS hash، ومن ثم تجميعه. حتى بالنسبة لهذه الأنواع من الأسئلة البسيطة نسبيا ، قد يستغرق الأمر ** ساعات أو حتى أيام ** لتطبيق لامركزي (dapp) يعمل في متصفح للحصول على إجابة. -You could also build out your own server, process the transactions there, save them to a database, and build an API endpoint on top of it all in order to query the data. However, this option is resource intensive, needs maintenance, presents a single point of failure, and breaks important security properties required for decentralization. +يمكنك أيضا إنشاء الخادم الخاص بك ، ومعالجة الإجراءات هناك ، وحفظها في قاعدة بيانات ، والقيام ببناء API endpoint من أجل الاستعلام عن البيانات. ومع ذلك ، فإن هذا الخيار يتطلب موارد كثيرة ، ويحتاج إلى صيانة ، ويقدم نقطة فشل واحدة ، ويكسر خصائص الأمان الهامة المطلوبة لتحقيق اللامركزية. -**Indexing blockchain data is really, really hard.** +**إن فهرسة بيانات الـ blockchain أمر صعب.** -Blockchain properties like finality, chain reorganizations, or uncled blocks complicate this process further, and make it not just time consuming but conceptually hard to retrieve correct query results from blockchain data. +خصائص الـ Blockchain مثل finality أو chain reorganizations أو uncled blocks تعقد هذه العملية بشكل أكبر ، ولن تجعلها مضيعة للوقت فحسب ، بل أيضا تجعلها من الصعب من الناحية النظرية جلب نتائج الاستعلام الصحيحة من بيانات الـ blockchain. -The Graph solves this with a decentralized protocol that indexes and enables the performant and efficient querying of blockchain data. These APIs (indexed "subgraphs") can then be queried with a standard GraphQL API. Today, there is a hosted service as well as a decentralized protocol with the same capabilities. Both are backed by the open source implementation of [Graph Node](https://github.com/graphprotocol/graph-node). +يقوم The Graph بحل هذا الأمر من خلال بروتوكول لامركزي والذي يقوم بفهرسة والاستعلام عن بيانات الـ blockchain بكفاءة عالية. حيث يمكن بعد ذلك الاستعلام عن APIs (الـ "subgraphs" المفهرسة) باستخدام GraphQL API قياسية. اليوم ، هناك خدمة مستضافة بالإضافة إلى بروتوكول لامركزي بنفس القدرات. كلاهما مدعوم بتطبيق مفتوح المصدر لـ [ Graph Node ](https://github.com/graphprotocol/graph-node). -## How The Graph Works +## كيف يعمل The Graph -The Graph learns what and how to index Ethereum data based on subgraph descriptions, known as the subgraph manifest. The subgraph description defines the smart contracts of interest for a subgraph, the events in those contracts to pay attention to, and how to map event data to data that The Graph will store in its database. +The Graph يفهرس بيانات Ethereumالـ بناء على أوصاف الـ subgraph ، والمعروفة باسم subgraph manifest. حيث أن وصف الـ subgraph يحدد العقود الذكية ذات الأهمية لـ subgraph ، ويحدد الأحداث في تلك العقود التي يجب الانتباه إليها ، وكيفية تعيين بيانات الحدث إلى البيانات التي سيخزنها The Graph في قاعدة البيانات الخاصة به. -Once you have written a `subgraph manifest`, you use the Graph CLI to store the definition in IPFS and tell the indexer to start indexing data for that subgraph. +بمجرد كتابة ` subgraph manifest ` ، يمكنك استخدام Graph CLI لتخزين التعريف في IPFS وإخبار المفهرس ببدء فهرسة البيانات لذلك الـ subgraph. -This diagram gives more detail about the flow of data once a subgraph manifest has been deployed, dealing with Ethereum transactions: +يقدم هذا الرسم البياني مزيدًا من التفاصيل حول تدفق البيانات عند نشر الـsubgraph manifest ، التعامل مع إجراءات الـ Ethereum: ![](/img/graph-dataflow.png) -The flow follows these steps: +تدفق البيانات يتبع الخطوات التالية: -1. A decentralized application adds data to Ethereum through a transaction on a smart contract. -2. The smart contract emits one or more events while processing the transaction. -3. Graph Node continually scans Ethereum for new blocks and the data for your subgraph they may contain. -4. Graph Node finds Ethereum events for your subgraph in these blocks and runs the mapping handlers you provided. The mapping is a WASM module that creates or updates the data entities that Graph Node stores in response to Ethereum events. -5. The decentralized application queries the Graph Node for data indexed from the blockchain, using the node's [GraphQL endpoint](https://graphql.org/learn/). The Graph Node in turn translates the GraphQL queries into queries for its underlying data store in order to fetch this data, making use of the store's indexing capabilities. The decentralized application displays this data in a rich UI for end-users, which they use to issue new transactions on Ethereum. The cycle repeats. +1. التطبيق اللامركزي يضيف البيانات إلى الـ Ethereum من خلال إجراء على العقد الذكي. +2. العقد الذكي يصدر حدثا واحدا أو أكثر أثناء معالجة الإجراء. +3. يقوم الـ Graph Node بمسح الـ Ethereum باستمرار بحثا عن الكتل الجديدة وبيانات الـ subgraph الخاص بك. +4. يعثر الـ Graph Node على أحداث الـ Ethereum لـ subgraph الخاص بك في هذه الكتل ويقوم بتشغيل mapping handlers التي قدمتها. الـ mapping عبارة عن وحدة WASM والتي تقوم بإنشاء أو تحديث البيانات التي يخزنها Graph Node استجابة لأحداث الـ Ethereum. +5. التطبيق اللامركزي يستعلم عن الـ Graph Node للبيانات المفهرسة من الـ blockchain ، باستخدام node's [ GraphQL endpoint](https://graphql.org/learn/). يقوم الـ The Graph Node بدوره بترجمة استعلامات الـ GraphQL إلى استعلامات مخزن البيانات الأساسي الخاص به من أجل جلب هذه البيانات ، والاستفادة من إمكانات فهرسة المخزن. التطبيق اللامركزي يعرض تلك البيانات في واجهة مستخدم ، والتي يمكن للمستخدمين من خلالها إصدار إجراءات جديدة على Ethereum. والدورة تتكرر. -## Next Steps +## الخطوات التالية -In the following sections we will go into more detail on how to define subgraphs, how to deploy them, and how to query data from the indexes that Graph Node builds. +في الأقسام التالية سوف نخوض في المزيد من التفاصيل حول كيفية تعريف الـ subgraphs ، وكيفية نشرها ،وكيفية الاستعلام عن البيانات من الفهارس التي يبنيها الـ Graph Node. -Before you start writing your own subgraph, you might want to have a look at the Graph Explorer and explore some of the subgraphs that have already been deployed. The page for each subgraph contains a playground that lets you query that subgraph's data with GraphQL. +قبل أن تبدأ في كتابة الـ subgraph الخاص بك ، قد ترغب في إلقاء نظرة على The Graph Explorer واستكشاف بعض الـ subgraphs التي تم نشرها. تحتوي الصفحة الخاصة بكل subgraph على playground والذي يتيح لك الاستعلام عن بيانات الـ subgraph باستخدام GraphQL. diff --git a/pages/ar/about/network.mdx b/pages/ar/about/network.mdx index b19f08d12bc7..7b0c538514ce 100644 --- a/pages/ar/about/network.mdx +++ b/pages/ar/about/network.mdx @@ -1,15 +1,15 @@ --- -title: Network Overview +title: نظرة عامة حول الشبكة --- -The Graph Network is a decentralized indexing protocol for organizing blockchain data. Applications use GraphQL to query open APIs called subgraphs, to retrieve data that is indexed on the network. With The Graph, developers can build serverless applications that run entirely on public infrastructure. +شبكة The Graph هو بروتوكول فهرسة لامركزي لتنظيم بيانات الـ blockchain. التطبيقات تستخدم GraphQL للاستعلام عن APIs المفتوحة والتي تسمى subgraphs ، لجلب البيانات المفهرسة على الشبكة. باستخدام The Graph ، يمكن للمطورين إنشاء تطبيقات بدون خادم تعمل بالكامل على البنية الأساسية العامة. -> GRT Token Address: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) +> عنوان GRT Token: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) -## Overview +## نظره عامة -The Graph Network consists of Indexers, Curators and Delegators that provide services to the network, and serve data to Web3 applications. Consumers use the applications and consume the data. +شبكة TheGraph تتكون من مفهرسين (Indexers) ومنسقين (Curators) ومفوضين (Delegator) حيث يقدمون خدمات للشبكة ويقدمون البيانات لتطبيقات Web3. حيث يتم استخدام تلك التطبيقات والبيانات من قبل المستهلكين. ![Token Economics](/img/Network-roles@2x.png) -To ensure economic security of The Graph Network and the integrity of data being queried, participants stake and use Graph Tokens (GRT). GRT is a work token that is an ERC-20 on the Ethereum blockchain, used to allocate resources in the network. Active Indexers, Curators and Delegators can provide services and earn income from the network, proportional to the amount of work they perform and their GRT stake. +لضمان الأمن الاقتصادي لشبكة The Graph وسلامة البيانات التي يتم الاستعلام عنها ، يقوم المشاركون بـ stake لـ Graph Tokens (GRT). GRT رمزه ERC-20 على Ethereum blockchain ، يستخدم لمحاصصة (allocate) الموارد في الشبكة. المفوضون والمنسقون والمفهرسون النشطون يقدمون الخدمات لذلك يمكنهم الحصول على عوائد من الشبكة ، بما يتناسب مع حجم العمل الذي يؤدونه وحصة GRT الخاصة بهم. diff --git a/pages/ar/curating.mdx b/pages/ar/curating.mdx index b13e20525f2f..6e37a8776a6f 100644 --- a/pages/ar/curating.mdx +++ b/pages/ar/curating.mdx @@ -100,5 +100,5 @@ title: (التنسيق) curating title="مشغل فيديو يوتيوب" frameBorder="0" allowFullScreen - > +> diff --git a/pages/ar/delegating.mdx b/pages/ar/delegating.mdx index 3a0d55f8363d..207be3e2a948 100644 --- a/pages/ar/delegating.mdx +++ b/pages/ar/delegating.mdx @@ -28,7 +28,9 @@ This guide will explain how to be an effective delegator in the Graph Network. D يجب اختيار المفهرس بحكمة. إذا اخترت مفهرسا ليس جديرا بالثقة ، أو لا يقوم بعمل جيد ، فستحتاج إلى إلغاء التفويض ، مما يعني أنك ستفقد الكثير من الفرص لكسب المكافآت والتي يمكن أن تكون سيئة مثل حرق GRT. -
لاحظ 0.5٪ رسوم التفويض ، بالإضافة إلى فترة 28 يوما لإلغاء التفويض.
+
+ لاحظ 0.5٪ رسوم التفويض ، بالإضافة إلى فترة 28 يوما لإلغاء التفويض. +
### اختيار مفهرس جدير بالثقة مع عائد جيد للمفوضين @@ -86,5 +88,5 @@ Using this formula, we can see that it is actually possible for an indexer who i title="مشغل فيديو يوتيوب" frameBorder="0" allowFullScreen - > +> diff --git a/pages/ar/developer/assemblyscript-api.mdx b/pages/ar/developer/assemblyscript-api.mdx index 2b6aa855c4a3..8e73bb511c90 100644 --- a/pages/ar/developer/assemblyscript-api.mdx +++ b/pages/ar/developer/assemblyscript-api.mdx @@ -2,25 +2,25 @@ title: AssemblyScript API --- -> Note: if you created a subgraph prior to `graph-cli`/`graph-ts` version `0.22.0`, you're using an older version of AssemblyScript, we recommend taking a look at the [`Migration Guide`](/developer/assemblyscript-migration-guide) +> ملاحظة: إذا أنشأت رسمًا فرعيًا قبل إصدار `graph-cli` / `graph-ts` `0.22.0` ، فأنت تستخدم إصدارًا أقدم من AssemblyScript ، نوصي بإلقاء نظرة على [ `دليل الترحيل` ](/developer/assemblyscript-migration-guide) -This page documents what built-in APIs can be used when writing subgraph mappings. Two kinds of APIs are available out of the box: +هذه الصفحة توثق APIs المضمنة التي يمكن استخدامها عند كتابة subgraph mappings. Two kinds of APIs are available out of the box: -- the [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) and -- code generated from subgraph files by `graph codegen`. +- مكتبة Graph TypeScript(`graph-ts`) +- كود تم إنشاؤه من ملفات الـ subgraph بواسطة `graph codegen`. -It is also possible to add other libraries as dependencies, as long as they are compatible with [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Since this is the language mappings are written in, the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) is a good source for language and standard library features. +من الممكن أيضا إضافة مكتبات أخرى مثل dependencies، طالما أنها متوافقة مع [ AssemblyScript ](https://github.com/AssemblyScript/assemblyscript). Since this is the language mappings are written in, the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) is a good source for language and standard library features. -## Installation +## التثبيت -Subgraphs created with [`graph init`](/developer/create-subgraph-hosted) come with preconfigured dependencies. All that is required to install these dependencies is to run one of the following commands: +الـ Subgraphs التي تم إنشاؤها باستخدام [ `graph init` ](/developer/create-subgraph-hosted) تأتي مع dependencies مكونة مسبقا. كل ما هو مطلوب لتثبيت هذه الـ dependencies هو تشغيل أحد الأوامر التالية: ```sh yarn install # Yarn npm install # NPM ``` -If the subgraph was created from scratch, one of the following two commands will install the Graph TypeScript library as a dependency: +إذا تم إنشاء الـ subgraph من البداية ، فسيقوم أحد الأمرين التاليين بتثبيت مكتبة Graph TypeScript كـ dependency: ```sh yarn add --dev @graphprotocol/graph-ts # Yarn @@ -29,33 +29,33 @@ npm install --save-dev @graphprotocol/graph-ts # NPM ## API Reference -The `@graphprotocol/graph-ts` library provides the following APIs: +توفر مكتبة `graphprotocol / graph-ts@` الـ APIs التالية: -- An `ethereum` API for working with Ethereum smart contracts, events, blocks, transactions, and Ethereum values. -- A `store` API to load and save entities from and to the Graph Node store. -- A `log` API to log messages to the Graph Node output and the Graph Explorer. -- An `ipfs` API to load files from IPFS. -- A `json` API to parse JSON data. -- A `crypto` API to use cryptographic functions. +- واجهة برمجة تطبيقات `ethereum` للعمل مع عقود Ethereum الذكية والأحداث والكتل والإجراات وقيم Ethereum. +- واجهة برمجة تطبيقات `store` لتحميل الـ entities وحفظها من وإلى مخزن Graph Node. +- واجهة برمجة تطبيقات ` log` لتسجيل الرسائل إلى خرج Graph Node ومستكشف Graph Explorer. +- واجهة برمجة تطبيقات `ipfs` لتحميل الملفات من IPFS. +- واجهة برمجة تطبيقات `json` لتحليل بيانات JSON. +- واجهة برمجة تطبيقات ` crypto` لاستخدام وظائف التشفير. - Low-level primitives to translate between different type systems such as Ethereum, JSON, GraphQL and AssemblyScript. -### Versions +### إصدارات -The `apiVersion` in the subgraph manifest specifies the mapping API version which is run by Graph Node for a given subgraph. The current mapping API version is 0.0.6. +الـ `apiVersion` في الـ subgraph manifest تحدد إصدار الـ mapping API الذي يتم تشغيله بواسطة Graph Node للـ subgraph المحدد. الاصدار الحالي لـ mapping API هو 0.0.6. -| Version | Release notes | +| الاصدار | ملاحظات الإصدار | | :-: | --- | -| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | -| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | -| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | -| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | -| 0.0.2 | Added `input` field to the Ethereum Transaction object | +| 0.0.6 | تمت إضافة حقل `nonce` إلى كائن إجراء الـ Ethereum
تمت إضافة `baseFeePerGas` إلى كائن Ethereum Block | +| 0.0.5 | تمت ترقية AssemblyScript إلى الإصدار 0.19.10 (يرجى الاطلاع على [ `دليل الترحيل` ](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` أعيد تسميته إلى `ethereum.transaction.gasLimit` | +| 0.0.4 | تمت إضافة حقل `functionSignature` إلى كائن Ethereum SmartContractCall | +| 0.0.3 | تمت إضافةحقل `from` إلى كائن Ethereum Call
`etherem.call.address` تمت إعادة تسميته إلى `ethereum.call.to` | +| 0.0.2 | تمت إضافة حقل ` input` إلى كائن إجراء Ethereum | -### Built-in Types +### الأنواع المضمنة Built-in -Documentation on the base types built into AssemblyScript can be found in the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types). +يمكن العثور على الوثائق الخاصة بالأنواع الأساسية المضمنة في AssemblyScript في [ AssemblyScript wiki ](https://github.com/AssemblyScript/assemblyscript/wiki/Types). -The following additional types are provided by `@graphprotocol/graph-ts`. +يتم توفير الأنواع الإضافية التالية بواسطة `graphprotocol/graph-ts@`. #### ByteArray @@ -63,24 +63,24 @@ The following additional types are provided by `@graphprotocol/graph-ts`. import { ByteArray } from '@graphprotocol/graph-ts' ``` -`ByteArray` represents an array of `u8`. +تمثل `ByteArray` مصفوفة `u8`. _Construction_ - `fromI32(x: i32): ByteArray` - Decomposes `x` into bytes. -- `fromHexString(hex: string): ByteArray` - Input length must be even. Prefixing with `0x` is optional. +- `fromHexString(hex: string): ByteArray` - Input length must be even. البادئة بـ `0x` اختيارية. _Type conversions_ -- `toHexString(): string` - Converts to a hex string prefixed with `0x`. -- `toString(): string` - Interprets the bytes as a UTF-8 string. -- `toBase58(): string` - Encodes the bytes into a base58 string. -- `toU32(): u32` - Interprets the bytes as a little-endian `u32`. Throws in case of overflow. +- `toHexString (): string` - تحول إلى سلسلة سداسية عشرية مسبوقة بـ `0x`. +- `toString (): string` - تترجم البايت كسلسلة UTF-8. +- `toBase58 (): string` - ترميز البايت لسلسلة base58. +- `toU32 (): u32` - يترجم البايت كـ `u32` little-endian. Throws in case of overflow. - `toI32(): i32` - Interprets the byte array as a little-endian `i32`. Throws in case of overflow. _Operators_ -- `equals(y: ByteArray): bool` – can be written as `x == y`. +- `equals(y: ByteArray): bool` – يمكن كتابتها كـ `x == y`. #### BigDecimal @@ -88,30 +88,30 @@ _Operators_ import { BigDecimal } from '@graphprotocol/graph-ts' ``` -`BigDecimal` is used to represent arbitrary precision decimals. +يستخدم `BigDecimal` للتعبير عن الكسور العشرية. _Construction_ -- `constructor(bigInt: BigInt)` – creates a `BigDecimal` from an `BigInt`. -- `static fromString(s: string): BigDecimal` – parses from a decimal string. +- `constructor(bigInt: BigInt)` – يُنشئ `BigDecimal` من `BigInt`. +- `static fromString(s: string): BigDecimal` – يحلل من سلسلة عشرية. _Type conversions_ -- `toString(): string` – prints to a decimal string. +- `toString(): string` – يطبع سلسلة عشرية. _Math_ -- `plus(y: BigDecimal): BigDecimal` – can be written as `x + y`. -- `minus(y: BigDecimal): BigDecimal` – can be written as `x - y`. -- `times(y: BigDecimal): BigDecimal` – can be written as `x * y`. -- `div(y: BigDecimal): BigDecimal` – can be written as `x / y`. -- `equals(y: BigDecimal): bool` – can be written as `x == y`. -- `notEqual(y: BigDecimal): bool` – can be written as `x != y`. -- `lt(y: BigDecimal): bool` – can be written as `x < y`. -- `le(y: BigDecimal): bool` – can be written as `x <= y`. -- `gt(y: BigDecimal): bool` – can be written as `x > y`. -- `ge(y: BigDecimal): bool` – can be written as `x >= y`. -- `neg(): BigDecimal` - can be written as `-x`. +- `plus(y: BigDecimal): BigDecimal` – يمكن كتابتها كـ `x + y`. +- `minus(y: BigDecimal): BigDecimal` – يمكن كتابتها كـ `x - y`. +- `times(y: BigDecimal): BigDecimal` – يمكن كتابتها كـ `x * y`. +- `div(y: BigDecimal): BigDecimal` – يمكن كتابتها كـ`x / y`. +- `equals(y: BigDecimal): bool` – يمكن كتابتها كـ `x == y`. +- `notEqual(y: BigDecimal): bool` –يمكن كتابتها كـ `x != y`. +- `lt(y: BigDecimal): bool` – يمكن كتابتها كـ `x < y`. +- `le(y: BigDecimal): bool` – يمكن كتابتها كـ `x <= y`. +- `gt(y: BigDecimal): bool` – يمكن كتابتها كـ `x > y`. +- `ge(y: BigDecimal): bool` – يمكن كتابتها كـ `x >= y`. +- `neg(): BigDecimal` - يمكن كتابتها كـ `-x`. #### BigInt @@ -119,47 +119,48 @@ _Math_ import { BigInt } from '@graphprotocol/graph-ts' ``` -`BigInt` is used to represent big integers. This includes Ethereum values of type `uint32` to `uint256` and `int64` to `int256`. Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. +يستخدم `BigInt` لتمثيل أعداد صحيحة كبيرة. يتضمن ذلك قيم Ethereum من النوع `uint32` إلى `uint256` و `int64` إلى `int256`. كل شيء أدناه `uint32` ، مثل `int32` أو `uint24` أو `int8` يتم تمثيله كـ `i32`. -The `BigInt` class has the following API: +تحتوي فئة `BigInt` على API التالية: _Construction_ -- `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32`. -- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string. -- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interprets `bytes` as an unsigned, little-endian integer. If your input is big-endian, call `.reverse()` first. -- `BigInt.fromSignedBytes(x: Bytes): BigInt` – Interprets `bytes` as a signed, little-endian integer. If your input is big-endian, call `.reverse()` first. +- `BigInt.fromI32 (x: i32): BigInt` - ينشئ `BigInt` من `i32`. +- `BigInt.fromString(s: string): BigInt`– يحلل `BigInt` من سلسلة(string). +- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – يترجم `bytes` باعتباره عددا صحيحا little-endian بدون إشارة. إذا كان الإدخال الخاص بك big-endian، فقم باستدعاء `.()reverse ` أولا. +- `BigInt.fromSignedBytes(x: Bytes): BigInt` – يترجم `bytes` باعتباره عددا صحيحا little-endian له إشارة. إذا كان الإدخال الخاص بك big-endian، فاستدعي `.()reverse ` أولا. _Type conversions_ -- `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.toBigDecimal(): BigDecimal` - converts into a decimal with no fractional part. +- `x.toHex(): string` – ترجع `BigInt` إلى سلسلة سداسية العشرية. + +- `x.toString (): string` - يحول `BigInt` إلى سلسلة رقم عشري. +- `x.toI32 (): i32` - ترجع `BigInt` كـ `i32` ؛ تفشل إذا كانت القيمة لا تتناسب مع `i32`. إنها لفكرة جيدة أن تتحقق أولا من `()x.isI32`. +- `x.toBigDecimal (): BigDecimal` - يحول إلى رقم عشري بدون جزء كسري. _Math_ -- `x.plus(y: BigInt): BigInt` – can be written as `x + y`. -- `x.minus(y: BigInt): BigInt` – can be written as `x - y`. -- `x.times(y: BigInt): BigInt` – can be written as `x * y`. -- `x.div(y: BigInt): BigInt` – can be written as `x / y`. -- `x.mod(y: BigInt): BigInt` – can be written as `x % y`. -- `x.equals(y: BigInt): bool` – can be written as `x == y`. -- `x.notEqual(y: BigInt): bool` – can be written as `x != y`. -- `x.lt(y: BigInt): bool` – can be written as `x < y`. -- `x.le(y: BigInt): bool` – can be written as `x <= y`. -- `x.gt(y: BigInt): bool` – can be written as `x > y`. -- `x.ge(y: BigInt): bool` – can be written as `x >= y`. -- `x.neg(): BigInt` – can be written as `-x`. -- `x.divDecimal(y: BigDecimal): BigDecimal` – divides by a decimal, giving a decimal result. -- `x.isZero(): bool` – Convenience for checking if the number is zero. -- `x.isI32(): bool` – Check if the number fits in an `i32`. -- `x.abs(): BigInt` – Absolute value. -- `x.pow(exp: u8): BigInt` – Exponentiation. -- `bitOr(x: BigInt, y: BigInt): BigInt` – can be written as `x | y`. -- `bitAnd(x: BigInt, y: BigInt): BigInt` – can be written as `x & y`. -- `leftShift(x: BigInt, bits: u8): BigInt` – can be written as `x << y`. -- `rightShift(x: BigInt, bits: u8): BigInt` – can be written as `x >> y`. +- `x.plus(y: BigInt): BigInt` – يمكن كتابتها كـ `x + y`. +- `x.minus(y: BigInt): BigInt` – يمكن كتابتها كـ `x - y`. +- `x.times(y: BigInt): BigInt` – يمكن كتابتها كـ `x * y`. +- `x.div(y: BigInt): BigInt` – يمكن كتابتها كـ `x / y`. +- `x.mod(y: BigInt): BigInt` – يمكن كتابتها كـ `x % y`. +- `x.equals(y: BigInt): bool` – يمكن كتابتها كـ `x == y`. +- `x.notEqual(y: BigInt): bool` –يمكن كتابتها كـ `x != y`. +- `x.lt(y: BigInt): bool` – يمكن كتابتها كـ `x < y`. +- `x.le(y: BigInt): bool` – يمكن كتابتها كـ `x <= y`. +- `x.gt(y: BigInt): bool` – يمكن كتابتها كـ `x > y`. +- `x.ge(y: BigInt): bool` – يمكن كتابتها كـ `x >= y`. +- `x.neg(): BigInt` – يمكن كتابتها كـ `-x`. +- `x.divDecimal (y: BigDecimal): BigDecimal` - يتم القسمة على عدد عشري ، مما يعطي نتيجة عشرية. +- `x.isZero(): bool` – ملائم للتحقق مما إذا كان الرقم صفرا. +- `x.isI32(): bool` – يتحقق مما إذا كان الرقم يناسب `i32`. +- `x.abs(): BigInt` – قيمة مطلقة. +- `x.pow(exp: u8): BigInt` – أس. +- `bitOr(x: BigInt, y: BigInt): BigInt` – يمكن كتابتها كـ `x | y`. +- `bitAnd(x: BigInt, y: BigInt): BigInt` – يمكن كتابتها كـ `x & y`. +- `leftShift(x: BigInt, bits: u8): BigInt` –يمكن كتابتها كـ `x << y`. +- `rightShift(x: BigInt, bits: u8): BigInt` – يمكن كتابتها كـ `x >> y`. #### TypedMap @@ -167,15 +168,15 @@ _Math_ import { TypedMap } from '@graphprotocol/graph-ts' ``` -`TypedMap` can be used to stored key-value pairs. See [this example](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). +يمكن استخدام `TypedMap` لتخزين أزواج key-value. انظر [هذا المثال ](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). -The `TypedMap` class has the following 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` +- `map.set (key: K، value: V): void` - يضبط قيمة الـ `key` لـ `value` - `map.getEntry(key: K): TypedMapEntry | null` – returns the key-value pair for a `key` or `null` if the `key` does not exist in the map -- `map.get(key: K): V | null` – returns the value for a `key` or `null` if the `key` does not exist in the map -- `map.isSet(key: K): bool` – returns `true` if the `key` exists in the map and `false` if it does not +- `map.get(key: K): V | null` – يرجع قيمة ` key` أو `null` إذا كان المفتاح ` ` غير موجود في الخريطة +- `map.isSet(key: K): bool` – يرجع `true` إذا كان الـ `key` موجودا في الخريطة و `false` إذا كان غير موجود #### Bytes @@ -183,13 +184,13 @@ The `TypedMap` class has the following API: import { Bytes } from '@graphprotocol/graph-ts' ``` -`Bytes` is used to represent arbitrary-length arrays of bytes. This includes Ethereum values of type `bytes`, `bytes32` etc. +يتم استخدام ` Bytes` لتمثيل مصفوفات طول عشوائية من البايتات. يتضمن ذلك قيم إيثريوم من النوع ` bytes` و ` bytes32` وما إلى ذلك. -The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) and this supports all the `Uint8Array` functionality, plus the following new methods: +فئة `Bytes` ترث من [ Uint8Array ](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) و لذا فهو يدعم جميع وظائف `Uint8Array` ، بالإضافة إلى الـ methods الجديدة التالية: -- `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()` – ترع سلسلة سداسية عشرية تمثل الـ bytes في المصفوفة +- `b.toString()` – يحول الـ bytes في المصفوفة إلى سلسلة من unicode +- `b.toBase58()` – يحول قيمة Ethereum Bytes إلى ترميز base58 (يستخدم لـ IPFS hashes) #### Address @@ -197,11 +198,11 @@ The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/Assem import { Address } from '@graphprotocol/graph-ts' ``` -`Address` extends `Bytes` to represent Ethereum `address` values. +` Address` امتداد لـ` Bytes` لتمثيل قيم Ethereum ` address`. -It adds the following method on top of the `Bytes` API: +إنها تضيف الـ method التالية أعلىAPI الـ `Bytes`: -- `Address.fromString(s: string): Address` – creates an `Address` from a hexadecimal string +- `Address.fromString(s: string): Address` – ينشئ `Address` من سلسلة سداسية عشرية ### Store API @@ -209,13 +210,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. +تسمح واجهة برمجة التطبيقات `store` بتحميل وحفظ وإزالة الكيانات من وإلى مخزن 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. +Entities written to the store map one-to-one to the `@entity` types defined in the subgraph's GraphQL schema. لتسهيل العمل مع هذه الكيانات ، فالأمر `graph codegen` المقدم بواسطة [ Graph CLI ](https://github.com/graphprotocol/graph-cli) ينشئ فئات الكيان ، وهي فئات فرعية من النوع المضمن ` Entity` ، مع خصائص getters و setters للحقول في المخطط بالإضافة إلى methods لتحميل هذه الكيانات وحفظها. -#### Creating entities +#### إنشاء الكيانات -The following is a common pattern for creating entities from Ethereum events. +ما يلي هو نمط شائع لإنشاء كيانات من أحداث Ethereum. ```typescript // Import the Transfer event class generated from the ERC20 ABI @@ -241,13 +242,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` أثناء معالجة السلسلة ، يتم تمريره إلى معالج الحدث `handleTransfer` باستخدام نوع ` Transfer` المولدة (الاسم المستعار هنا لـ `TransferEvent` لتجنب تعارض التسمية مع نوع الكيان). يسمح هذا النوع بالوصول إلى البيانات مثل الإجراء الأصلي للحدث وبارامتراته. -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 فريد لتجنب التضارب مع الكيانات الأخرى. من الشائع إلى حد ما أن تتضمن بارامترات الأحداث معرفا فريدا يمكن استخدامه. ملاحظة: استخدام hash الـ الإجراء كـ ID يفترض أنه لا توجد أحداث أخرى في نفس الإجراء تؤدي إلى إنشاء كيانات بهذا الـ hash كـ ID. -#### Loading entities from the store +#### تحميل الكيانات من المخزن -If an entity already exists, it can be loaded from the store with the following: +إذا كان الكيان موجودا بالفعل ، فيمكن تحميله من المخزن بالتالي: ```typescript let id = event.transaction.hash.toHex() // or however the ID is constructed @@ -259,18 +260,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. +نظرا لأن الكيان قد لا يكون موجودا في المتجر ، فإن method `load` تُرجع قيمة من النوع ` Transfer | null`. وبالتالي قد يكون من الضروري التحقق من حالة `null` قبل استخدام القيمة. -> **Note:** Loading entities is only necessary if the changes made in the mapping depend on the previous data of an entity. See the next section for the two ways of updating existing entities. +> ** ملاحظة: ** تحميل الكيانات ضروري فقط إذا كانت التغييرات التي تم إجراؤها في الـ mapping تعتمد على البيانات السابقة للكيان. انظر القسم التالي للتعرف على الطريقتين لتحديث الكيانات الموجودة. -#### Updating existing entities +#### تحديث الكيانات الموجودة -There are two ways to update an existing entity: +هناك طريقتان لتحديث كيان موجود: -1. Load the entity with e.g. `Transfer.load(id)`, set properties on the entity, then `.save()` it back to the store. -2. Simply create the entity with e.g. `new Transfer(id)`, set properties on the entity, then `.save()` it to the store. If the entity already exists, the changes are merged into it. +1. حمل الكيان بـ `Transfer.load (id)` على سبيل المثال، قم بتعيين الخصائص على الكيان ، ثم `()save.` للمخزن. +2. ببساطة أنشئ الكيان بـ ` new Transfer(id)` على سبيل المثال، قم بتعيين الخصائص على الكيان ، ثم `()save.` للمخزن. إذا كان الكيان موجودا بالفعل ، يتم دمج التغييرات فيه. -Changing properties is straight forward in most cases, thanks to the generated property setters: +يتم تغيير الخصائص بشكل مباشر في معظم الحالات ، وذلك بفضل خاصية الـ setters التي تم إنشاؤها: ```typescript let transfer = new Transfer(id) @@ -279,16 +280,16 @@ transfer.to = ... transfer.amount = ... ``` -It is also possible to unset properties with one of the following two instructions: +من الممكن أيضا إلغاء الخصائص بإحدى التعليمات التالية: ```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` به حقل `أرقام: [BigInt!]!`. ```typescript // This won't work @@ -302,28 +303,28 @@ entity.numbers = numbers entity.save() ``` -#### Removing entities from the 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`: +لا توجد حاليا طريقة لإزالة كيان عبر الأنواع التي تم إنشاؤها. بدلاً من ذلك ، تتطلب إزالة الكيان تمرير اسم نوع الكيان و ID الكيان إلى `store.remove`: ```typescript import { store } from '@graphprotocol/graph-ts' ... -let id = event.transaction.hash.toHex() +()let id = event.transaction.hash.toHex 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. -#### Support for Ethereum Types +#### دعم أنواع الإيثيريوم -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` ينشئ فئات لجميع العقود الذكية والأحداث المستخدمة في الـ subgraph. لهذا ، يجب أن يكون ABI العقد جزءا من مصدر البيانات في subgraph manifest. عادة ما يتم تخزين ملفات 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) خلف الكواليس بحيث لا يضطر منشؤوا الـ subgraph إلى القلق بشأنها. -The following example illustrates this. Given a subgraph schema like +يوضح المثال التالي هذا. مخطط subgraph معطى مثل ```graphql type Transfer @entity { @@ -333,7 +334,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: +و توقيع الحدث `Transfer(address,address,uint256)` على Ethereum ، قيم ` from` ، ` to` و `amount` من النوع `address` و `address` و `uint256` يتم تحويلها إلى `Address` و `BigInt` ، مما يسمح بتمريرها إلى خصائص `!Bytes ` و `!BigInt ` للكيان `Transfer`: ```typescript let id = event.transaction.hash.toHex() @@ -344,9 +345,9 @@ transfer.amount = event.params.amount transfer.save() ``` -#### Events and Block/Transaction Data +#### الأحداث وبيانات الكتلة/ الإجراء -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`): +أحداث Ethereum التي تم تمريرها إلى معالجات الأحداث ، مثل حدث `Transfer` في الأمثلة السابقة ، لا توفر فقط الوصول إلى بارامترات الحدث ولكن أيضا إلى الإجراء الأصلي والكتلة التي تشكل جزءا منها. يمكن الحصول على البيانات التالية من `event` instances (هذه الفئات هي جزء من وحدة الـ `ethereum` في `graph-ts`): ```typescript class Event { @@ -390,11 +391,11 @@ class Transaction { } ``` -#### Access to Smart Contract State +#### الوصول إلى حالة العقد الذكي Smart Contract -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` على فئات للعقود الذكية المستخدمة في الـ subgraph. يمكن استخدامها للوصول إلى متغيرات الحالة العامة واستدعاء دوال العقد في الكتلة الحالية. -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 @@ -411,13 +412,13 @@ 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. +طالما أن `ERC20Contract` في الـ Ethereum له دالة عامة للقراءة فقط تسمى ` symbol` ، فيمكن استدعاؤها بـ `()symbol.`. بالنسبة لمتغيرات الحالة العامة ، يتم إنشاء method بنفس الاسم تلقائيا. -Any other contract that is part of the subgraph can be imported from the generated code and can be bound to a valid address. +أي عقد آخر يمثل جزءا من الـ subgraph يمكن استيراده من الكود الذي تم انشاؤه ويمكن ربطه بعنوان صالح. #### Handling Reverted Calls -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: +إذا كان من الممكن التراجع عن methods القراءة فقط لعقدك ، فيجب عليك التعامل مع ذلك عن طريق استدعاء method العقد التي تم انشاؤها والمسبوقة بـ على سبيل المثال ، يكشف عقد Gravity عن method `gravatarToOwner`. سيكون هذا الكود قادرا على معالجة التراجع في ذلك الـ method: ```typescript let gravity = Gravity.bind(event.address) @@ -429,11 +430,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. +لاحظ أن Graph node المتصلة بعميل Geth أو Infura قد لا تكتشف جميع المرتجعات ، إذا كنت تعتمد على ذلك ، فإننا نوصي باستخدام Graph node المتصلة بعميل Parity. #### Encoding/Decoding ABI -Data can be encoded and decoded according to Ethereum's ABI encoding format using the `encode` and `decode` functions in the `ethereum` module. +يمكن تشفير البيانات وفك تشفيرها وفقا لتنسيق تشفير ABI الـ Ethereum باستخدام دالتي `encode` و `decode` في الوحدة الـ `ethereum`. ```typescript import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts' @@ -450,11 +451,11 @@ 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) -- More [complex example](https://github.com/graphprotocol/graph-node/blob/6a7806cc465949ebb9e5b8269eeb763857797efc/tests/integration-tests/host-exports/src/mapping.ts#L72). +- تشفير/فك تشفير [Rust library/CLI](https://github.com/rust-ethereum/ethabi) +- [أمثلة معقدة](https://github.com/graphprotocol/graph-node/blob/6a7806cc465949ebb9e5b8269eeb763857797efc/tests/integration-tests/host-exports/src/mapping.ts#L72) أكثر. ### Logging API @@ -462,17 +463,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. +تسمح واجهة برمجة التطبيقات `log` لـ subgraphs بتسجيل المعلومات إلى الخرج القياسي لـ Graph Node بالإضافة إلى Graph Explorer. يمكن تسجيل الرسائل باستخدام مستويات سجل مختلفة. بنية سلسلة التنسيق الأساسي يتم توفيرها لتكوين رسائل السجل من argument. -The `log` API includes the following functions: +تتضمن واجهة برمجة التطبيقات `log` الدوال التالية: -- `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` - تسجل رسالة debug. +- `log.info(fmt: string, args: Array): void` - تسجل رسالة اعلامية. +- `log.warning(fmt: string, args: Array): void` - تسجل تحذير. +- `log.error(fmt: string, args: Array): void` - تسجل رسالة خطأ. +- `log.critical(fmt: string, args: Array): void` – تسجل رسالة حرجة _و_ وتنهي الـ 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` تأخذ تنسيق string ومصفوفة من قيم string. ثم يستبدل placeholders بقيم string من المصفوفة. يتم استبدال placeholder `{}` الأول بالقيمة الأولى في المصفوفة ، ويتم استبدال placeholder `{}` الثاني بالقيمة الثانية وهكذا. ```typescript log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue.toString(), 'already a string']) @@ -482,7 +483,7 @@ log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue. ##### Logging a single value -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' @@ -495,7 +496,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### Logging a single entry from an existing array -In the example below, only the first value of the argument array is logged, despite the array containing three values. +في المثال أدناه ، يتم تسجيل القيمة الأولى فقط لـ argument المصفوفة، على الرغم من احتواء المصفوفة على ثلاث قيم. ```typescript let myArray = ['A', 'B', 'C'] @@ -508,7 +509,7 @@ export function handleSomeEvent(event: SomeEvent): void { #### Logging multiple entries from an existing array -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. +يتطلب كل إدخال في arguments المصفوفة placeholder خاص به `{}` في سلسلة رسالة السجل. يحتوي المثال أدناه على ثلاثة placeholders `{}` في رسالة السجل. لهذا السبب ، يتم تسجيل جميع القيم الثلاث في `myArray`. ```typescript let myArray = ['A', 'B', 'C'] @@ -521,7 +522,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### Logging a specific entry from an existing array -To display a specific value in the array, the indexed value must be provided. +لعرض قيمة محددة في المصفوفة ، يجب توفير القيمة المفهرسة. ```typescript export function handleSomeEvent(event: SomeEvent): void { @@ -532,7 +533,7 @@ export function handleSomeEvent(event: SomeEvent): void { ##### Logging event information -The example below logs the block number, block hash and transaction hash from an event: +يسجل المثال أدناه رقم الكتلة و hash الكتلة و hash الإجراء من حدث: ```typescript import { log } from '@graphprotocol/graph-ts' @@ -552,9 +553,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. +تقوم العقود الذكية أحيانا بإرساء ملفات IPFS على السلسلة. يسمح هذا للـ mappings بالحصول على IPFS hashes من العقد وقراءة الملفات المقابلة من IPFS. سيتم إرجاع بيانات الملف كـ ` Bytes` ، والتي تتطلب عادة مزيدا من المعالجة ، على سبيل المثال مع واجهة برمجة التطبيقات `json` الموثقة لاحقا في هذه الصفحة. -Given an IPFS hash or path, reading a file from IPFS is done as follows: +IPFS hash أو مسار معطى، تتم قراءة ملف من IPFS على النحو التالي: ```typescript // Put this inside an event handler in the mapping @@ -567,9 +568,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](/developer/create-subgraph-hosted#ipfs-pinning) section for more information. +** ملاحظة: ** `ipfs.cat` ليست إجبارية في الوقت الحالي. لهذا السبب ، من المفيد دائما التحقق من نتيجة `null`. إذا تعذر استرداد الملف عبر شبكة Ipfs قبل انتهاء مهلة الطلب ، فسيعود `null`. لضمان إمكانية استرداد الملفات ، يجب تثبيتها في IPFS node التي تتصل بها Graph Node. على [الخدمة المستضافة ](https://thegraph.com/hosted-service) ، هذا هو [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs/). راجع قسم [تثبيت IPFS](/developer/create-subgraph-hosted#ipfs-pinning) لمزيد من المعلومات. -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`. تتوقع الدالة الـ hash أو مسارا لملف IPFS واسم الـ callback والـ flags لتعديل سلوكه: ```typescript import { JSONValue, Value } from '@graphprotocol/graph-ts' @@ -599,9 +600,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. +الـ flag الوحيد المدعوم حاليا هو `json` ، والذي يجب تمريره إلى `ipfs.map`. باستخدام flag الـ `json` ، يجب أن يتكون ملف IPFS من سلسلة من قيم JSON ، قيمة واحدة لكل سطر. سيؤدي استدعاء `ipfs.map` إلى قراءة كل سطر في الملف ، وإلغاء تسلسله إلى `JSONValue` واستدعاء الـ callback لكل منها. يمكن لـ callback بعد ذلك استخدام عمليات الكيان لتخزين البيانات من `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`. إذا تسبب أي استدعاء لـ callback في حدوث خطأ ، فسيتم إحباط المعالج الذي استدعى `ipfs.map` ، ويتم وضع علامة على الـ subgraph على أنه فشل. ### Crypto API @@ -609,7 +610,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: +توفر واجهة برمجة تطبيقات ` crypto` دوال التشفير للاستخدام في mappings. الآن ، يوجد واحد فقط: - `crypto.keccak256(input: ByteArray): ByteArray` @@ -619,14 +620,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: +يمكن تحليل بيانات JSON باستخدام `json` API: -- `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: Bytes): JSONValue` – parses JSON data from a valid UTF-8 `String` -- `json.try_fromString(data: Bytes): Result` – safe version of `json.fromString`, it returns an error variant if the parsing failed +- `json.fromBytes(data: Bytes): JSONValue` – يحول بيانات JSON من مصفوفة `Bytes` +- `json.try_fromBytes(data: Bytes): Result` – إصدار آمن من `json.fromBytes` ، يقوم بإرجاع متغير خطأ إذا فشل التحليل +- `json.fromString(data: Bytes): JSONValue` – يحلل بيانات JSON من UTF-8 `String` صالح +- `json.try_fromString(data: Bytes): 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(...) @@ -635,22 +636,22 @@ if (value.kind == JSONValueKind.BOOL) { } ``` -In addition, there is a method to check if the value is `null`: +بالإضافة إلى ذلك ، هناك method للتحقق مما إذا كانت القيمة ` 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) باستخدام إحدى الـ methods التالية: - `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` - (ثم قم بتحويل `JSONValue` بإحدى الـ methods الخمس المذكورة أعلاه) ### Type Conversions Reference -| Source(s) | Destination | Conversion function | +| المصدر(المصادر) | الغاية | دالة التحويل | | -------------------- | -------------------- | ---------------------------- | | Address | Bytes | none | | Address | ID | s.toHexString() | @@ -690,7 +691,7 @@ When the type of a value is certain, it can be converted to a [built-in type](#b ### Data Source Metadata -You can inspect the contract address, network and context of the data source that invoked the handler through the `dataSource` namespace: +يمكنك فحص عنوان العقد والشبكة وسياق مصدر البيانات الذي استدعى المعالج من خلال `dataSource` namespace: - `dataSource.address(): Address` - `dataSource.network(): string` @@ -698,7 +699,7 @@ You can inspect the contract address, network and context of the data source tha ### Entity and DataSourceContext -The base `Entity` class and the child `DataSourceContext` class have helpers to dynamically set and get fields: +تحتوي فئة `Entity` الأساسية والفئة الفرعية `DataSourceContext` على مساعدين لتعيين الحقول والحصول عليها ديناميكيا: - `setString(key: string, value: string): void` - `setI32(key: string, value: i32): void` diff --git a/pages/ar/developer/assemblyscript-migration-guide.mdx b/pages/ar/developer/assemblyscript-migration-guide.mdx index c63a1af95d7b..d0eba1f9a31a 100644 --- a/pages/ar/developer/assemblyscript-migration-guide.mdx +++ b/pages/ar/developer/assemblyscript-migration-guide.mdx @@ -1,50 +1,50 @@ --- -title: AssemblyScript Migration Guide +title: دليل ترحيل AssemblyScript --- -Up until now, subgraphs have been using one of the [first versions of AssemblyScript](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). Finally we've added support for the [newest one available](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉 +حتى الآن ، كانت ال Subgraphs تستخدم أحد [ الإصدارات الأولى من AssemblyScript ](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). أخيرًا ، أضفنا الدعم لـ [ أحدث دعم متاح ](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉 -That will enable subgraph developers to use newer features of the AS language and standard library. +سيمكن ذلك لمطوري ال Subgraph من استخدام مميزات أحدث للغة AS والمكتبة القياسية. -This guide is applicable for anyone using `graph-cli`/`graph-ts` below version `0.22.0`. If you're already at a higher than (or equal) version to that, you've already been using version `0.19.10` of AssemblyScript 🙂 +ينطبق هذا الدليل على أي شخص يستخدم `graph-cli`/`graph-ts` ادنى من الإصدار `0.22.0`. إذا كنت تستخدم بالفعل إصدارًا أعلى من (أو مساويًا) لذلك ، فأنت بالفعل تستخدم الإصدار ` 0.19.10 ` من AssemblyScript 🙂 -> Note: As of `0.24.0`, `graph-node` can support both versions, depending on the `apiVersion` specified in the subgraph manifest. +> ملاحظة: اعتبارًا من ` 0.24.0 ` ، يمكن أن يدعم ` grapg-node ` كلا الإصدارين ، اعتمادًا على ` apiVersion ` المحدد في Subgraph manifest. -## Features +## مميزات -### New functionality +### وظائف جديدة - `TypedArray`s can now be built from `ArrayBuffer`s by using the [new `wrap` static method](https://www.assemblyscript.org/stdlib/typedarray.html#static-members) ([v0.8.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.8.1)) -- New standard library functions: `String#toUpperCase`, `String#toLowerCase`, `String#localeCompare`and `TypedArray#set` ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Added support for x instanceof GenericClass ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) +- وظائف المكتبة القياسية الجديدة`String#toUpperCase`, `String#toLowerCase`, `String#localeCompare`and `TypedArray#set` ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- تمت إضافة دعم لـ x instanceof GenericClass ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) - Added `StaticArray`, a more efficient array variant ([v0.9.3](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.3)) -- Added `Array#flat` ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -- Implemented `radix` argument on `Number#toString` ([v0.10.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.1)) +- تمت إضافة`Array#flat` ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- تم تنفيذ`radix` argument on `Number#toString` ([v0.10.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.1)) - Added support for separators in floating point literals ([v0.13.7](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.13.7)) -- Added support for first class functions ([v0.14.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.0)) -- Add builtins: `i32/i64/f32/f64.add/sub/mul` ([v0.14.13](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.13)) -- Implement `Array/TypedArray/String#at` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) +- دعم إضافي لوظائف الدرجة الأولى ([ v0.14.0 ](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.0)) +- إضافة البناء: `i32/i64/f32/f64.add/sub/mul` ([v0.14.13](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.13)) +- تنفيذ `Array/TypedArray/String#at` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) - Added support for template literal strings ([v0.18.17](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.17)) -- Add `encodeURI(Component)` and `decodeURI(Component)` ([v0.18.27](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.27)) -- Add `toString`, `toDateString` and `toTimeString` to `Date` ([v0.18.29](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.29)) -- Add `toUTCString` for `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) -- Add `nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) +- أضف`encodeURI(Component)` و `decodeURI(Component)` ([v0.18.27](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.27)) +- أضف`toString`, `toDateString` و `toTimeString` ل `Date` ([v0.18.29](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.29)) +- أضف`toUTCString` ل `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) +- أضف`nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) -### Optimizations +### التحسينات -- `Math` functions such as `exp`, `exp2`, `log`, `log2` and `pow` have been replaced by faster variants ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Slightly optimize `Math.mod` ([v0.17.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.1)) +- `Math` دوال مثل `exp`, `exp2`, `log`, `log2` and `pow` تم استبدالها بمتغيرات أسرع ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- أكثر تحسينا `Math.mod` ([v0.17.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.1)) - Cache more field accesses in std Map and Set ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) -- Optimize for powers of two in `ipow32/64` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) +- قم بتحسين قدرات اثنين في ` ipow32 / 64 ` ([ v0.18.2 ](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) -### Other +### آخر -- The type of an array literal can now be inferred from its contents ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Updated stdlib to Unicode 13.0.0 ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- يمكن الآن استنتاج نوع array literal من محتوياتها([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- تم تحديث stdlib إلى Unicode 13.0.0([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -## How to upgrade? +## كيف تقوم بالترقية؟ -1. Change your mappings `apiVersion` in `subgraph.yaml` to `0.0.6`: +1. تغيير ال Mappings الخاص بك ` apiVersion ` في ` subgraph.yaml ` إلى ` 0.0.6 `: ```yaml ... @@ -56,7 +56,7 @@ dataSources: ... ``` -2. Update the `graph-cli` you're using to the `latest` version by running: +2. قم بتحديث ` graph-cli ` الذي تستخدمه إلى ` أحدث إصدار ` عن طريق تشغيل: ```bash # if you have it globally installed @@ -66,20 +66,20 @@ npm install --global @graphprotocol/graph-cli@latest npm install --save-dev @graphprotocol/graph-cli@latest ``` -3. Do the same for `graph-ts`, but instead of installing globally, save it in your main dependencies: +3. افعل الشيء نفسه مع ` graph-ts ` ، ولكن بدلاً من التثبيت بشكل عام ، احفظه في dependencies الرئيسية: ```bash npm install --save @graphprotocol/graph-ts@latest ``` 4. Follow the rest of the guide to fix the language breaking changes. -5. Run `codegen` and `deploy` again. +5. قم بتشغيل ` codegen ` و ` deploy` مرة أخرى. ## Breaking changes ### Nullability -On the older version of AssemblyScript, you could create code like this: +في الإصدار الأقدم من AssemblyScript ، يمكنك إنشاء كود مثل هذا: ```typescript function load(): Value | null { ... } @@ -88,7 +88,7 @@ let maybeValue = load(); maybeValue.aMethod(); ``` -However on the newer version, because the value is nullable, it requires you to check, like this: +ولكن في الإصدار الأحدث ، نظرًا لأن القيمة nullable ، فإنها تتطلب منك التحقق ، مثل هذا: ```typescript let maybeValue = load() @@ -98,7 +98,7 @@ if (maybeValue) { } ``` -Or force it like this: +أو إجباره على هذا النحو: ```typescript let maybeValue = load()! // breaks in runtime if value is null @@ -106,7 +106,7 @@ let maybeValue = load()! // breaks in runtime if value is null maybeValue.aMethod() ``` -If you are unsure which to choose, we recommend always using the safe version. If the value doesn't exist you might want to just do an early if statement with a return in you subgraph handler. +إذا لم تكن متأكدًا من اختيارك ، فنحن نوصي دائمًا باستخدام الإصدار الآمن. If the value doesn't exist you might want to just do an early if statement with a return in you subgraph handler. ### Variable Shadowing @@ -118,7 +118,7 @@ let b = 20 let a = a + b ``` -However now this isn't possible anymore, and the compiler returns this error: +لكن هذا لم يعد ممكنًا الآن ، ويعيد المترجم هذا الخطأ: ```typescript ERROR TS2451: Cannot redeclare block-scoped variable 'a' @@ -127,12 +127,9 @@ ERROR TS2451: Cannot redeclare block-scoped variable 'a' ~~~~~~~~~~~~~ in assembly/index.ts(4,3) ``` - -You'll need to rename your duplicate variables if you had variable shadowing. - -### Null Comparisons - -By doing the upgrade on your subgraph, sometimes you might get errors like these: +ستحتاج إلى إعادة تسمية المتغيرات المكررة إذا كان لديك variable shadowing. +### مقارنات ملغية(Null Comparisons) +من خلال إجراء الترقية على ال Subgraph الخاص بك ، قد تحصل أحيانًا على أخطاء مثل هذه: ```typescript ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' is not assignable to type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt'. @@ -140,8 +137,7 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i ~~~~ in src/mappings/file.ts(41,21) ``` - -To solve you can simply change the `if` statement to something like this: +لحل المشكلة يمكنك ببساطة تغيير عبارة ` if ` إلى شيء مثل هذا: ```typescript if (!decimals) { @@ -151,23 +147,23 @@ To solve you can simply change the `if` statement to something like this: if (decimals === null) { ``` -The same applies if you're doing != instead of ==. +الأمر نفسه ينطبق إذا كنت تفعل! = بدلاً من ==. ### Casting -The common way to do casting before was to just use the `as` keyword, like this: +كانت الطريقة الشائعة لإجراء ال Casting من قبل هي استخدام `as`كلمة رئيسية ، مثل هذا: ```typescript let byteArray = new ByteArray(10) let uint8Array = byteArray as Uint8Array // equivalent to: byteArray ``` -However this only works in two scenarios: +لكن هذا لا يعمل إلا في سيناريوهين: -- Primitive casting (between types such as `u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); +- Primitive casting (بين انواع مثل`u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); - Upcasting on class inheritance (subclass → superclass) -Examples: +أمثلة: ```typescript // primitive casting @@ -183,10 +179,10 @@ class Bytes extends Uint8Array {} let bytes = new Bytes(2) < Uint8Array > bytes // same as: bytes as Uint8Array ``` -There are two scenarios where you may want to cast, but using `as`/`var` **isn't safe**: +هناك سيناريوهين قد ترغب في ال cast ، ولكن باستخدام`as`/`var` **ليس آمنا**: - Downcasting on class inheritance (superclass → subclass) -- Between two types that share a superclass +- بين نوعين يشتركان في فئة superclass ```typescript // downcasting on class inheritance @@ -203,7 +199,7 @@ class ByteArray extends Uint8Array {} let bytes = new Bytes(2) < ByteArray > bytes // breaks in runtime :( ``` -For those cases, you can use the `changetype` function: +في هذه الحالة يمكنك إستخدام`changetype` دالة: ```typescript // downcasting on class inheritance @@ -222,7 +218,7 @@ let bytes = new Bytes(2) changetype(bytes) // works :) ``` -If you just want to remove nullability, you can keep using the `as` operator (or `variable`), but make sure you know that value can't be null, otherwise it will break. +إذا كنت تريد فقط إزالة nullability ، فيمكنك الاستمرار في استخدام ` as ` (أو `variable`) ، ولكن تأكد من أنك تعرف أن القيمة لا يمكن أن تكون خالية ، وإلا فإنه سوف ينكسر. ```typescript // remove nullability @@ -235,23 +231,23 @@ if (previousBalance != null) { let newBalance = new AccountBalance(balanceId) ``` -For the nullability case we recommend taking a look at the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks), it will make your code cleaner 🙂 +بالنسبة لحالة ال nullability ، نوصي بإلقاء نظرة على [ مميزة التحقق من nullability ](https://www.assemblyscript.org/basics.html#nullability-checks) ، ستجعل الكود أكثر نظافة 🙂 -Also we've added a few more static methods in some types to ease casting, they are: +أضفنا أيضًا بعض ال static methods في بعض الأنواع وذلك لتسهيل عملية ال Casting ، وهي: - Bytes.fromByteArray - Bytes.fromUint8Array - BigInt.fromByteArray - ByteArray.fromBigInt -### Nullability check with property access +### التحقق من Nullability مع الوصول الى الخاصية -To use the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks) you can use either `if` statements or the ternary operator (`?` and `:`) like this: +لاستخدام [ مميزة التحقق من nullability ](https://www.assemblyscript.org/basics.html#nullability-checks) ، يمكنك استخدام عبارات ` if ` أو عامل التشغيل الثلاثي (`؟ ` and `: `) مثل هذا: ```typescript let something: string | null = 'data' -let somethingOrElse = something ? something : 'else' +let somethingOrElse = something ؟ something : 'else' // or @@ -264,7 +260,7 @@ if (something) { } ``` -However that only works when you're doing the `if` / ternary on a variable, not on a property access, like this: +ومع ذلك ، فإن هذا لا يعمل إلا عند تنفيذ ` if ` / ternary على متغير ، وليس على خاصية الوصول ، مثل هذا: ```typescript class Container { @@ -274,18 +270,17 @@ class Container { let container = new Container() container.data = 'data' -let somethingOrElse: string = container.data ? container.data : 'else' // doesn't compile +let somethingOrElse: string = container.data ؟ container.data : 'else' // doesn't compile ``` -Which outputs this error: +الذي يخرج هذا الخطأ: ```typescript ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/string/String'. - let somethingOrElse: string = container.data ? container.data : "else"; + let somethingOrElse: string = container.data ؟ container.data : "else"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` - To fix this issue, you can create a variable for that property access so that the compiler can do the nullability check magic: ```typescript @@ -298,10 +293,10 @@ container.data = 'data' let data = container.data -let somethingOrElse: string = data ? data : 'else' // compiles just fine :) +let somethingOrElse: string = data ؟ data : 'else' // compiles just fine :) ``` -### Operator overloading with property access +### التحميل الزائد للمشغل مع الوصول للخاصية If you try to sum (for example) a nullable type (from a property access) with a non nullable one, the AssemblyScript compiler instead of giving a compile time error warning that one of the values is nullable, it just compiles silently, giving chance for the code to break at runtime. @@ -327,7 +322,7 @@ let wrapper = new Wrapper(y) wrapper.n = wrapper.n + x // doesn't give compile time errors as it should ``` -We've opened a issue on the AssemblyScript compiler for this, but for now if you do these kind of operations in your subgraph mappings, you should change them to do a null check before it. +لقد فتحنا مشكلة في مترجم AssemblyScript ، ولكن في الوقت الحالي إذا أجريت هذا النوع من العمليات في Subgraph mappings ، فيجب عليك تغييرها لإجراء فحص ل null قبل ذلك. ```typescript let wrapper = new Wrapper(y) @@ -339,9 +334,9 @@ if (!wrapper.n) { wrapper.n = wrapper.n + x // now `n` is guaranteed to be a BigInt ``` -### Value initialization +### تهيئة القيمة -If you have any code like this: +إذا كان لديك أي كود مثل هذا: ```typescript var value: Type // null @@ -349,7 +344,7 @@ value.x = 10 value.y = 'content' ``` -It will compile but break at runtime, that happens because the value hasn't been initialized, so make sure your subgraph has initialized their values, like this: +سيتم تجميعها لكنها ستتوقف في وقت التشغيل ، وهذا يحدث لأن القيمة لم تتم تهيئتها ، لذا تأكد من أن ال subgraph قد قام بتهيئة قيمها ، على النحو التالي: ```typescript var value = new Type() // initialized @@ -357,7 +352,7 @@ value.x = 10 value.y = 'content' ``` -Also if you have nullable properties in a GraphQL entity, like this: +وأيضًا إذا كانت لديك خصائص ل nullable في كيان GraphQL ، مثل هذا: ```graphql type Total @entity { @@ -366,7 +361,7 @@ type Total @entity { } ``` -And you have code similar to this: +ولديك كود مشابه لهذا: ```typescript let total = Total.load('latest') @@ -378,7 +373,7 @@ if (total === null) { total.amount = total.amount + BigInt.fromI32(1) ``` -You'll need to make sure to initialize the `total.amount` value, because if you try to access like in the last line for the sum, it will crash. So you either initialize it first: +ستحتاج إلى التأكد من تهيئة`total.amount`القيمة ، لأنه إذا حاولت الوصول كما في السطر الأخير للمجموع ، فسوف يتعطل. لذلك إما أن تقوم بتهيئته أولاً: ```typescript let total = Total.load('latest') @@ -391,7 +386,7 @@ if (total === null) { total.tokens = total.tokens + BigInt.fromI32(1) ``` -Or you can just change your GraphQL schema to not use a nullable type for this property, then we'll initialize it as zero on the `codegen` step 😉 +أو يمكنك فقط تغيير مخطط GraphQL الخاص بك بحيث لا تستخدم نوع nullable لهذه الخاصية ، ثم سنقوم بتهيئته على أنه صفر في الخطوة`codegen`😉 ```graphql type Total @entity { @@ -410,9 +405,9 @@ if (total === null) { total.amount = total.amount + BigInt.fromI32(1) ``` -### Class property initialization +### تهيئة خاصية الفئة -If you export any classes with properties that are other classes (declared by you or by the standard library) like this: +إذا قمت بتصدير أي فئات ذات خصائص فئات أخرى (تم تعريفها بواسطتك أو بواسطة المكتبة القياسية) مثل هذا: ```typescript class Thing {} @@ -422,7 +417,7 @@ export class Something { } ``` -The compiler will error because you either need to add an initializer for the properties that are classes, or add the `!` operator: +فإن المترجم سيخطئ لأنك ستحتاج إما إضافة مُهيئ للخصائص التي هي فئات ، أو إضافة عامل التشغيل `! `: ```typescript export class Something { @@ -446,11 +441,11 @@ export class Something { } ``` -### GraphQL schema +### مخطط GraphQL -This is not a direct AssemblyScript change, but you may have to update your `schema.graphql` file. +هذا ليس تغيير مباشرا ل AssemblyScript ، ولكن قد تحتاج إلى تحديث ملف ` schema.graphql ` الخاص بك. -Now you no longer can define fields in your types that are Non-Nullable Lists. If you have a schema like this: +الآن لم يعد بإمكانك تعريف الحقول في الأنواع الخاصة بك والتي هي قوائم Non-Nullable. إذا كان لديك مخطط مثل هذا: ```graphql type Something @entity { @@ -463,7 +458,7 @@ type MyEntity @entity { } ``` -You'll have to add an `!` to the member of the List type, like this: +سيتعين عليك إضافة `! ` لعضو من نوع القائمة ، مثل هذا: ```graphql type Something @entity { @@ -476,14 +471,14 @@ type MyEntity @entity { } ``` -This changed because of nullability differences between AssemblyScript versions, and it's related to the `src/generated/schema.ts` file (default path, you might have changed this). +هذا التغير بسبب اختلافات ال nullability بين إصدارات AssemblyScript وهو مرتبط بملف`src/generated/schema.ts` (المسار الافتراضي ، ربما تكون قد غيرت هذا). -### Other +### آخر - Aligned `Map#set` and `Set#add` with the spec, returning `this` ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) -- Arrays no longer inherit from ArrayBufferView, but are now distinct ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- لم تعد المصفوفة ترث من ArrayBufferView ، لكنها أصبحت متميزة الآن ([ v0.10.0 ](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) - 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)) +- نتيجة العملية الثنائية ` ** ` هي الآن العدد الصحيح للمقام المشترك إذا كان كلا المعاملين عددًا صحيحًا. 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)) +- إجبار`NaN` إلى `false` عندما ال casting إلى`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)) - 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/pages/ar/developer/create-subgraph-hosted.mdx b/pages/ar/developer/create-subgraph-hosted.mdx index 3b05b2548456..c95b98fdc85d 100644 --- a/pages/ar/developer/create-subgraph-hosted.mdx +++ b/pages/ar/developer/create-subgraph-hosted.mdx @@ -1,18 +1,18 @@ --- -title: Create a Subgraph +title: إنشاء الـ Subgraph --- -Before being able to use the Graph CLI, you need to create your subgraph in [Subgraph Studio](https://thegraph.com/studio). You will then be able to setup your subgraph project and deploy it to the platform of your choice. Note that **subgraphs that do not index Ethereum mainnet will not be published to The Graph Network**. +قبل التمكن من استخدام Graph CLI ، يلزمك إنشاء الـ subgraph الخاص بك في [ Subgraph Studio ](https://thegraph.com/studio). ستتمكن بعد ذلك من إعداد مشروع الـ subgraph الخاص بك ونشره على المنصة الي تختارها. لاحظ أنه لن يتم نشر ** الـ subgraphs التي لا تقوم بفهرسة mainnet لإيثريوم على شبكة The Graph **. -The `graph init` command can be used to set up a new subgraph project, either from an existing contract on any of the public Ethereum networks, or from an example subgraph. This command can be used to create a subgraph on the Subgraph Studio by passing in `graph init --product subgraph-studio`. If you already have a smart contract deployed to Ethereum mainnet or one of the testnets, bootstrapping a new subgraph from that contract can be a good way to get started. But first, a little about the networks The Graph supports. +يمكن استخدام الأمر `graph init ` لإعداد مشروع subgraph جديد ، إما من عقد موجود على أي من شبكات Ethereum العامة ، أو من مثال subgraph. يمكن استخدام هذا الأمر لإنشاء subgraph في Subgraph Studio عن طريق تمرير `graph init --product subgraph-studio`. إذا كان لديك بالفعل عقد ذكي تم نشره على شبكة Ethereum mainnet أو إحدى شبكات testnets ، فإن تمهيد subgraph جديد من هذا العقد يمكن أن يكون طريقة جيدة للبدء. لكن أولا ، لنتحدث قليلا عن الشبكات التي يدعمها The Graph. -## Supported Networks +## الشبكات المدعومة The Graph Network supports subgraphs indexing mainnet Ethereum: - `mainnet` -**Additional Networks are supported in beta on the Hosted Service**: +** يتم دعم الشبكات الإضافية في الإصدار beta على Hosted Service **: - `mainnet` - `kovan` @@ -44,13 +44,13 @@ The Graph Network supports subgraphs indexing mainnet Ethereum: - `aurora` - `aurora-testnet` -The Graph's Hosted Service relies on the stability and reliability of the underlying technologies, namely the provided JSON RPC endpoints. Newer networks will be marked as being in beta until the network has proven itself in terms of stability, reliability, and scalability. During this beta period, there is risk of downtime and unexpected behaviour. +يعتمد Graph's Hosted Service على استقرار وموثوقية التقنيات الأساسية ، وهي نقاط JSON RPC endpoints. المتوفرة. سيتم تمييز الشبكات الأحدث على أنها في مرحلة beta حتى تثبت الشبكة نفسها من حيث الاستقرار والموثوقية وقابلية التوسع. خلال هذه الفترة beta ، هناك خطر حدوث عطل وسلوك غير متوقع. -Remember that you will **not be able** to publish a subgraph that indexes a non-mainnet network to the decentralized Graph Network in [Subgraph Studio](/studio/subgraph-studio). +تذكر أنك ** لن تكون قادرا ** على نشر subgraph يفهرس شبكة non-mainnet لـ شبكة Graph اللامركزية في [Subgraph Studio ](/ studio / subgraph-studio). -## From An Existing Contract +## من عقد موجود -The following command creates a subgraph that indexes all events of an existing contract. It attempts to fetch the contract ABI from Etherscan and falls back to requesting a local file path. If any of the optional arguments are missing, it takes you through an interactive form. +الأمر التالي ينشئ subgraph يفهرس كل الأحداث للعقد الموجود. إنه يحاول جلب ABI للعقد من Etherscan ويعود إلى طلب مسار ملف محلي. إذا كانت أي من arguments الاختيارية مفقودة ، فسيأخذك عبر نموذج تفاعلي. ```sh graph init \ @@ -61,23 +61,23 @@ graph init \ [] ``` -The `` is the ID of your subgraph in Subgraph Studio, it can be found on your subgraph details page. +`` هو ID لـ subgraph الخاص بك في Subgraph Studio ، ويمكن العثور عليه في صفحة تفاصيل الـ subgraph. -## From An Example Subgraph +## من مثال Subgraph -The second mode `graph init` supports is creating a new project from an example subgraph. The following command does this: +الوضع الثاني `graph init` يدعم إنشاء مشروع جديد من مثال subgraph. الأمر التالي يقوم بهذا: ``` graph init --studio ``` -The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. The following sections will go over the files that make up the subgraph manifest for this example. +يعتمد مثال الـ subgraph على عقد Gravity بواسطة Dani Grant الذي يدير avatars للمستخدم ويصدر أحداث ` NewGravatar ` أو ` UpdateGravatar ` كلما تم إنشاء avatars أو تحديثها. يعالج الـ subgraph هذه الأحداث عن طريق كتابة كيانات ` Gravatar ` إلى مخزن Graph Node والتأكد من تحديثها وفقا للأحداث. ستنتقل الأقسام التالية إلى الملفات التي تشكل الـ subgraph manifest لهذا المثال. ## The Subgraph Manifest -The subgraph manifest `subgraph.yaml` defines the smart contracts your subgraph indexes, which events from these contracts to pay attention to, and how to map event data to entities that Graph Node stores and allows to query. The full specification for subgraph manifests can be found [here](https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md). +Subgraph manifest `subgraph.yaml` تحدد العقود الذكية لفهارس الـ subgraph الخاص بك ، والأحداث من هذه العقود التي يجب الانتباه إليها ، وكيفية عمل map لبيانات الأحداث للكيانات التي تخزنها Graph Node وتسمح بالاستعلام عنها. يمكن العثور على المواصفات الكاملة لـ subgraph manifests [ هنا ](https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md). -For the example subgraph, `subgraph.yaml` is: +بالنسبة لمثال الـ subgraph ،يكون الـ ` subgraph.yaml `: ```yaml specVersion: 0.0.4 @@ -118,59 +118,59 @@ dataSources: file: ./src/mapping.ts ``` -The important entries to update for the manifest are: +الإدخالات الهامة لتحديث manifest هي: -- `description`: a human-readable description of what the subgraph is. This description is displayed by the Graph Explorer when the subgraph is deployed to the Hosted Service. +- ` description`: وصف يمكن قراءته لماهية الـ subgraph. يتم عرض هذا الوصف بواسطة Graph Explorer عند نشر الـ subgraph على الـ Hosted Service. -- `repository`: the URL of the repository where the subgraph manifest can be found. This is also displayed by the Graph Explorer. +- `repository`: عنوان URL للمخزن حيث يمكن العثور على subgraph manifest. يتم أيضا عرض هذا بواسطة Graph Explorer. -- `features`: a list of all used [feature](#experimental-features) names. +- `features`: قائمة بجميع أسماء الـ [ الميزات](#experimental-features) المستخدمة. -- `dataSources.source`: the address of the smart contract the subgraph sources, and the abi of the smart contract to use. The address is optional; omitting it allows to index matching events from all contracts. +- `dataSources.source`: عنوان العقد الذكي ،و مصادر الـ subgraph ، و abi استخدام العقد الذكي. العنوان اختياري. وبحذفه يسمح بفهرسة الأحداث المطابقة من جميع العقود. -- `dataSources.source.startBlock`: the optional number of the block that the data source starts indexing from. In most cases we suggest using the block in which the contract was created. +- `dataSources.source.startBlock`: الرقم الاختياري للكتلة والتي يبدأ مصدر البيانات بالفهرسة منها. في معظم الحالات نقترح استخدام الكتلة التي تم إنشاء العقد من خلالها. -- `dataSources.mapping.entities`: the entities that the data source writes to the store. The schema for each entity is defined in the the schema.graphql file. +- `dataSources.mapping.entities`: الكيانات التي يكتبها مصدر البيانات إلى المخزن. يتم تحديد مخطط كل كيان في ملف schema.graphql. -- `dataSources.mapping.abis`: one or more named ABI files for the source contract as well as any other smart contracts that you interact with from within the mappings. +- `dataSources.mapping.abis`: ملف ABI واحد أو أكثر لعقد المصدر بالإضافة إلى أي عقود ذكية أخرى تتفاعل معها من داخل الـ mappings. - `dataSources.mapping.eventHandlers`: lists the smart contract events this subgraph reacts to and the handlers in the mapping—./src/mapping.ts in the example—that transform these events into entities in the store. - `dataSources.mapping.callHandlers`: lists the smart contract functions this subgraph reacts to and handlers in the mapping that transform the inputs and outputs to function calls into entities in the store. -- `dataSources.mapping.blockHandlers`: lists the blocks this subgraph reacts to and handlers in the mapping to run when a block is appended to the chain. Without a filter, the block handler will be run every block. An optional filter can be provided with the following kinds: call`. A`call` filter will run the handler if the block contains at least one call to the data source contract. +- `dataSources.mapping.blockHandlers`: lists the blocks this subgraph reacts to and handlers in the mapping to run when a block is appended to the chain. بدون فلتر، سيتم تشغيل معالج الكتلة في كل كتلة. يمكن توفير فلتر اختياري مع الأنواع التالية: call`. سيعمل فلتر ` call` على تشغيل المعالج إذا كانت الكتلة تحتوي على استدعاء واحد على الأقل لعقد مصدر البيانات. -A single subgraph can index data from multiple smart contracts. Add an entry for each contract from which data needs to be indexed to the `dataSources` array. +يمكن لـ subgraph واحد فهرسة البيانات من عقود ذكية متعددة. أضف إدخالا لكل عقد يجب فهرسة البيانات منه إلى مصفوفة ` dataSources `. -The triggers for a data source within a block are ordered using the following process: +يتم ترتيب الـ triggers لمصدر البيانات داخل الكتلة باستخدام العملية التالية: -1. Event and call triggers are first ordered by transaction index within the block. -2. Event and call triggers with in the same transaction are ordered using a convention: event triggers first then call triggers, each type respecting the order they are defined in the manifest. -3. Block triggers are run after event and call triggers, in the order they are defined in the manifest. +1. يتم ترتيب triggers الأحداث والاستدعاءات أولا من خلال فهرس الإجراء داخل الكتلة. +2. يتم ترتيب triggers الحدث والاستدعاء في نفس الإجراء باستخدام اصطلاح: يتم تفعيل مشغلات الحدث أولا ثم مشغلات الاستدعاء (event triggers first then call triggers) ، ويحترم كل نوع الترتيب المحدد في الـ manifest. +3. يتم تشغيل مشغلات الكتلة بعد مشغلات الحدث والاستدعاء، بالترتيب المحدد في الـ manifest. -These ordering rules are subject to change. +قواعد الترتيب هذه عرضة للتغيير. ### Getting The ABIs -The ABI file(s) must match your contract(s). There are a few ways to obtain ABI files: +يجب أن تتطابق ملف (ملفات) ABI مع العقد (العقود) الخاصة بك. هناك عدة طرق للحصول على ملفات ABI: -- If you are building your own project, you will likely have access to your most current ABIs. -- If you are building a subgraph for a public project, you can download that project to your computer and get the ABI by using [`truffle compile`](https://truffleframework.com/docs/truffle/overview) or using solc to compile. -- You can also find the ABI on [Etherscan](https://etherscan.io/), but this isn't always reliable, as the ABI that is uploaded there may be out of date. Make sure you have the right ABI, otherwise running your subgraph will fail. +- إذا كنت تقوم ببناء مشروعك الخاص ، فمن المحتمل أن تتمكن من الوصول إلى أحدث ABIs. +- إذا كنت تقوم ببناء subgraph لمشروع عام ، فيمكنك تنزيل هذا المشروع على جهاز الكمبيوتر الخاص بك والحصول على ABI باستخدام [ ` truffle compile ` ](https://truffleframework.com/docs/truffle/overview) أو استخدام solc للترجمة. +- يمكنك أيضا العثور على ABI على [ Etherscan ](https://etherscan.io/) ، ولكن هذا ليس موثوقا به دائما ، حيث قد يكون ABI الذي تم تحميله هناك قديما. تأكد من أن لديك ABI الصحيح ، وإلا فإن تشغيل الـ subgraph الخاص بك سيفشل. -## The GraphQL Schema +## مخطط GraphQL -The schema for your subgraph is in the file `schema.graphql`. GraphQL schemas are defined using the GraphQL interface definition language. If you've never written a GraphQL schema, it is recommended that you check out this primer on the GraphQL type system. Reference documentation for GraphQL schemas can be found in the [GraphQL API](/developer/graphql-api) section. +مخطط الـ subgraph الخاص بك موجود في الملف ` schema.graphql `. يتم تعريف مخططات GraphQL باستخدام لغة تعريف واجهة GraphQL. إذا لم تكتب مخطط GraphQL مطلقا ، فمن المستحسن أن تقوم بمراجعة هذا التمهيد على نظام نوع GraphQL. يمكن العثور على الوثائق المرجعية لمخططات GraphQL في قسم [ GraphQL API ](/developer/graphql-api). -## Defining Entities +## تعريف الكيانات -Before defining entities, it is important to take a step back and think about how your data is structured and linked. All queries will be made against the data model defined in the subgraph schema and the entities indexed by the subgraph. Because of this, it is good to define the subgraph schema in a way that matches the needs of your dapp. It may be useful to imagine entities as "objects containing data", rather than as events or functions. +قبل تعريف الكيانات ، من المهم التراجع والتفكير في كيفية هيكلة بياناتك وربطها. سيتم إجراء جميع الاستعلامات لنموذج البيانات المعرفة في مخطط الـ subgraph والكيانات المفهرسة بواسطة الـ subgraph. لهذا السبب ، من الجيد تعريف مخطط الـ subgraph بطريقة تتوافق مع احتياجات الـ dapp الخاص بك. قد يكون من المفيد تصور الكيانات على أنها "كائنات تحتوي على بيانات" ، وليس أحداثا أو دوال. -With The Graph, you simply define entity types in `schema.graphql`, and Graph Node will generate top level fields for querying single instances and collections of that entity type. Each type that should be an entity is required to be annotated with an `@entity` directive. +بواسطة The Graph ، يمكنك ببساطة تحديد أنواع الكيانات في ` schema.graphql ` ، وسيقوم Graph Node بإنشاء حقول المستوى الأعلى للاستعلام عن الـ instances الفردية والمجموعات من هذا النوع من الكيانات. كل نوع يجب أن يكون كيانا يكون مطلوبا للتعليق عليه باستخدام التوجيه `entity `. -### Good Example +### مثال جيد -The `Gravatar` entity below is structured around a Gravatar object and is a good example of how an entity could be defined. +تم تنظيم الكيان ` Gravatar ` أدناه حول كائن Gravatar وهو مثال جيد لكيفية تعريف الكيان. ```graphql type Gravatar @entity { @@ -182,9 +182,9 @@ type Gravatar @entity { } ``` -### Bad Example +### مثال سيئ -The example `GravatarAccepted` and `GravatarDeclined` entities below are based around events. It is not recommended to map events or function calls to entities 1:1. +يستند مثالان الكيانات أدناه ` GravatarAccepted ` و ` GravatarDeclined ` إلى أحداث. لا يوصى بعمل map الأحداث أو استدعاءات الدوال للكيانات 1: 1. ```graphql type GravatarAccepted @entity { @@ -202,35 +202,35 @@ type GravatarDeclined @entity { } ``` -### Optional and Required Fields +### الحقول الاختيارية والمطلوبة -Entity fields can be defined as required or optional. Required fields are indicated by the `!` in the schema. If a required field is not set in the mapping, you will receive this error when querying the field: +يمكن تعريف حقول الكيانات على أنها مطلوبة أو اختيارية. الحقول المطلوبة يشار إليها بواسطة `!` في المخطط. إذا لم يتم تعيين حقل مطلوب في الـ mapping ، فستتلقى هذا الخطأ عند الاستعلام عن الحقل: ``` Null value resolved for non-null field 'name' ``` -Each entity must have an `id` field, which is of type `ID!` (string). The `id` field serves as the primary key, and needs to be unique among all entities of the same type. +يجب أن يكون لكل كيان حقل ` id` ، وهو من النوع ` ID!` (string). حقل `id` يقدم كمفتاح رئيسي ويجب أن يكون فريدا في كل الكيانات لنفس النوع. -### Built-In Scalar Types +### أنواع المقاييس المضمنة -#### GraphQL Supported Scalars +#### المقاييس المدعومة من GraphQL -We support the following scalars in our GraphQL API: +ندعم المقاييس التالية في GraphQL API الخاصة بنا: -| Type | Description | -| --- | --- | -| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | -| `ID` | Stored as a `string`. | -| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | -| `Boolean` | Scalar for `boolean` values. | -| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | -| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | -| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | +| النوع | الوصف | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Bytes` | مصفوفة Byte ، ممثلة كسلسلة سداسية عشرية. يشيع استخدامها في Ethereum hashes وعناوينه. | +| `ID` | يتم تخزينه كـ `string`. | +| `String` | لقيم ` string`. لا يتم دعم اNull ويتم إزالتها تلقائيا. | +| `Boolean` | لقيم `boolean`. | +| `Int` | GraphQL spec تعرف `Int` بحجم 32 بايت. | +| `BigInt` | أعداد صحيحة كبيرة. يستخدم لأنواع Ethereum ` uint32 ` ، ` int64 ` ، ` uint64 ` ، ... ، ` uint256 `. ملاحظة: كل شيء تحت ` uint32 ` ، مثل ` int32 ` أو ` uint24 ` أو ` int8 ` يتم تمثيله كـ ` i32 `. | +| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. يتراوح نطاق الأس من −6143 إلى +6144. مقربة إلى 34 رقما. | #### Enums -You can also create enums within a schema. Enums have the following syntax: +يمكنك أيضا إنشاء enums داخل مخطط. Enums لها البناء التالي: ```graphql enum TokenStatus { @@ -240,19 +240,19 @@ enum TokenStatus { } ``` -Once the enum is defined in the schema, you can use the string representation of the enum value to set an enum field on an entity. For example, you can set the `tokenStatus` to `SecondOwner` by first defining your entity and subsequently setting the field with `entity.tokenStatus = "SecondOwner`. The example below demonstrates what the Token entity would look like with an enum field: +بمجرد تعريف الـ enum في المخطط ، يمكنك استخدام string لقيمة الـ enum لتعيين حقل الـ enum في الكيان. على سبيل المثال ، يمكنك تعيين ` tokenStatus ` إلى ` SecondOwner ` عن طريق تعريف الكيان أولا ثم تعيين الحقل بعد ذلك بـ `entity.tokenStatus = "SecondOwner`. يوضح المثال أدناه الشكل الذي سيبدو عليه كيان التوكن في حقل الـ enum: -More detail on writing enums can be found in the [GraphQL documentation](https://graphql.org/learn/schema/). +يمكن العثور على مزيد من التفاصيل حول كتابة الـ enums في [GraphQL documentation](https://graphql.org/learn/schema/). -#### Entity Relationships +#### علاقات الكيانات -An entity may have a relationship to one or more other entities in your schema. These relationships may be traversed in your queries. Relationships in The Graph are unidirectional. It is possible to simulate bidirectional relationships by defining a unidirectional relationship on either "end" of the relationship. +قد يكون للكيان علاقة بواحد أو أكثر من الكيانات الأخرى في مخططك. قد يتم اجتياز هذه العلاقات في استعلاماتك. العلاقات في The Graph تكون أحادية الاتجاه. من الممكن محاكاة العلاقات ثنائية الاتجاه من خلال تعريف علاقة أحادية الاتجاه على "طرفي" العلاقة. -Relationships are defined on entities just like any other field except that the type specified is that of another entity. +يتم تعريف العلاقات على الكيانات تماما مثل أي حقل آخر عدا أن النوع المحدد هو كيان آخر. -#### One-To-One Relationships +#### العلاقات واحد لواحد -Define a `Transaction` entity type with an optional one-to-one relationship with a `TransactionReceipt` entity type: +عرف نوع كيان ` Transaction` بعلاقة فردية اختيارية مع نوع كيان ` TransactionReceipt `: ```graphql type Transaction @entity { @@ -266,9 +266,9 @@ type TransactionReceipt @entity { } ``` -#### One-To-Many Relationships +#### علاقات واحد لمتعدد -Define a `TokenBalance` entity type with a required one-to-many relationship with a Token entity type: +عرف نوع كيان ` TokenBalance ` بعلاقة واحد لمتعدد المطلوبة مع نوع كيان Token: ```graphql type Token @entity { @@ -282,15 +282,15 @@ type TokenBalance @entity { } ``` -#### Reverse Lookups +#### البحث العكسي -Reverse lookups can be defined on an entity through the `@derivedFrom` field. This creates a virtual field on the entity that may be queried but cannot be set manually through the mappings API. Rather, it is derived from the relationship defined on the other entity. For such relationships, it rarely makes sense to store both sides of the relationship, and both indexing and query performance will be better when only one side is stored and the other is derived. +يمكن تعريف البحث العكسي لكيان من خلال الحقل `derivedFrom `. يؤدي هذا إلى إنشاء حقل افتراضي للكيان الذي قد يتم الاستعلام عنه ولكن لا يمكن تعيينه يدويا من خلال الـ mappings API. بالأحرى، هو مشتق من العلاقة المعرفة للكيان الآخر. بالنسبة لمثل هذه العلاقات ، نادرا ما يكون من المنطقي تخزين جانبي العلاقة ، وسيكون أداء الفهرسة والاستعلام أفضل عندما يتم تخزين جانب واحد فقط ويتم اشتقاق الجانب الآخر. -For one-to-many relationships, the relationship should always be stored on the 'one' side, and the 'many' side should always be derived. Storing the relationship this way, rather than storing an array of entities on the 'many' side, will result in dramatically better performance for both indexing and querying the subgraph. In general, storing arrays of entities should be avoided as much as is practical. +بالنسبة لعلاقات واحد_لمتعدد ، يجب دائما تخزين العلاقة في جانب "واحد" ، ويجب دائما اشتقاق جانب "المتعدد". سيؤدي تخزين العلاقة بهذه الطريقة ، بدلا من تخزين مجموعة من الكيانات على الجانب "متعدد" ، إلى أداء أفضل بشكل كبير لكل من فهرسة واستعلام الـ subgraph. بشكل عام ، يجب تجنب تخزين مصفوفات الكيانات. -#### Example +#### مثال -We can make the balances for a token accessible from the token by deriving a `tokenBalances` field: +يمكننا إنشاء أرصدة لتوكن يمكن الوصول إليه من التوكن عن طريق اشتقاق حقل ` tokenBalances `: ```graphql type Token @entity { @@ -305,13 +305,13 @@ type TokenBalance @entity { } ``` -#### Many-To-Many Relationships +#### علاقات متعدد_لمتعدد -For many-to-many relationships, such as users that each may belong to any number of organizations, the most straightforward, but generally not the most performant, way to model the relationship is as an array in each of the two entities involved. If the relationship is symmetric, only one side of the relationship needs to be stored and the other side can be derived. +بالنسبة لعلاقات متعدد_لمتعدد ، مثل المستخدمين الذين قد ينتمي كل منهم إلى عدد من المؤسسات ، فإن الطريقة الأكثر وضوحا ، ولكنها ليست الأكثر أداء بشكل عام ، طريقة لنمذجة العلاقة كمصفوفة في كل من الكيانين المعنيين. إذا كانت العلاقة متماثلة ، فيجب تخزين جانب واحد فقط من العلاقة ويمكن اشتقاق الجانب الآخر. -#### Example +#### مثال -Define a reverse lookup from a `User` entity type to an `Organization` entity type. In the example below, this is achieved by looking up the `members` attribute from within the `Organization` entity. In queries, the `organizations` field on `User` will be resolved by finding all `Organization` entities that include the user's ID. +عرف البحث العكسي من نوع كيان ` User` إلى نوع كيان ` Organization`. في المثال أدناه ، يتم تحقيق ذلك من خلال البحث عن خاصية` members ` من داخل كيان ` Organization `. في الاستعلامات ، سيتم حل حقل ` organizations` في ` User` من خلال البحث عن جميع كيانات ` Organization` التي تتضمن ID المستخدم. ```graphql type Organization @entity { @@ -327,7 +327,7 @@ type User @entity { } ``` -A more performant way to store this relationship is through a mapping table that has one entry for each `User` / `Organization` pair with a schema like +هناك طريقة أكثر فاعلية لتخزين هذه العلاقة وهي من خلال جدول mapping يحتوي على إدخال واحد لكل زوج ` User` / ` Organization` بمخطط مثل ```graphql type Organization @entity { @@ -349,7 +349,7 @@ type UserOrganization @entity { } ``` -This approach requires that queries descend into one additional level to retrieve, for example, the organizations for users: +يتطلب هذا الأسلوب أن تنحدر الاستعلامات إلى مستوى إضافي واحد لاستردادها ، على سبيل المثال ، المؤسسات للمستخدمين: ```graphql query usersWithOrganizations { @@ -364,11 +364,11 @@ query usersWithOrganizations { } ``` -This more elaborate way of storing many-to-many relationships will result in less data stored for the subgraph, and therefore to a subgraph that is often dramatically faster to index and to query. +هذه الطريقة الأكثر إتقانا لتخزين علاقات متعدد_لمتعدد ستؤدي إلى بيانات مخزنة أقل للـ subgraph، وبالتالي غالبا إلى subgraph ما يكون أسرع في الفهرسة والاستعلام. -#### Adding comments to the schema +#### إضافة تعليقات إلى المخطط -As per GraphQL spec, comments can be added above schema entity attributes using double quotations `""`. This is illustrated in the example below: +وفقا لمواصفات GraphQL ، يمكن إضافة التعليقات فوق خاصيات كيان المخطط باستخدام الاقتباسات المزدوجة ` "" `. هذا موضح في المثال أدناه: ```graphql type MyFirstEntity @entity { @@ -378,13 +378,13 @@ type MyFirstEntity @entity { } ``` -## Defining Fulltext Search Fields +## تعريف حقول البحث عن النص الكامل -Fulltext search queries filter and rank entities based on a text search input. Fulltext queries are able to return matches for similar words by processing the query text input into stems before comparing to the indexed text data. +استعلامات بحث النص الكامل تقوم بفلترة وترتيب الكيانات بناء على إدخال نص البحث. استعلامات النص الكامل قادرة على إرجاع التطابقات للكلمات المتشابهة عن طريق معالجة إدخال نص الاستعلام إلى الـ stems قبل مقارنة ببيانات النص المفهرس. -A fulltext query definition includes the query name, the language dictionary used to process the text fields, the ranking algorithm used to order the results, and the fields included in the search. Each fulltext query may span multiple fields, but all included fields must be from a single entity type. +تعريف استعلام النص الكامل يتضمن اسم الاستعلام وقاموس اللغة المستخدم لمعالجة حقول النص وخوارزمية الترتيب المستخدمة لترتيب النتائج والحقول المضمنة في البحث. كل استعلام نص كامل قد يمتد إلى عدة حقول ، ولكن يجب أن تكون جميع الحقول المضمنة من نوع كيان واحد. -To add a fulltext query, include a `_Schema_` type with a fulltext directive in the GraphQL schema. +لإضافة استعلام نص كامل ، قم بتضمين نوع ` _Schema_ ` مع نص كامل موجه في مخطط GraphQL. ```graphql type _Schema_ @@ -407,7 +407,7 @@ type Band @entity { } ``` -The example `bandSearch` field can be used in queries to filter `Band` entities based on the text documents in the `name`, `description`, and `bio` fields. Jump to [GraphQL API - Queries](/developer/graphql-api#queries) for a description of the Fulltext search API and for more example usage. +يمكن استخدام حقل المثال ` bandSearch ` في الاستعلامات لفلترة كيانات ` Band ` استنادا إلى المستندات النصية في الـ ` name ` ، ` description` و ` bio `. انتقل إلى [GraphQL API - Queries](/developer/graphql-api#queries) للحصول على وصف لـ API بحث النص الكامل ولمزيد من الأمثلة المستخدمة. ```graphql query { @@ -420,49 +420,49 @@ query { } ``` -> **[Feature Management](#experimental-features):** From `specVersion` `0.0.4` and onwards, `fullTextSearch` must be declared under the `features` section in the subgraph manifest. +> ** [ إدارة الميزات ](#experimental-features): ** من ` specVersion ` ` 0.0.4 ` وما بعده ، يجب الإعلان عن ` fullTextSearch ` ضمن قسم ` features ` في the subgraph manifest. -### Languages supported +### اللغات المدعومة -Choosing a different language will have a definitive, though sometimes subtle, effect on the fulltext search API. Fields covered by a fulltext query field are examined in the context of the chosen language, so the lexemes produced by analysis and search queries vary language to language. For example: when using the supported Turkish dictionary "token" is stemmed to "toke" while, of course, the English dictionary will stem it to "token". +اختيار لغة مختلفة سيكون له تأثير نهائي ، على الرغم من دقتها في بعض الأحيان ، إلا أنها تؤثر على API بحث النص الكامل. يتم فحص الحقول التي يغطيها حقل استعلام نص_كامل في سياق اللغة المختارة ، وبالتالي فإن المفردات الناتجة عن التحليل واستعلامات البحث تختلف من لغة إلى لغة. على سبيل المثال: عند استخدام القاموس التركي المدعوم ، فإن "token" ينشأ من "toke" بينما قاموس اللغة الإنجليزية سيشتقها إلى "token". -Supported language dictionaries: +قواميس اللغة المدعومة: -| Code | Dictionary | -| ------ | ---------- | -| simple | General | -| da | Danish | -| nl | Dutch | -| en | English | -| fi | Finnish | -| fr | French | -| de | German | -| hu | Hungarian | -| it | Italian | -| no | Norwegian | -| pt | Portugese | -| ro | Romanian | -| ru | Russian | -| es | Spanish | -| sv | Swedish | -| tr | Turkish | +| الرمز | القاموس | +| ------ | ------- | +| simple | عام | +| da | دنماركي | +| nl | هولندي | +| en | إنجليزي | +| fi | فنلندي | +| fr | فرنسي | +| de | ألماني | +| hu | مجري | +| it | إيطالي | +| no | نرويجي | +| pt | برتغالي | +| ro | روماني | +| ru | روسي | +| es | إسباني | +| sv | سويدي | +| tr | تركي | -### Ranking Algorithms +### خوارزميات التصنيف -Supported algorithms for ordering results: +الخوارزميات المدعومة لترتيب النتائج: -| Algorithm | Description | -| ------------- | ----------------------------------------------------------------------- | -| rank | Use the match quality (0-1) of the fulltext query to order the results. | -| proximityRank | Similar to rank but also includes the proximity of the matches. | +| الخوارزمية | الوصف | +| ------------- | ------------------------------------------------------------ | +| rank | استخدم جودة مطابقة استعلام النص-الكامل (0-1) لترتيب النتائج. | +| proximityRank | مشابه لـ rank ولكنه يشمل أيضا القرب من المطابقات. | -## Writing Mappings +## كتابة الـ Mappings -The mappings transform the Ethereum data your mappings are sourcing into entities defined in your schema. Mappings are written in a subset of [TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) called [AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki) which can be compiled to WASM ([WebAssembly](https://webassembly.org/)). AssemblyScript is stricter than normal TypeScript, yet provides a familiar syntax. +The mappings transform the Ethereum data your mappings are sourcing into entities defined in your schema. تتم كتابة الـ Mappings في مجموعة فرعية من [ TypeScript ](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) تسمى [AssemblyScript ](https: //github.com/AssemblyScript/assemblyscript/wiki) والتي يمكن ترجمتها إلى WASM ([ WebAssembly ](https://webassembly.org/)). يعتبر AssemblyScript أكثر صرامة من TypeScript العادي ، ولكنه يوفر تركيبا مألوفا. -For each event handler that is defined in `subgraph.yaml` under `mapping.eventHandlers`, create an exported function of the same name. Each handler must accept a single parameter called `event` with a type corresponding to the name of the event which is being handled. +لكل معالج حدث تم تعريفه في ` subgraph.yaml ` ضمن ` mapping.eventHandlers ` ، قم بإنشاء دالة صادرة بنفس الاسم. يجب أن يقبل كل معالج بارمترا واحدا يسمى ` event ` بنوع مطابق لاسم الحدث الذي تتم معالجته. -In the example subgraph, `src/mapping.ts` contains handlers for the `NewGravatar` and `UpdatedGravatar` events: +في مثال الـ subgraph ، يحتوي ` src / mapping.ts ` على معالجات لأحداث ` NewGravatar ` و ` UpdatedGravatar `: ```javascript import { NewGravatar, UpdatedGravatar } from '../generated/Gravity/Gravity' @@ -489,31 +489,31 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { } ``` -The first handler takes a `NewGravatar` event and creates a new `Gravatar` entity with `new Gravatar(event.params.id.toHex())`, populating the entity fields using the corresponding event parameters. This entity instance is represented by the variable `gravatar`, with an id value of `event.params.id.toHex()`. +يأخذ المعالج الأول حدث ` NewGravatar ` وينشئ كيان ` Gravatar ` جديد بـ ` new Gravatar (event.params.id.toHex ()) ` ،مالئا حقول الكيان باستخدام بارامترات الحدث المقابلة. يتم تمثيل instance الكيان بالمتغير ` gravatar ` ، مع قيمة معرف `()event.params.id.toHex `. -The second handler tries to load the existing `Gravatar` from the Graph Node store. If it does not exist yet, it is created on demand. The entity is then updated to match the new event parameters, before it is saved back to the store using `gravatar.save()`. +يحاول المعالج الثاني تحميل ` Gravatar ` الموجود من مخزن Graph Node. إذا لم يكن موجودا بعد ، فإنه يتم إنشاؤه عند الطلب. يتم بعد ذلك تحديث الكيان لمطابقة بارامترات الحدث الجديدة ، قبل حفظه مرة أخرى في المخزن باستخدام ` ()gravatar.save `. -### Recommended IDs for Creating New Entities +### الـ IDs الموصى بها لإنشاء كيانات جديدة -Every entity has to have an `id` that is unique among all entities of the same type. An entity's `id` value is set when the entity is created. Below are some recommended `id` values to consider when creating new entities. NOTE: The value of `id` must be a `string`. +يجب أن يكون لكل كيان ` id` فريدا بين جميع الكيانات من نفس النوع. يتم تعيين قيمة ` id ` للكيان عند إنشاء الكيان. فيما يلي بعض قيم ` id ` الموصى بها التي يجب مراعاتها عند إنشاء كيانات جديدة. ملاحظة: قيمة ` id `يجب أن تكون `string`. - `event.params.id.toHex()` - `event.transaction.from.toHex()` - `event.transaction.hash.toHex() + "-" + event.logIndex.toString()` -We provide the [Graph Typescript Library](https://github.com/graphprotocol/graph-ts) which contains utilies for interacting with the Graph Node store and conveniences for handling smart contract data and entities. You can use this library in your mappings by importing `@graphprotocol/graph-ts` in `mapping.ts`. +نحن نقدم [Graph Typescript Library](https://github.com/graphprotocol/graph-ts) التي تحتوي على أدوات مساعدة للتفاعل مع مخزن Graph Node وملائمة للتعامل مع بيانات العقد الذكي والكيانات. يمكنك استخدام هذه المكتبة في mappings الخاص بك عن طريق استيراد `graphprotocol/graph-ts` in `mapping.ts@`. -## Code Generation +## توليد الكود -In order to make working smart contracts, events and entities easy and type-safe, the Graph CLI can generate AssemblyScript types from the subgraph's GraphQL schema and the contract ABIs included in the data sources. +من أجل جعل العقود الذكية والأحداث والكيانات سهلة وآمنة ، يمكن لـ Graph CLI إنشاء أنواع AssemblyScript من مخطط subgraph's GraphQL وعقد الـ ABIs المضمنة في مصادر البيانات. -This is done with +يتم ذلك بـ ```sh graph codegen [--output-dir ] [] ``` -but in most cases, subgraphs are already preconfigured via `package.json` to allow you to simply run one of the following to achieve the same: +ولكن في معظم الحالات ، تكون الـ subgraphs مهيأة مسبقا بالفعل عبر ` package.json ` للسماح لك ببساطة بتشغيل واحد مما يلي لتحقيق نفس الشيء: ```sh # Yarn @@ -523,7 +523,7 @@ yarn codegen npm run codegen ``` -This will generate an AssemblyScript class for every smart contract in the ABI files mentioned in `subgraph.yaml`, allowing you to bind these contracts to specific addresses in the mappings and call read-only contract methods against the block being processed. It will also generate a class for every contract event to provide easy access to event parameters as well as the block and transaction the event originated from. All of these types are written to `//.ts`. In the example subgraph, this would be `generated/Gravity/Gravity.ts`, allowing mappings to import these types with +سيؤدي هذا إلى إنشاء فئة AssemblyScript لكل عقد ذكي في ملفات ABI المذكورة في ` subgraph.yaml ` ، مما يسمح لك بربط هذه العقود بعناوين محددة في الـ mappings واستدعاء methods العقد للكتلة التي تتم معالجتها. وستنشئ أيضا فئة لكل حدث للعقد لتوفير وصول سهل إلى بارامترات الحدث بالإضافة إلى الكتلة والإجراء التي نشأ منها الحدث. كل هذه الأنواع تكتب إلى `//.ts`. في مثال الـ subgraph ، سيكون هذا `generated/Gravity/Gravity.ts`,مما يسمح للـ mappings باستيراد هذه الأنواع باستخدام ```javascript import { @@ -535,23 +535,23 @@ import { } from '../generated/Gravity/Gravity' ``` -In addition to this, one class is generated for each entity type in the subgraph's GraphQL schema. These classes provide type-safe entity loading, read and write access to entity fields as well as a `save()` method to write entities to store. All entity classes are written to `/schema.ts`, allowing mappings to import them with +بالإضافة إلى ذلك ، يتم إنشاء فئة واحدة لكل نوع كيان في مخطط الـ subgraph's GraphQL. توفر هذه الفئات إمكانية تحميل كيان نوغ آمن والقراءة والكتابة إلى حقول الكيان بالإضافة إلى `save()` method لكتابة الكيانات للمخزن. تمت كتابة جميع فئات الكيانات إلى `/schema.ts`, مما يسمح للـ mappings باستيرادها باستخدام ```javascript import { Gravatar } from '../generated/schema' ``` -> **Note:** The code generation must be performed again after every change to the GraphQL schema or the ABIs included in the manifest. It must also be performed at least once before building or deploying the subgraph. +> **Note:** يجب إجراء إنشاء الكود مرة أخرى بعد كل تغيير في مخطط GraphQL أو ABI المضمنة في الـ manifest. يجب أيضا إجراؤه مرة واحدة على الأقل قبل بناء أو نشر الـ subgraph. -Code generation does not check your mapping code in `src/mapping.ts`. If you want to check that before trying to deploy your subgraph to the Graph Explorer, you can run `yarn build` and fix any syntax errors that the TypeScript compiler might find. +إنشاء الكود لا يتحقق من كود الـ mapping الخاص بك في `src/mapping.ts`. إذا كنت تريد التحقق من ذلك قبل محاولة نشر الـ subgraph الخاص بك في Graph Explorer ، فيمكنك تشغيل `yarn build` وإصلاح أي أخطاء في تركيب الجملة التي قد يعثر عليها المترجم TypeScript. -## Data Source Templates +## قوالب مصدر البيانات -A common pattern in Ethereum smart contracts is the use of registry or factory contracts, where one contract creates, manages or references an arbitrary number of other contracts that each have their own state and events. The addresses of these sub-contracts may or may not be known upfront and many of these contracts may be created and/or added over time. This is why, in such cases, defining a single data source or a fixed number of data sources is impossible and a more dynamic approach is needed: _data source templates_. +النمط الشائع في عقود Ethereum الذكية هو استخدام عقود السجل أو المصنع ، حيث أحد العقود ينشئ أو يدير أو يشير إلى عدد اعتباطي من العقود الأخرى التي لكل منها حالتها وأحداثها الخاصة. عناوين هذه العقود الفرعية قد تكون أو لا تكون معروفة مقدما وقد يتم إنشاء و / أو إضافة العديد من هذه العقود بمرور الوقت. هذا هو السبب في أنه في مثل هذه الحالات ، يكون تعريف مصدر بيانات واحد أو عدد ثابت من مصادر البيانات أمرا مستحيلا ويلزم اتباع نهج أكثر ديناميكية: _قوالب مصدر البيانات_. -### Data Source for the Main Contract +### مصدر البيانات للعقد الرئيسي -First, you define a regular data source for the main contract. The snippet below shows a simplified example data source for the [Uniswap](https://uniswap.io) exchange factory contract. Note the `NewExchange(address,address)` event handler. This is emitted when a new exchange contract is created on chain by the factory contract. +أولاً ، تقوم بتعريف مصدر بيانات منتظم للعقد الرئيسي. يُظهر المقتطف أدناه مثالا مبسطا لمصدر البيانات لعقد تبادل[ Uniswap ](https://uniswap.io). لاحظ معالج الحدث `NewExchange(address,address)`. يتم اصدار هذا عندما يتم إنشاء عقد تبادل جديد على السلسلة بواسطة عقد المصنع. ```yaml dataSources: @@ -576,9 +576,9 @@ dataSources: handler: handleNewExchange ``` -### Data Source Templates for Dynamically Created Contracts +### قوالب مصدر البيانات للعقود التي تم إنشاؤها ديناميكيا -Then, you add _data source templates_ to the manifest. These are identical to regular data sources, except that they lack a predefined contract address under `source`. Typically, you would define one template for each type of sub-contract managed or referenced by the parent contract. +بعد ذلك ، أضف _ قوالب مصدر البيانات _ إلى الـ manifest. وهي متطابقة مع مصادر البيانات العادية ، باستثناء أنها تفتقر إلى عنوان عقد معرف مسبقا تحت ` source `. عادة ، يمكنك تعريف قالب واحد لكل نوع من أنواع العقود الفرعية المدارة أو المشار إليها بواسطة العقد الأصلي. ```yaml dataSources: @@ -612,9 +612,9 @@ templates: handler: handleRemoveLiquidity ``` -### Instantiating a Data Source Template +### إنشاء قالب مصدر البيانات -In the final step, you update your main contract mapping to create a dynamic data source instance from one of the templates. In this example, you would change the main contract mapping to import the `Exchange` template and call the `Exchange.create(address)` method on it to start indexing the new exchange contract. +في الخطوة الأخيرة ، تقوم بتحديث mapping عقدك الرئيسي لإنشاء instance لمصدر بيانات ديناميكي من أحد القوالب. في هذا المثال ، يمكنك تغيير mapping العقد الرئيسي لاستيراد قالب ` Exchange ` واستدعاء method الـ`Exchange.create(address)` لبدء فهرسة عقد التبادل الجديد. ```typescript import { Exchange } from '../generated/templates' @@ -626,13 +626,13 @@ export function handleNewExchange(event: NewExchange): void { } ``` -> **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks. -> -> If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created. +> ** ملاحظة: ** مصدر البيانات الجديد سيعالج فقط الاستدعاءات والأحداث للكتلة التي تم إنشاؤها فيه وجميع الكتل التالية ، ولكنه لن يعالج البيانات التاريخية ، أي البيانات الموجودة في الكتل السابقة. +> +> إذا كانت الكتل السابقة تحتوي على بيانات ذات صلة بمصدر البيانات الجديد ، فمن الأفضل فهرسة تلك البيانات من خلال قراءة الحالة الحالية للعقد وإنشاء كيانات تمثل تلك الحالة في وقت إنشاء مصدر البيانات الجديد. -### Data Source Context +### سياق مصدر البيانات -Data source contexts allow passing extra configuration when instantiating a template. In our example, let's say exchanges are associated with a particular trading pair, which is included in the `NewExchange` event. That information can be passed into the instantiated data source, like so: +تسمح سياقات مصدر البيانات بتمرير تكوين إضافي عند عمل instantiating للقالب. في مثالنا ، لنفترض أن التبادلات مرتبطة بزوج تداول معين ، والذي تم تضمينه في حدث ` NewExchange `. That information can be passed into the instantiated data source, like so: ```typescript import { Exchange } from '../generated/templates' @@ -644,7 +644,7 @@ export function handleNewExchange(event: NewExchange): void { } ``` -Inside a mapping of the `Exchange` template, the context can then be accessed: +داخل mapping قالب ` Exchange ` ، يمكن الوصول إلى السياق بعد ذلك: ```typescript import { dataSource } from '@graphprotocol/graph-ts' @@ -653,11 +653,11 @@ let context = dataSource.context() let tradingPair = context.getString('tradingPair') ``` -There are setters and getters like `setString` and `getString` for all value types. +هناك setters و getters مثل ` setString ` و ` getString ` لجميع أنواع القيم. ## Start Blocks -The `startBlock` is an optional setting that allows you to define from which block in the chain the data source will start indexing. Setting the start block allows the data source to skip potentially millions of blocks that are irrelevant. Typically, a subgraph developer will set `startBlock` to the block in which the smart contract of the data source was created. +يعد ` startBlock ` إعدادا اختياريا يسمح لك بتحديد كتلة في السلسلة والتي سيبدأ مصدر البيانات بالفهرسة. تعيين كتلة البدء يسمح لمصدر البيانات بتخطي الملايين من الكتل التي ربما ليست ذات صلة. عادةً ما يقوم مطور الرسم البياني الفرعي بتعيين ` startBlock ` إلى الكتلة التي تم فيها إنشاء العقد الذكي لمصدر البيانات. ```yaml dataSources: @@ -683,23 +683,23 @@ dataSources: handler: handleNewEvent ``` -> **Note:** The contract creation block can be quickly looked up on Etherscan: -> -> 1. Search for the contract by entering its address in the search bar. -> 2. Click on the creation transaction hash in the `Contract Creator` section. -> 3. Load the transaction details page where you'll find the start block for that contract. +> ** ملاحظة: ** يمكن البحث عن كتلة إنشاء العقد بسرعة على Etherscan: +> +> 1. ابحث عن العقد بإدخال عنوانه في شريط البحث. +> 2. انقر فوق hash إجراء الإنشاء في قسم `Contract Creator`. +> 3. قم بتحميل صفحة تفاصيل الإجراء حيث ستجد كتلة البدء لذلك العقد. -## Call Handlers +## معالجات الاستدعاء -While events provide an effective way to collect relevant changes to the state of a contract, many contracts avoid generating logs to optimize gas costs. In these cases, a subgraph can subscribe to calls made to the data source contract. This is achieved by defining call handlers referencing the function signature and the mapping handler that will process calls to this function. To process these calls, the mapping handler will receive an `ethereum.Call` as an argument with the typed inputs to and outputs from the call. Calls made at any depth in a transaction's call chain will trigger the mapping, allowing activity with the data source contract through proxy contracts to be captured. +بينما توفر الأحداث طريقة فعالة لجمع التغييرات ذات الصلة بحالة العقد ، تتجنب العديد من العقود إنشاء سجلات لتحسين تكاليف الغاز. في هذه الحالات ، يمكن لـ subgraph الاشتراك في الاستدعاء الذي يتم إجراؤه على عقد مصدر البيانات. يتم تحقيق ذلك من خلال تعريف معالجات الاستدعاء التي تشير إلى signature الدالة ومعالج الـ mapping الذي سيعالج الاستدعاءات لهذه الدالة. لمعالجة هذه المكالمات ، سيتلقى معالج الـ mapping الـ`ethereum.Call` كـ argument مع المدخلات المكتوبة والمخرجات من الاستدعاء. ستؤدي الاستدعاءات التي يتم إجراؤها على أي عمق في سلسلة استدعاء الاجراء إلى تشغيل الـ mapping، مما يسمح بالتقاط النشاط مع عقد مصدر البيانات من خلال عقود الـ proxy. -Call handlers will only trigger in one of two cases: when the function specified is called by an account other than the contract itself or when it is marked as external in Solidity and called as part of another function in the same contract. +لن يتم تشغيل معالجات الاستدعاء إلا في إحدى الحالتين: عندما يتم استدعاء الدالة المحددة بواسطة حساب آخر غير العقد نفسه أو عندما يتم تمييزها على أنها خارجية في Solidity ويتم استدعاؤها كجزء من دالة أخرى في نفس العقد. -> **Note:** Call handlers are not supported on Rinkeby, Goerli or Ganache. Call handlers currently depend on the Parity tracing API and these networks do not support it. +> ** ملاحظة: ** معالجات الاستدعاء غير مدعومة في Rinkeby أو Goerli أو Ganache. تعتمد معالجات الاستدعاء حاليا على Parity tracing API و هذه الشبكات لا تدعمها. -### Defining a Call Handler +### تعريف معالج الاستدعاء -To define a call handler in your manifest simply add a `callHandlers` array under the data source you would like to subscribe to. +لتعريف معالج استدعاء في الـ manifest الخاص بك ، ما عليك سوى إضافة مصفوفة ` callHandlers ` أسفل مصدر البيانات الذي ترغب في الاشتراك فيه. ```yaml dataSources: @@ -724,11 +724,11 @@ dataSources: handler: handleCreateGravatar ``` -The `function` is the normalized function signature to filter calls by. The `handler` property is the name of the function in your mapping you would like to execute when the target function is called in the data source contract. +الـ `function` هي توقيع الدالة المعياري لفلترة الاستدعاءات من خلالها. خاصية `handler` هي اسم الدالة في الـ mapping الذي ترغب في تنفيذه عندما يتم استدعاء الدالة المستهدفة في عقد مصدر البيانات. -### Mapping Function +### دالة الـ Mapping -Each call handler takes a single parameter that has a type corresponding to the name of the called function. In the example subgraph above, the mapping contains a handler for when the `createGravatar` function is called and receives a `CreateGravatarCall` parameter as an argument: +كل معالج استدعاء يأخذ بارامترا واحدا له نوع يتوافق مع اسم الدالة التي تم استدعاؤها. في مثال الـ subgraph أعلاه ، يحتوي الـ mapping على معالج عندما يتم استدعاء الدالة ` createGravatar ` ويتلقى البارامتر ` CreateGravatarCall ` كـ argument: ```typescript import { CreateGravatarCall } from '../generated/Gravity/Gravity' @@ -743,22 +743,22 @@ export function handleCreateGravatar(call: CreateGravatarCall): void { } ``` -The `handleCreateGravatar` function takes a new `CreateGravatarCall` which is a subclass of `ethereum.Call`, provided by `@graphprotocol/graph-ts`, that includes the typed inputs and outputs of the call. The `CreateGravatarCall` type is generated for you when you run `graph codegen`. +الدالة ` handleCreateGravatar ` تأخذ ` CreateGravatarCall ` جديد وهو فئة فرعية من`ethereum.Call`, ، مقدم بواسطة `graphprotocol/graph-ts@`, والذي يتضمن المدخلات والمخرجات المكتوبة للاستدعاء. يتم إنشاء النوع ` CreateGravatarCall ` من أجلك عندما تشغل`graph codegen`. -## Block Handlers +## معالجات الكتلة -In addition to subscribing to contract events or function calls, a subgraph may want to update its data as new blocks are appended to the chain. To achieve this a subgraph can run a function after every block or after blocks that match a predefined filter. +بالإضافة إلى الاشتراك في أحداث العقد أو استدعاءات الدوال، قد يرغب الـ subgraph في تحديث بياناته عند إلحاق كتل جديدة بالسلسلة. لتحقيق ذلك ، يمكن لـ subgraph تشغيل دالة بعد كل كتلة أو بعد الكتل التي تطابق فلترا معرفا مسبقا. -### Supported Filters +### الفلاتر المدعومة ```yaml filter: kind: call ``` -_The defined handler will be called once for every block which contains a call to the contract (data source) the handler is defined under._ +_سيتم استدعاء المعالج المعرف مرة واحدة لكل كتلة تحتوي على استدعاء للعقد (مصدر البيانات) الذي تم تعريف المعالج ضمنه._ -The absense of a filter for a block handler will ensure that the handler is called every block. A data source can only contain one block handler for each filter type. +عدم وجود فلتر لمعالج الكتلة سيضمن أن المعالج يتم استدعاؤه في كل كتلة. يمكن أن يحتوي مصدر البيانات على معالج كتلة واحد فقط لكل نوع فلتر. ```yaml dataSources: @@ -785,9 +785,9 @@ dataSources: kind: call ``` -### Mapping Function +### دالة الـ Mapping -The mapping function will receive an `ethereum.Block` as its only argument. Like mapping functions for events, this function can access existing subgraph entities in the store, call smart contracts and create or update entities. +دالة الـ mapping ستتلقى `ethereum.Block` كوسيطتها الوحيدة. مثل دوال الـ mapping للأحداث ، يمكن لهذه الدالة الوصول إلى كيانات الـ subgraph الموجودة في المخزن، واستدعاء العقود الذكية وإنشاء الكيانات أو تحديثها. ```typescript import { ethereum } from '@graphprotocol/graph-ts' @@ -799,9 +799,9 @@ export function handleBlock(block: ethereum.Block): void { } ``` -## Anonymous Events +## أحداث الـ Anonymous -If you need to process anonymous events in Solidity, that can be achieved by providing the topic 0 of the event, as in the example: +إذا كنت بحاجة إلى معالجة أحداث anonymous في Solidity ، فيمكن تحقيق ذلك من خلال توفير الموضوع 0 للحدث ، كما في المثال: ```yaml eventHandlers: @@ -810,20 +810,20 @@ eventHandlers: handler: handleGive ``` -An event will only be triggered when both the signature and topic 0 match. By default, `topic0` is equal to the hash of the event signature. +سيتم تشغيل حدث فقط عندما يتطابق كل من التوقيع والموضوع 0. بشكل افتراضي ، `topic0` يساوي hash توقيع الحدث. -## Experimental features +## الميزات التجريبية -Starting from `specVersion` `0.0.4`, subgraph features must be explicitly declared in the `features` section at the top level of the manifest file, using their `camelCase` name, as listed in the table below: +بدءًا من ` specVersion ` ` 0.0.4 ` ، يجب الإعلان صراحة عن ميزات الـ subgraph في قسم `features` في المستوى العلوي من ملف الـ manifest ، باستخدام اسم `camelCase` الخاص بهم ، كما هو موضح في الجدول أدناه: -| Feature | Name | -| --------------------------------------------------------- | ------------------------- | -| [Non-fatal errors](#non-fatal-errors) | `nonFatalErrors` | -| [Full-text Search](#defining-fulltext-search-fields) | `fullTextSearch` | -| [Grafting](#grafting-onto-existing-subgraphs) | `grafting` | -| [IPFS on Ethereum Contracts](#ipfs-on-ethereum-contracts) | `ipfsOnEthereumContracts` | +| الميزة | الاسم | +| ----------------------------------------------------- | ------------------------- | +| [أخطاء غير فادحة](#non-fatal-errors) | `nonFatalErrors` | +| [البحث عن نص كامل](#defining-fulltext-search-fields) | `fullTextSearch` | +| [Grafting](#grafting-onto-existing-subgraphs) | `grafting` | +| [IPFS على عقود Ethereum](#ipfs-on-ethereum-contracts) | `ipfsOnEthereumContracts` | -For instance, if a subgraph uses the **Full-Text Search** and the **Non-fatal Errors** features, the `features` field in the manifest should be: +على سبيل المثال ، إذا كان الـ subgraph يستخدم ** بحث النص الكامل ** و ** أخطاء غير فادحة ** ، فإن حقل `features` في الـ manifest يجب أن يكون: ```yaml specVersion: 0.0.4 @@ -834,27 +834,27 @@ features: dataSources: ... ``` -Note that using a feature without declaring it will incur in a **validation error** during subgraph deployment, but no errors will occur if a feature is declared but not used. +لاحظ أن استخدام ميزة دون الإعلان عنها سيؤدي إلى حدوث ** خطأ تحقق من الصحة ** أثناء نشر الـ subgraph ، ولكن لن تحدث أخطاء إذا تم الإعلان عن الميزة ولكن لم يتم استخدامها. -### IPFS on Ethereum Contracts +### IPFS على عقود Ethereum -A common use case for combining IPFS with Ethereum is to store data on IPFS that would be too expensive to maintain on chain, and reference the IPFS hash in Ethereum contracts. +حالة الاستخدام الشائعة لدمج IPFS مع Ethereum هي تخزين البيانات على IPFS التي ستكون مكلفة للغاية للحفاظ عليها في السلسلة ، والإشارة إلى IPFS hash في عقود Ethereum. -Given such IPFS hashes, subgraphs can read the corresponding files from IPFS using `ipfs.cat` and `ipfs.map`. To do this reliably, however, it is required that these files are pinned on the IPFS node that the Graph Node indexing the subgraph connects to. In the case of the [hosted service](https://thegraph.com/hosted-service), this is [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs/). +بالنظر إلى IPFS hashes هذه ، يمكن لـ subgraphs قراءة الملفات المقابلة من IPFS باستخدام ` ipfs.cat ` و ` ipfs.map `. للقيام بذلك بشكل موثوق ، من الضروري أن يتم تثبيت هذه الملفات على عقدة IPFS التي تتصل بها Graph Node التي تقوم بفهرسة الـ subgraph. في حالة [hosted service](https://thegraph.com/hosted-service),يكون هذا [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs/). -> **Note:** The Graph Network does not yet support `ipfs.cat` and `ipfs.map`, and developers should not deploy subgraphs using that functionality to the network via the Studio. +> ** ملاحظة: ** لا تدعم شبكة Graph حتى الآن ` ipfs.cat ` و ` ipfs.map ` ، ويجب على المطورين عدم النشر الـ subgraphs للشبكة باستخدام تلك الوظيفة عبر الـ Studio. -In order to make this easy for subgraph developers, The Graph team wrote a tool for transfering files from one IPFS node to another, called [ipfs-sync](https://github.com/graphprotocol/ipfs-sync). +من أجل تسهيل ذلك على مطوري الـ subgraph ، فريق Graph كتب أداة لنقل الملفات من عقدة IPFS إلى أخرى ، تسمى [ ipfs-sync ](https://github.com/graphprotocol/ipfs-sync). -> **[Feature Management](#experimental-features):** `ipfsOnEthereumContracts` must be declared under `features` in the subgraph manifest. +> **[إدارة الميزات](#experimental-features):** يجب الإعلان عن ` ipfsOnEthereumContracts ` ضمن `features` في subgraph manifest. -### Non-fatal errors +### أخطاء غير فادحة -Indexing errors on already synced subgraphs will, by default, cause the subgraph to fail and stop syncing. Subgraphs can alternatively be configured to continue syncing in the presence of errors, by ignoring the changes made by the handler which provoked the error. This gives subgraph authors time to correct their subgraphs while queries continue to be served against the latest block, though the results will possibly be inconsistent due to the bug that caused the error. Note that some errors are still always fatal, to be non-fatal the error must be known to be deterministic. +افتراضيا ستؤدي أخطاء الفهرسة في الـ subgraphs التي تمت مزامنتها بالفعل ، إلى فشل الـ subgraph وإيقاف المزامنة. يمكن بدلا من ذلك تكوين الـ Subgraphs لمواصلة المزامنة في حالة وجود أخطاء ، عن طريق تجاهل التغييرات التي أجراها المعالج والتي تسببت في حدوث الخطأ. يمنح هذا منشئوا الـ subgraph الوقت لتصحيح الـ subgraphs الخاصة بهم بينما يستمر تقديم الاستعلامات للكتلة الأخيرة ، على الرغم من أن النتائج قد تكون متعارضة بسبب الخطأ الذي تسبب في الخطأ. لاحظ أن بعض الأخطاء لا تزال كارثية دائما ، ولكي تكون غير فادحة ، يجب أن يُعرف الخطأ بأنه حتمي. -> **Note:** The Graph Network does not yet support non-fatal errors, and developers should not deploy subgraphs using that functionality to the network via the Studio. +> ** ملاحظة: ** لا تدعم شبكة Graph حتى الآن الأخطاء غير الفادحة ، ويجب على المطورين عدم نشر الـ subgraphs على الشبكة باستخدام تلك الوظيفة عبر الـ Studio. -Enabling non-fatal errors requires setting the following feature flag on the subgraph manifest: +يتطلب تمكين الأخطاء غير الفادحة تعيين flag الميزة في subgraph manifest كالتالي: ```yaml specVersion: 0.0.4 @@ -864,7 +864,7 @@ features: ... ``` -The query must also opt-in to querying data with potential inconsistencies through the `subgraphError` argument. It is also recommended to query `_meta` to check if the subgraph has skipped over errors, as in the example: +يجب أن يتضمن الاستعلام أيضا الاستعلام عن البيانات ذات التناقضات المحتملة من خلال الوسيطة ` subgraphError `. يوصى أيضا بالاستعلام عن ` _meta ` للتحقق مما إذا كان الـ subgraph قد تخطى الأخطاء ، كما في المثال: ```graphql foos(first: 100, subgraphError: allow) { @@ -876,7 +876,7 @@ _meta { } ``` -If the subgraph encounters an error that query will return both the data and a graphql error with the message `"indexing_error"`, as in this example response: +إذا واجه الـ subgraph خطأ فسيرجع هذا الاستعلام كلا من البيانات وخطأ الـ graphql ضمن رسالة ` "indexing_error" ` ، كما في مثال الاستجابة هذا: ```graphql "data": { @@ -898,11 +898,11 @@ If the subgraph encounters an error that query will return both the data and a g ### Grafting onto Existing Subgraphs -When a subgraph is first deployed, it starts indexing events at the genesis block of the corresponding chain (or at the `startBlock` defined with each data source) In some circumstances, it is beneficial to reuse the data from an existing subgraph and start indexing at a much later block. This mode of indexing is called _Grafting_. Grafting is, for example, useful during development to get past simple errors in the mappings quickly, or to temporarily get an existing subgraph working again after it has failed. +عندما يتم نشر الـ subgraph لأول مرة ، فإنه يبدأ في فهرسة الأحداث من كتلة نشوء السلسلة المتوافقة (أو من ` startBlock ` المعرفة مع كل مصدر بيانات) في بعض الحالات ، يكون من المفيد إعادة استخدام البيانات من subgraph موجود وبدء الفهرسة من كتلة لاحقة. يسمى هذا الوضع من الفهرسة بـ _Grafting_. Grafting ، على سبيل المثال ، مفيد أثناء التطوير لتجاوز الأخطاء البسيطة بسرعة في الـ mappings ، أو للحصول مؤقتا على subgraph موجود يعمل مرة أخرى بعد فشله. -> **Note:** Grafting requires that the Indexer has indexed the base subgraph. It is not recommended on The Graph Network at this time, and developers should not deploy subgraphs using that functionality to the network via the Studio. +> ** ملاحظة: ** الـ Grafting يتطلب أن المفهرس قد فهرس الـ subgraph الأساسي. لا يوصى باستخدامه على شبكة The Graph في الوقت الحالي ، ولا ينبغي للمطورين نشر الـ subgraphs على الشبكة باستخدام تلك الوظيفة عبر الـ Studio. -A subgraph is grafted onto a base subgraph when the subgraph manifest in `subgraph.yaml` contains a `graft` block at the toplevel: +يتم عمل Grafte لـ subgraph في الـ subgraph الأساسي عندما يحتوي الـ subgraph manifest في ` subgraph.yaml ` على كتلة ` graft ` في المستوى العلوي: ```yaml description: ... @@ -911,18 +911,18 @@ graft: block: 7345624 # Block number ``` -When a subgraph whose manifest contains a `graft` block is deployed, Graph Node will copy the data of the `base` subgraph up to and including the given `block` and then continue indexing the new subgraph from that block on. The base subgraph must exist on the target Graph Node instance and must have indexed up to at least the given block. Because of this restriction, grafting should only be used during development or during an emergency to speed up producing an equivalent non-grafted subgraph. +عندما يتم نشر subgraph يحتوي الـ manifest على كتلة ` graft ` ، فإن Graph Node سوف تنسخ بيانات ` base ` subgraph بما في ذلك الـ ` block ` المعطى ثم يتابع فهرسة الـ subgraph الجديد من تلك الكتلة. يجب أن يوجد الـ subgraph الأساسي في instance الـ Graph Node المستهدف ويجب أن يكون قد تمت فهرسته حتى الكتلة المحددة على الأقل. بسبب هذا التقييد ، يجب استخدام الـ grafting فقط أثناء التطوير أو أثناء الطوارئ لتسريع إنتاج non-grafted subgraph مكافئ. -Because grafting copies rather than indexes base data it is much quicker in getting the subgraph to the desired block than indexing from scratch, though the initial data copy can still take several hours for very large subgraphs. While the grafted subgraph is being initialized, the Graph Node will log information about the entity types that have already been copied. +Because grafting copies rather than indexes base data it is much quicker in getting the subgraph to the desired block than indexing from scratch, though the initial data copy can still take several hours for very large subgraphs. أثناء تهيئة الـ grafted subgraph ، سيقوم الـ Graph Node بتسجيل المعلومات حول أنواع الكيانات التي تم نسخها بالفعل. -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right but may deviate from the base subgraph's schema in the following ways: +يمكن أن يستخدم الـ grafted subgraph مخطط GraphQL غير مطابق لمخطط الـ subgraph الأساسي ، ولكنه متوافق معه. يجب أن يكون مخطط الـ subgraph صالحا في حد ذاته ولكنه قد ينحرف عن مخطط الـ subgraph الأساسي بالطرق التالية: -- It adds or removes entity types -- It removes attributes from entity types -- It adds nullable attributes to entity types -- It turns non-nullable attributes into nullable attributes -- It adds values to enums -- It adds or removes interfaces +- يضيف أو يزيل أنواع الكيانات +- يزيل الصفات من أنواع الكيانات +- يضيف صفات nullable لأنواع الكيانات +- يحول صفات non-nullable إلى صفات nullable +- يضيف قيما إلى enums +- يضيف أو يزيل الواجهات - It changes for which entity types an interface is implemented -> **[Feature Management](#experimental-features):** `grafting` must be declared under `features` in the subgraph manifest. +> **[إدارة الميزات](#experimental-features):**يجب الإعلان عن ` التطعيم ` ضمن `features` في subgraph manifest. diff --git a/pages/ar/developer/define-subgraph-hosted.mdx b/pages/ar/developer/define-subgraph-hosted.mdx index 92bf5bd8cd2f..c4ec3a65d2e0 100644 --- a/pages/ar/developer/define-subgraph-hosted.mdx +++ b/pages/ar/developer/define-subgraph-hosted.mdx @@ -1,34 +1,34 @@ --- -title: Define a Subgraph +title: تعريف Subgraph --- -A subgraph defines which data The Graph will index from Ethereum, and how it will store it. Once deployed, it will form a part of a global graph of blockchain data. +يحدد ال Subgraph البيانات التي سيقوم TheGraph بفهرستها من الايثيريوم ، وكيف سيتم تخزينها. بمجرد نشرها ، ستشكل جزءا من رسم graph عالمي لبيانات blockchain. -![Define a Subgraph](/img/define-subgraph.png) +![تعريف Subgraph](/img/define-subgraph.png) -The subgraph definition consists of a few files: +يتكون تعريف Subgraph من عدة ملفات: -- `subgraph.yaml`: a YAML file containing the subgraph manifest +- `Subgraph.yaml `ملف YAML يحتوي على Subgraph manifest -- `schema.graphql`: a GraphQL schema that defines what data is stored for your subgraph, and how to query it via GraphQL +- ` schema.graphql `: مخطط GraphQL يحدد البيانات المخزنة في Subgraph وكيفية الاستعلام عنها عبر GraphQL - `AssemblyScript Mappings`: [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) code that translates from the event data to the entities defined in your schema (e.g. `mapping.ts` in this tutorial) -Before you go into detail about the contents of the manifest file, you need to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) which you will need to build and deploy a subgraph. +قبل الخوض في التفاصيل حول محتويات ملف manifest ، تحتاج إلى تثبيت [Graph CLI](https://github.com/graphprotocol/graph-cli) والذي سوف تحتاجه لبناء ونشر Subgraph. -## Install the Graph CLI +## قم بتثبيت Graph CLI -The Graph CLI is written in JavaScript, and you will need to install either `yarn` or `npm` to use it; it is assumed that you have yarn in what follows. +تمت كتابة Graph CLI بلغة JavaScript ، وستحتاج إلى تثبيتها أيضًا `yarn` or `npm` لتستخدمها؛ من المفترض أن يكون لديك yarn فيما يلي. -Once you have `yarn`, install the Graph CLI by running +بمجرد حصولك على ` yarn ` ، قم بتثبيت Graph CLI عن طريق التشغيل -**Install with yarn:** +**التثبيت بواسطة yarn:** ```bash yarn global add @graphprotocol/graph-cli ``` -**Install with npm:** +**التثبيت بواسطة npm:** ```bash npm install -g @graphprotocol/graph-cli diff --git a/pages/ar/developer/deprecating-a-subgraph.mdx b/pages/ar/developer/deprecating-a-subgraph.mdx index f8966e025c13..2d83064709da 100644 --- a/pages/ar/developer/deprecating-a-subgraph.mdx +++ b/pages/ar/developer/deprecating-a-subgraph.mdx @@ -1,17 +1,17 @@ --- -title: Deprecating a Subgraph +title: إهمال Subgraph --- -So you'd like to deprecate your subgraph on The Graph Explorer. You've come to the right place! Follow the steps below: +إن كنت ترغب في إهمال الـ subgraph الخاص بك في The Graph Explorer. فأنت في المكان المناسب! اتبع الخطوات أدناه: -1. Visit the contract address [here](https://etherscan.io/address/0xadca0dd4729c8ba3acf3e99f3a9f471ef37b6825#writeProxyContract) -2. Call 'deprecateSubgraph' with your own address as the first parameter -3. In the 'subgraphNumber' field, list 0 if it's the first subgraph you're publishing, 1 if it's your second, 2 if it's your third, etc. -4. Inputs for #2 and #3 can be found in your `` which is composed of the `{graphAccount}-{subgraphNumber}`. For example, the [Sushi Subgraph's](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&version=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0-0&view=Overview) ID is `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0>`, which is a combination of `graphAccount` = `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0>` and `subgraphNumber` = `<0>` -5. Voila! Your subgraph will no longer show up on searches on The Graph Explorer. Please note the following: +1. قم بزيارة عنوان العقد [ هنا ](https://etherscan.io/address/0xadca0dd4729c8ba3acf3e99f3a9f471ef37b6825#writeProxyContract) +2. استدعِ "devecateSubgraph" بعنوانك الخاص كأول بارامتر +3. في حقل "subgraphNumber" ، قم بإدراج 0 إذا كان أول subgraph تنشره ، 1 إذا كان الثاني ، 2 إذا كان الثالث ، إلخ. +4. يمكن العثور على مدخلات # 2 و # 3 في `` الخاص بك والذي يتكون من `{graphAccount}-{subgraphNumber}`. فمثلا، [Sushi Subgraph's](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&version=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0-0&view=Overview) ID هو `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0>`,وهو مزيج من `graphAccount` = `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0>` و `subgraphNumber` = `<0>` +5. هاهو! لن يظهر الـ subgraph بعد الآن في عمليات البحث في The Graph Explorer. يرجى ملاحظة ما يلي: -- Curators will not be able to signal on the subgraph anymore -- Curators that already signaled on the subgraph will be able to withdraw their signal at an average share price -- Deprecated subgraphs will be indicated with an error message. +- لن يتمكن المنسقون من الإشارة على الـ subgraph بعد الآن +- سيتمكن المنشقون الذين قد أشاروا شابقا على الـ subgraph من سحب إشاراتهم بمتوسط سعر السهم +- ستتم تحديد الـ subgraphs المهملة برسالة خطأ. -If you interacted with the now deprecated subgraph, you'll be able to find it in your user profile under the "Subgraphs", "Indexing", or "Curating" tab respectively. +إذا تفاعلت مع الـ subgraph المهمل ، فستتمكن من العثور عليه في ملف تعريف المستخدم الخاص بك ضمن علامة التبويب "Subgraphs" أو "Indexing" أو "Curating" على التوالي. diff --git a/pages/ar/developer/developer-faq.mdx b/pages/ar/developer/developer-faq.mdx index 41449c60e5ab..1f0a5cbd6f81 100644 --- a/pages/ar/developer/developer-faq.mdx +++ b/pages/ar/developer/developer-faq.mdx @@ -1,70 +1,70 @@ --- -title: Developer FAQs +title: الأسئلة الشائعة للمطورين --- -### 1. Can I delete my subgraph? +### 1. هل يمكنني حذف ال Subgraph الخاص بي؟ -It is not possible to delete subgraphs once they are created. +لا يمكن حذف ال Subgraph بمجرد إنشائها. -### 2. Can I change my subgraph name? +### 2. هل يمكنني تغيير اسم ال Subgraph الخاص بي؟ -No. Once a subgraph is created, the name cannot be changed. Make sure to think of this carefully before you create your subgraph so it is easily searchable and identifiable by other dapps. +لا. بمجرد إنشاء ال Subgraph ، لا يمكن تغيير الاسم. تأكد من التفكير بعناية قبل إنشاء ال Subgraph الخاص بك حتى يسهل البحث عنه والتعرف عليه من خلال ال Dapps الأخرى. -### 3. Can I change the GitHub account associated with my subgraph? +### 3. هل يمكنني تغيير حساب GitHub المرتبط ب Subgraph الخاص بي؟ -No. Once a subgraph is created, the associated GitHub account cannot be changed. Make sure to think of this carefully before you create your subgraph. +لا. بمجرد إنشاء ال Subgraph ، لا يمكن تغيير حساب GitHub المرتبط. تأكد من التفكير بعناية قبل إنشاء ال Subgraph الخاص بك. -### 4. Am I still able to create a subgraph if my smart contracts don't have events? +### 4. هل يمكنني إنشاء Subgraph إذا لم تكن العقود الذكية الخاصة بي تحتوي على أحداث؟ -It is highly recommended that you structure your smart contracts to have events associated with data you are interested in querying. Event handlers in the subgraph are triggered by contract events, and are by far the fastest way to retrieve useful data. +من المستحسن جدا أن تقوم بإنشاء عقودك الذكية بحيث يكون لديك أحداث مرتبطة بالبيانات التي ترغب في الاستعلام عنها. يتم تشغيل معالجات الأحداث في subgraph بواسطة أحداث العقد، وهي إلى حد بعيد أسرع طريقة لاسترداد البيانات المفيدة. -If the contracts you are working with do not contain events, your subgraph can use call and block handlers to trigger indexing. Although this is not recommended as performance will be significantly slower. +إذا كانت العقود التي تعمل معها لا تحتوي على أحداث، فيمكن أن يستخدم ال Subgraph معالجات الاتصال والحظر لتشغيل الفهرسة. وهذا غير موصى به لأن الأداء سيكون أبطأ بشكل ملحوظ. -### 5. Is it possible to deploy one subgraph with the same name for multiple networks? +### 5. هل من الممكن نشر Subgraph واحد تحمل نفس الاسم لشبكات متعددة؟ -You will need separate names for multiple networks. While you can't have different subgraphs under the same name, there are convenient ways of having a single codebase for multiple networks. Find more on this in our documentation: [Redeploying a Subgraph](/hosted-service/deploy-subgraph-hosted#redeploying-a-subgraph) +ستحتاج إلى أسماء مختلفه لشبكات متعددة. ولا يمكن أن يكون لديك Subgraph مختلف تحت نفس الاسم ، إلا أن هناك طرقًا ملائمة لأمتلاك قاعدة بيانات واحدة لشبكات متعددة. اكتشف المزيد حول هذا الأمر في وثائقنا: [ إعادة نشر ال Subgraph ](/hosted-service/deploy-subgraph-hosted#redeploying-a-subgraph) -### 6. How are templates different from data sources? +### 6. كيف تختلف النماذج عن مصادر البيانات؟ -Templates allow you to create data sources on the fly, while your subgraph is indexing. It might be the case that your contract will spawn new contracts as people interact with it, and since you know the shape of those contracts (ABI, events, etc) up front you can define how you want to index them in a template and when they are spawned your subgraph will create a dynamic data source by supplying the contract address. +تسمح لك النماذج بإنشاء مصادر البيانات على الفور ، أثناء فهرسة ال Subgraph الخاص بك. قد يكون الأمر هو أن عقدك سينتج عنه عقود جديدة عندما يتفاعل الأشخاص معه ، وبما أنك تعرف شكل هذه العقود (ABI ، الأحداث ، إلخ) مسبقًا ، يمكنك تحديد الطريقة التي تريد فهرستها بها في النموذج ومتى يتم إنتاجها ، وسيقوم ال Subgraph الخاص بك بإنشاء مصدر بيانات ديناميكي عن طريق توفير عنوان العقد. -Check out the "Instantiating a data source template" section on: [Data Source Templates](/developer/create-subgraph-hosted#data-source-templates). +راجع قسم "إنشاء نموذج مصدر بيانات" في: [ نماذج مصدر البيانات ](/developer/create-subgraph-hosted#data-source-templates). -### 7. How do I make sure I'm using the latest version of graph-node for my local deployments? +### 7. كيف أتأكد من أنني أستخدم أحدث إصدار من graph-node لعمليات النشر المحلية الخاصة بي؟ -You can run the following command: +يمكنك تشغيل الأمر التالي: ```sh docker pull graphprotocol/graph-node:latest ``` -**NOTE:** docker / docker-compose will always use whatever graph-node version was pulled the first time you ran it, so it is important to do this to make sure you are up to date with the latest version of graph-node. +** ملاحظة: ** ستستخدم docker / docker-compose دائمًا أي إصدار من graph-node تم سحبه في المرة الأولى التي قمت بتشغيلها ، لذلك من المهم القيام بذلك للتأكد من أنك محدث بأحدث إصدار graph-node. -### 8. How do I call a contract function or access a public state variable from my subgraph mappings? +### 8. كيف يمكنني استدعاء دالة العقد أو الوصول إلى متغير الحالة العامة من Subgraph mappings الخاصة بي؟ -Take a look at `Access to smart contract` state inside the section [AssemblyScript API](/developer/assemblyscript-api). +ألقِ نظرة على حالة ` الوصول إلى العقد الذكي ` داخل القسم [ AssemblyScript API ](/developer/assemblyscript-api). -### 9. Is it possible to set up a subgraph using `graph init` from `graph-cli` with two contracts? Or should I manually add another datasource in `subgraph.yaml` after running `graph init`? +### 9. هل من الممكن إنشاء Subgraph باستخدام`graph init` from `graph-cli`بعقدين؟ أو هل يجب علي إضافة مصدر بيانات آخر يدويًا في ` subgraph.yaml ` بعد تشغيل ` graph init `؟ -Unfortunately this is currently not possible. `graph init` is intended as a basic starting point, from which you can then add more data sources manually. +للأسف هذا غير ممكن حاليا. الغرض من ` graph init ` هو أن تكون نقطة بداية أساسية حيث يمكنك من خلالها إضافة المزيد من مصادر البيانات يدويًا. -### 10. I want to contribute or add a GitHub issue, where can I find the open source repositories? +### 10. أرغب في المساهمة أو إضافة مشكلة GitHub ، أين يمكنني العثور على مستودعات مفتوحة المصدر؟ - [graph-node](https://github.com/graphprotocol/graph-node) - [graph-cli](https://github.com/graphprotocol/graph-cli) - [graph-ts](https://github.com/graphprotocol/graph-ts) -### 11. What is the recommended way to build "autogenerated" ids for an entity when handling events? +### 11. ما هي الطريقة الموصى بها لإنشاء معرفات "تلقائية" لكيان عند معالجة الأحداث؟ -If only one entity is created during the event and if there's nothing better available, then the transaction hash + log index would be unique. You can obfuscate these by converting that to Bytes and then piping it through `crypto.keccak256` but this won't make it more unique. +إذا تم إنشاء كيان واحد فقط أثناء الحدث ولم يكن هناك أي شيء متاح بشكل أفضل ، فسيكون hash الإجراء + فهرس السجل فريدا. يمكنك تشويشها عن طريق تحويلها إلى Bytes ثم تمريرها عبر ` crypto.keccak256 ` ولكن هذا لن يجعلها فريدة من نوعها. -### 12. When listening to multiple contracts, is it possible to select the contract order to listen to events? +### 12. عند الاستماع إلى عدة عقود ، هل من الممكن تحديد أمر العقد للاستماع إلى الأحداث؟ -Within a subgraph, the events are always processed in the order they appear in the blocks, regardless of whether that is across multiple contracts or not. +ضمن ال Subgraph ، تتم معالجة الأحداث دائمًا بالترتيب الذي تظهر به في الكتل ، بغض النظر عما إذا كان ذلك عبر عقود متعددة أم لا. -### 13. Is it possible to differentiate between networks (mainnet, Kovan, Ropsten, local) from within event handlers? +### 13. هل من الممكن التفريق بين الشبكات (mainnet، Kovan، Ropsten، local) من داخل معالجات الأحداث؟ -Yes. You can do this by importing `graph-ts` as per the example below: +نعم. يمكنك القيام بذلك عن طريق استيراد ` graph-ts ` كما في المثال أدناه: ```javascript import { dataSource } from '@graphprotocol/graph-ts' @@ -73,39 +73,39 @@ dataSource.network() dataSource.address() ``` -### 14. Do you support block and call handlers on Rinkeby? +### 14. هل تدعم معالجات الكتل والإستدعاء على Rinkeby؟ -On Rinkeby we support block handlers, but without `filter: call`. Call handlers are not supported for the time being. +في Rinkeby ، ندعم معالجات الكتل ، لكن بدون ` filter: call `. معالجات الاستدعاء غير مدعومة في الوقت الحالي. -### 15. Can I import ethers.js or other JS libraries into my subgraph mappings? +### 15. هل يمكنني استيراد ethers.js أو مكتبات JS الأخرى إلى ال Subgraph mappings الخاصة بي؟ -Not currently, as mappings are written in AssemblyScript. One possible alternative solution to this is to store raw data in entities and perform logic that requires JS libraries on the client. +ليس حاليًا ، حيث تتم كتابة ال mappings في AssemblyScript. أحد الحلول البديلة الممكنة لذلك هو تخزين البيانات الأولية في الكيانات وتنفيذ المنطق الذي يتطلب مكتبات JS على ال client. -### 16. Is it possible to specifying what block to start indexing on? +### 16. هل من الممكن تحديد الكتلة التي سيتم بدء الفهرسة عليها؟ -Yes. `dataSources.source.startBlock` in the `subgraph.yaml` file specifies the number of the block that the data source starts indexing from. In most cases we suggest using the block in which the contract was created: Start blocks +نعم. يحدد ` dataSources.source.startBlock ` في ملف ` subgraph.yaml ` رقم الكتلة الذي يبدأ مصدر البيانات الفهرسة منها. في معظم الحالات نقترح استخدام الكتلة التي تم إنشاء العقد من خلالها: Start blocks -### 17. Are there some tips to increase performance of indexing? My subgraph is taking a very long time to sync. +### 17. هل هناك بعض النصائح لتحسين أداء الفهرسة؟ تستغرق مزامنة ال subgraph وقتًا طويلاً جدًا. -Yes, you should take a look at the optional start block feature to start indexing from the block that the contract was deployed: [Start blocks](/developer/create-subgraph-hosted#start-blocks) +نعم ، يجب إلقاء نظرة على ميزة start block الاختيارية لبدء الفهرسة من الكتل التي تم نشر العقد: [ start block ](/developer/create-subgraph-hosted#start-blocks) -### 18. Is there a way to query the subgraph directly to determine what the latest block number it has indexed? +### 18. هل هناك طريقة للاستعلام عن ال Subgraph بشكل مباشر مباشرةً رقم الكتلة الأخير الذي تمت فهرسته؟ -Yes! Try the following command, substituting "organization/subgraphName" with the organization under it is published and the name of your subgraph: +نعم! Try the following command, substituting "organization/subgraphName" with the organization under it is published and the name of your subgraph: ```sh curl -X POST -d '{ "query": "{indexingStatusForCurrentVersion(subgraphName: \"organization/subgraphName\") { chains { latestBlock { hash number }}}}"}' https://api.thegraph.com/index-node/graphql ``` -### 19. What networks are supported by The Graph? +### 19. ما هي الشبكات الذي يدعمها The Graph؟ -The graph-node supports any EVM-compatible JSON RPC API chain. +تدعم graph-node أي سلسلة API JSON RPC متوافقة مع EVM. -The Graph Network supports subgraphs indexing mainnet Ethereum: +شبكة The Graph تدعم ال subgraph وذلك لفهرسة mainnet Ethereum: - `mainnet` -In the Hosted Service, the following networks are supported: +في ال Hosted Service ، يتم دعم الشبكات التالية: - Ethereum mainnet - Kovan @@ -129,9 +129,9 @@ In the Hosted Service, the following networks are supported: - Fuse - Moonbeam - Arbitrum One -- Arbitrum Testnet (on Rinkeby) +- (Arbitrum Testnet (on Rinkeby - Optimism -- Optimism Testnet (on Kovan) +- (Optimism Testnet (on Kovan There is work in progress towards integrating other blockchains, you can read more in our repo: [RFC-0003: Multi-Blockchain Support](https://github.com/graphprotocol/rfcs/pull/8/files). diff --git a/pages/ar/developer/distributed-systems.mdx b/pages/ar/developer/distributed-systems.mdx index 894fcbe2e18b..e647ca602f02 100644 --- a/pages/ar/developer/distributed-systems.mdx +++ b/pages/ar/developer/distributed-systems.mdx @@ -1,37 +1,37 @@ --- -title: Distributed Systems +title: الانظمة الموزعة --- -The Graph is a protocol implemented as a distributed system. +The Graph هو بروتوكول يتم تنفيذه كنظام موزع. -Connections fail. Requests arrive out of order. Different computers with out-of-sync clocks and states process related requests. Servers restart. Re-orgs happen between requests. These problems are inherent to all distributed systems but are exacerbated in systems operating at a global scale. +فشل الاتصالات. وصول الطلبات خارج الترتيب. أجهزة الكمبيوتر المختلفة ذات الساعات والحالات غير المتزامنة تعالج الطلبات ذات الصلة. الخوادم تعيد التشغيل. حدوث عمليات Re-orgs بين الطلبات. هذه المشاكل متأصلة في جميع الأنظمة الموزعة ولكنها تتفاقم في الأنظمة التي تعمل على نطاق عالمي. -Consider this example of what may occur if a client polls an Indexer for the latest data during a re-org. +ضع في اعتبارك هذا المثال لما قد يحدث إذا قام العميل بـ polls للمفهرس للحصول على أحدث البيانات أثناء re-org. -1. Indexer ingests block 8 -2. Request served to the client for block 8 -3. Indexer ingests block 9 -4. Indexer ingests block 10A -5. Request served to the client for block 10A -6. Indexer detects reorg to 10B and rolls back 10A -7. Request served to the client for block 9 -8. Indexer ingests block 10B -9. Indexer ingests block 11 -10. Request served to the client for block 11 +1. المفهرس يستوعب الكتلة 8 +2. تقديم الطلب للعميل للمجموعة 8 +3. يستوعب المفهرس الكتلة 9 +4. المفهرس يستوعب الكتلة 10A +5. تقديم الطلب للعميل للكتلة 10A +6. يكتشف المفهرس reorg لـ 10B ويسترجع 10A +7. تقديم الطلب للعميل للكتلة 9 +8. المفهرس يستوعب الكتلة 10B +9. المفهرس يستوعب الكتلة 11 +10. تقديم الطلب للعميل للكتلة 11 -From the point of view of the Indexer, things are progressing forward logically. Time is moving forward, though we did have to roll back an uncle block and play the block under consensus forward on top of it. Along the way, the Indexer serves requests using the latest state it knows about at that time. +من وجهة نظر المفهرس ، تسير الأمور إلى الأمام بشكل منطقي. الوقت يمضي قدما ، على الرغم من أننا اضطررنا إلى التراجع عن كتلة الـ uncle وتشغيل الكتلة وفقا للاتفاق. على طول الطريق ، يقدم المفهرس الطلبات باستخدام أحدث حالة يعرفها في ذلك الوقت. -From the point of view of the client, however, things appear chaotic. The client observes that the responses were for blocks 8, 10, 9, and 11 in that order. We call this the "block wobble" problem. When a client experiences block wobble, data may appear to contradict itself over time. The situation worsens when we consider that Indexers do not all ingest the latest blocks simultaneously, and your requests may be routed to multiple Indexers. +لكن من وجهة نظر العميل ، تبدو الأمور مشوشة. يلاحظ العميل أن الردود كانت للكتل 8 و 10 و 9 و 11 بهذا الترتيب. نسمي هذا مشكلة "تذبذب الكتلة". عندما يواجه العميل تذبذبا في الكتلة ، فقد تظهر البيانات متناقضة مع نفسها بمرور الوقت. يزداد الموقف سوءا عندما نعتبر أن المفهرسين لا يستوعبون جميع الكتل الأخيرة في وقت واحد ، وقد يتم توجيه طلباتك إلى عدة مفهرسين. -It is the responsibility of the client and server to work together to provide consistent data to the user. Different approaches must be used depending on the desired consistency as there is no one right program for every problem. +تقع على عاتق العميل والخادم مسؤولية العمل معا لتوفير بيانات متسقة للمستخدم. يجب استخدام طرق مختلفة اعتمادا على الاتساق المطلوب حيث لا يوجد برنامج واحد مناسب لكل مشكلة. -Reasoning through the implications of distributed systems is hard, but the fix may not be! We've established APIs and patterns to help you navigate some common use-cases. The following examples illustrate those patterns but still elide details required by production code (like error handling and cancellation) to not obfuscate the main ideas. +الاستنتاج من خلال الآثار المترتبة على الأنظمة الموزعة أمر صعب ، لكن الإصلاح قد لا يكون كذلك! لقد أنشأنا APIs وأنماط لمساعدتك على تصفح بعض حالات الاستخدام الشائعة. توضح الأمثلة التالية هذه الأنماط ولكنها لا تزال تتجاهل التفاصيل التي يتطلبها كود الإنتاج (مثل معالجة الأخطاء والإلغاء) حتى لا يتم تشويش الأفكار الرئيسية. -## Polling for updated data +## Polling للبيانات المحدثة -The Graph provides the `block: { number_gte: $minBlock }` API, which ensures that the response is for a single block equal or higher to `$minBlock`. If the request is made to a `graph-node` instance and the min block is not yet synced, `graph-node` will return an error. If `graph-node` has synced min block, it will run the response for the latest block. If the request is made to an Edge & Node Gateway, the Gateway will filter out any Indexers that have not yet synced min block and make the request for the latest block the Indexer has synced. +The Graph يوفر `block: { number_gte: $minBlock }` API ، والتي تضمن أن تكون الاستجابة لكتلة واحدة تزيد أو تساوي `$minBlock`. إذا تم إجراء الطلب لـ `graph-node` instance ولم تتم مزامنة الكتلة الدنيا بعد ، فسيرجع `graph-node` بخطأ. إذا قام `graph-node` بمزامنة الكتلة الدنيا ، فسيتم تشغيل الاستجابة لأحدث كتلة. إذا تم تقديم الطلب إلى Edge & Node Gateway ، ستقوم الـ Gateway بفلترة المفهرسين الذين لم يقوموا بعد بمزامنة الكتلة الدنيا وتجعل الطلب لأحدث كتلة قام المفهرس بمزامنتها. -We can use `number_gte` to ensure that time never travels backward when polling for data in a loop. Here is an example: +يمكننا استخدام ` number_gte ` لضمان عدم عودة الوقت إلى الوراء عند عمل polling للبيانات في الحلقة. هنا مثال لذلك: ```javascript /// Updates the protocol.paused variable to the latest @@ -73,11 +73,11 @@ async function updateProtocolPaused() { } ``` -## Fetching a set of related items +## جلب مجموعة من العناصر المرتبطة -Another use-case is retrieving a large set or, more generally, retrieving related items across multiple requests. Unlike the polling case (where the desired consistency was to move forward in time), the desired consistency is for a single point in time. +حالة أخرى هي جلب مجموعة كبيرة أو بشكل عام جلب العناصر المرتبطة عبر طلبات متعددة. على عكس حالة الـ polling (حيث كان التناسق المطلوب هو المضي قدما في الزمن) ، فإن الاتساق المطلوب هو لنقطة واحدة في الزمن. -Here we will use the `block: { hash: $blockHash }` argument to pin all of our results to the same block. +هنا سوف نستخدم الوسيطة `block: { hash: $blockHash }` لتثبيت جميع نتائجنا في نفس الكتلة. ```javascript /// Gets a list of domain names from a single block using pagination @@ -129,4 +129,4 @@ async function getDomainNames() { } ``` -Note that in case of a re-org, the client will need to retry from the first request to update the block hash to a non-uncle block. +لاحظ أنه في حالة re-org ، سيحتاج العميل إلى إعادة المحاولة من الطلب الأول لتحديث hash الكتلة إلى كتلة non-uncle. diff --git a/pages/ar/developer/graphql-api.mdx b/pages/ar/developer/graphql-api.mdx index 65928d8734e0..15ab979dacff 100644 --- a/pages/ar/developer/graphql-api.mdx +++ b/pages/ar/developer/graphql-api.mdx @@ -2,15 +2,15 @@ title: GraphQL API --- -This guide explains the GraphQL Query API that is used for the Graph Protocol. +يشرح هذا الدليل GraphQL Query API المستخدمة في بروتوكول Graph. -## Queries +## الاستعلامات -In your subgraph schema you define types called `Entities`. For each `Entity` type, an `entity` and `entities` field will be generated on the top-level `Query` type. Note that `query` does not need to be included at the top of the `graphql` query when using The Graph. +في مخطط الـ subgraph الخاص بك ، يمكنك تعريف أنواع وتسمى `Entities`. لكل نوع من `Entity` ، سيتم إنشاء حقل `entity` و `entities` في المستوى الأعلى من نوع `Query`. لاحظ أنه لا يلزم تضمين ` query ` أعلى استعلام ` graphql ` عند استخدام The Graph. -#### Examples +#### أمثلة -Query for a single `Token` entity defined in your schema: +الاستعلام عن كيان `Token` واحد معرف في مخططك: ```graphql { @@ -21,9 +21,9 @@ Query for a single `Token` entity defined in your schema: } ``` -**Note:** When querying for a single entity, the `id` field is required and it must be a string. +** ملاحظة: ** عند الاستعلام عن كيان واحد ، فإن الحقل ` id ` يكون مطلوبا ويجب أن يكون string. -Query all `Token` entities: +الاستعلام عن جميع كيانات `Token`: ```graphql { @@ -34,11 +34,11 @@ Query all `Token` entities: } ``` -### Sorting +### الفرز -When querying a collection, the `orderBy` parameter may be used to sort by a specific attribute. Additionally, the `orderDirection` can be used to specify the sort direction, `asc` for ascending or `desc` for descending. +عند الاستعلام عن مجموعة ، يمكن استخدام البارامتر `orderBy` للترتيب حسب صفة معينة. بالإضافة إلى ذلك ، يمكن استخدام ` OrderDirection ` لتحديد اتجاه الفرز ،`asc` للترتيب التصاعدي أو `desc` للترتيب التنازلي. -#### Example +#### مثال ```graphql { @@ -49,17 +49,17 @@ When querying a collection, the `orderBy` parameter may be used to sort by a spe } ``` -### Pagination +### ترقيم الصفحات -When querying a collection, the `first` parameter can be used to paginate from the beginning of the collection. It is worth noting that the default sort order is by ID in ascending alphanumeric order, not by creation time. +عند الاستعلام عن مجموعة ، يمكن استخدام البارامتر `first` لترقيم الصفحات من بداية المجموعة. من الجدير بالذكر أن ترتيب الفرز الافتراضي يكون حسب الـ ID بترتيب رقمي تصاعدي ، وليس حسب وقت الإنشاء. -Further, the `skip` parameter can be used to skip entities and paginate. e.g. `first:100` shows the first 100 entities and `first:100, skip:100` shows the next 100 entities. +علاوة على ذلك ، يمكن استخدام البارامتر ` skip ` لتخطي الكيانات وترقيم الصفحات. على سبيل المثال `first:100` يعرض أول 100 عنصر و `first:100, skip:100` يعرض 100 عنصر التالية. -Queries should avoid using very large `skip` values since they generally perform poorly. For retrieving a large number of items, it is much better to page through entities based on an attribute as shown in the last example. +الاستعلامات يجب أن تتجنب استخدام قيم `skip` كبيرة جدا نظرا لأنها تؤدي بشكل عام أداء ضعيفا. لجلب عدد كبير من العناصر ، من الأفضل تصفح الكيانات بناء على صفة كما هو موضح في المثال الأخير. -#### Example +#### مثال -Query the first 10 tokens: +استعلم عن أول 10 توكن: ```graphql { @@ -70,11 +70,11 @@ Query the first 10 tokens: } ``` -To query for groups of entities in the middle of a collection, the `skip` parameter may be used in conjunction with the `first` parameter to skip a specified number of entities starting at the beginning of the collection. +للاستعلام عن مجموعات الكيانات في منتصف المجموعة ، يمكن استخدام البارامتر `skip` بالاصافة لبارامتر `first` لتخطي عدد محدد من الكيانات بدءا من بداية المجموعة. -#### Example +#### مثال -Query 10 `Token` entities, offset by 10 places from the beginning of the collection: +الاستعلام عن 10 كيانات `Token` ،بإزاحة 10 أماكن من بداية المجموعة: ```graphql { @@ -85,9 +85,9 @@ Query 10 `Token` entities, offset by 10 places from the beginning of the collect } ``` -#### Example +#### مثال -If a client needs to retrieve a large number of entities, it is much more performant to base queries on an attribute and filter by that attribute. For example, a client would retrieve a large number of tokens using this query: +إذا احتاج العميل إلى جلب عدد كبير من الكيانات ، فمن الأفضل أن تستند الاستعلامات إلى إحدى الصفات والفلترة حسب تلك الصفة. على سبيل المثال ، قد يجلب العميل عددا كبيرا من التوكن باستخدام هذا الاستعلام: ```graphql { @@ -100,15 +100,15 @@ If a client needs to retrieve a large number of entities, it is much more perfor } ``` -The first time, it would send the query with `lastID = ""`, and for subsequent requests would set `lastID` to the `id` attribute of the last entity in the previous request. This approach will perform significantly better than using increasing `skip` values. +في المرة الأولى ، سيتم إرسال الاستعلام مع `lastID = ""` ، وبالنسبة للطلبات اللاحقة ، سيتم تعيين `lastID` إلى صفة `id` للكيان الأخير في الطلب السابق. أداء هذا الأسلوب أفضل بكثير من استخدام زيادة قيم `skip`. -### Filtering +### الفلترة -You can use the `where` parameter in your queries to filter for different properties. You can filter on mulltiple values within the `where` parameter. +يمكنك استخدام البارامتر `where` في الاستعلام لتصفية الخصائص المختلفة. يمكنك الفلترة على قيم متعددة ضمن البارامتر `where`. -#### Example +#### مثال -Query challenges with `failed` outcome: +تحديات الاسعلام مع نتيجة `failed`: ```graphql { @@ -122,9 +122,9 @@ Query challenges with `failed` outcome: } ``` -You can use suffixes like `_gt`, `_lte` for value comparison: +يمكنك استخدام لواحق مثل ` _gt ` ، ` _lte ` لمقارنة القيم: -#### Example +#### مثال ```graphql { @@ -136,7 +136,7 @@ You can use suffixes like `_gt`, `_lte` for value comparison: } ``` -Full list of parameter suffixes: +القائمة الكاملة للواحق البارامترات: ```graphql _not @@ -154,17 +154,17 @@ _not_starts_with _not_ends_with ``` -Please note that some suffixes are only supported for specific types. For example, `Boolean` only supports `_not`, `_in`, and `_not_in`. +يرجى ملاحظة أن بعض اللواحق مدعومة فقط لأنواع معينة. على سبيل المثال ، ` Boolean ` يدعم فقط ` _not ` و ` _in ` و ` _not_in `. ### Time-travel queries -You can query the state of your entities not just for the latest block, which is the by default, but also for an arbitrary block in the past. The block at which a query should happen can be specified either by its block number or its block hash by including a `block` argument in the toplevel fields of queries. +يمكنك الاستعلام عن حالة الكيانات الخاصة بك ليس فقط للكتلة الأخيرة ، والتي هي افتراضيا ، ولكن أيضا لكتلة اعتباطية في الماضي. يمكن تحديد الكتلة التي يجب أن يحدث فيها الاستعلام إما عن طريق رقم الكتلة أو hash الكتلة الخاص بها عن طريق تضمين وسيطة ` block ` في حقول المستوى الأعلى للاستعلامات. -The result of such a query will not change over time, i.e., querying at a certain past block will return the same result no matter when it is executed, with the exception that if you query at a block very close to the head of the Ethereum chain, the result might change if that block turns out to not be on the main chain and the chain gets reorganized. Once a block can be considered final, the result of the query will not change. +لن تتغير نتيجة مثل هذا الاستعلام بمرور الوقت ، أي أن الاستعلام في كتلة سابقة معينة سيعيد نفس النتيجة بغض النظر عن وقت تنفيذها ، باستثناء أنه إذا قمت بالاستعلام في كتلة قريبة جدا من رأس سلسلة Ethereum ، قد تتغير النتيجة إذا تبين أن هذه الكتلة ليست في السلسلة الرئيسية وتمت إعادة تنظيم السلسلة. بمجرد اعتبار الكتلة نهائية ، لن تتغير نتيجة الاستعلام. -Note that the current implementation is still subject to certain limitations that might violate these gurantees. The implementation can not always tell that a given block hash is not on the main chain at all, or that the result of a query by block hash for a block that can not be considered final yet might be influenced by a block reorganization running concurrently with the query. They do not affect the results of queries by block hash when the block is final and known to be on the main chain. [This issue](https://github.com/graphprotocol/graph-node/issues/1405) explains what these limitations are in detail. +لاحظ أن التنفيذ الحالي لا يزال يخضع لقيود معينة قد تنتهك هذه الضمانات. لا يمكن للتنفيذ دائما أن يخبرنا أن hash كتلة معينة ليست في السلسلة الرئيسية ، أو أن نتيجة استعلام لكتلة عن طريق hash الكتلة لا يمكن اعتبارها نهائية ومع ذلك قد تتأثر بإعادة تنظيم الكتلة التي تعمل بشكل متزامن مع الاستعلام. لا تؤثر نتائج الاستعلامات عن طريق hash الكتلة عندما تكون الكتلة نهائية ومعروفة بأنها موجودة في السلسلة الرئيسية. [ تشرح هذه المشكلة ](https://github.com/graphprotocol/graph-node/issues/1405) ماهية هذه القيود بالتفصيل. -#### Example +#### مثال ```graphql { @@ -178,9 +178,9 @@ Note that the current implementation is still subject to certain limitations tha } ``` -This query will return `Challenge` entities, and their associated `Application` entities, as they existed directly after processing block number 8,000,000. +سيعود هذا الاستعلام بكيانات ` Challenge ` وكيانات ` Application ` المرتبطة بها ، كما كانت موجودة مباشرة بعد معالجة رقم الكتلة 8،000،000. -#### Example +#### مثال ```graphql { @@ -194,26 +194,26 @@ This query will return `Challenge` entities, and their associated `Application` } ``` -This query will return `Challenge` entities, and their associated `Application` entities, as they existed directly after processing the block with the given hash. +سيعود هذا الاستعلام بكيانات ` Challenge ` وكيانات ` Application ` المرتبطة بها ، كما كانت موجودة مباشرة بعد معالجة الكتلة باستخدام hash المحددة. -### Fulltext Search Queries +### استعلامات بحث النص الكامل -Fulltext search query fields provide an expressive text search API that can be added to the subgraph schema and customized. Refer to [Defining Fulltext Search Fields](/developer/create-subgraph-hosted#defining-fulltext-search-fields) to add fulltext search to your subgraph. +حقول استعلام البحث عن نص كامل توفر API للبحث عن نص تعبيري يمكن إضافتها إلى مخطط الـ subgraph وتخصيصها. راجع [ تعريف حقول بحث النص الكامل ](/developer/create-subgraph-hosted#defining-fulltext-search-fields) لإضافة بحث نص كامل إلى الـ subgraph الخاص بك. -Fulltext search queries have one required field, `text`, for supplying search terms. Several special fulltext operators are available to be used in this `text` search field. +استعلامات البحث عن النص الكامل لها حقل واحد مطلوب ، وهو ` text ` ، لتوفير عبارة البحث. تتوفر العديد من عوامل النص الكامل الخاصة لاستخدامها في حقل البحث ` text `. -Fulltext search operators: +عوامل تشغيل البحث عن النص الكامل: -| Symbol | Operator | Description | -| --- | --- | --- | -| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | -| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | -| `<->` | `Follow by` | Specify the distance between two words. | -| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | +| رمز | عامل التشغيل | الوصف | +| ----------- | ------------ | --------------------------------------------------------------------------------------------------------------------------- | +| `&` | `And` | لدمج عبارات بحث متعددة في فلتر للكيانات التي تتضمن جميع العبارات المتوفرة | +| | | `Or` | الاستعلامات التي تحتوي على عبارات بحث متعددة مفصولة بواسطة عامل التشغيل or ستعيد جميع الكيانات المتطابقة من أي عبارة متوفرة | +| `<->` | `Follow by` | يحدد المسافة بين كلمتين. | +| `:*` | `Prefix` | يستخدم عبارة البحث prefix للعثور على الكلمات التي تتطابق بادئتها (مطلوب حرفان.) | -#### Examples +#### أمثلة -Using the `or` operator, this query will filter to blog entities with variations of either "anarchism" or "crumpet" in their fulltext fields. +باستخدام العامل ` or` ، سيقوم الاستعلام هذا بتصفية blog الكيانات التي تحتوي على أشكال مختلفة من "anarchism" أو "crumpet" في حقول النص الكامل الخاصة بها. ```graphql { @@ -226,7 +226,7 @@ Using the `or` operator, this query will filter to blog entities with variations } ``` -The `follow by` operator specifies a words a specific distance apart in the fulltext documents. The following query will return all blogs with variations of "decentralize" followed by "philosophy" +العامل ` follow by ` يحدد الكلمات بمسافة محددة عن بعضها في مستندات النص-الكامل. الاستعلام التالي سيعيد جميع الـ blogs التي تحتوي على أشكال مختلفة من "decentralize" متبوعة بكلمة "philosophy" ```graphql { @@ -239,7 +239,7 @@ The `follow by` operator specifies a words a specific distance apart in the full } ``` -Combine fulltext operators to make more complex filters. With a pretext search operator combined with a follow by this example query will match all blog entities with words that start with "lou" followed by "music". +اجمع بين عوامل تشغيل النص-الكامل لعمل فلترة أكثر تعقيدا. With a pretext search operator combined with a follow by this example query will match all blog entities with words that start with "lou" followed by "music". ```graphql { @@ -252,16 +252,16 @@ Combine fulltext operators to make more complex filters. With a pretext search o } ``` -## Schema +## المخطط -The schema of your data source--that is, the entity types, values, and relationships that are available to query--are defined through the [GraphQL Interface Definition Langauge (IDL)](https://facebook.github.io/graphql/draft/#sec-Type-System). +يتم تعريف مخطط مصدر البيانات الخاص بك - أي أنواع الكيانات والقيم والعلاقات المتاحة للاستعلام - من خلال [GraphQL Interface Definition Langauge (IDL)](https://facebook.github.io/graphql/draft/#sec-Type-System). -GraphQL schemas generally define root types for `queries`, `subscriptions` and `mutations`. The Graph only supports `queries`. The root `Query` type for your subgraph is automatically generated from the GraphQL schema that's included in your subgraph manifest. +مخططات GraphQL تعرف عموما أنواع الجذر لـ `queries`, و `subscriptions` و`mutations`. The Graph يدعم فقط `queries`. يتم إنشاء نوع الجذر `Query` لـ subgraph تلقائيا من مخطط GraphQL المضمن في subgraph manifest الخاص بك. -> **Note:** Our API does not expose mutations because developers are expected to issue transactions directly against the underlying blockchain from their applications. +> ** ملاحظة: ** الـ API الخاصة بنا لا تعرض الـ mutations لأنه يُتوقع من المطورين إصدار إجراءات مباشرة لـblockchain الأساسي من تطبيقاتهم. -### Entities +### الكيانات -All GraphQL types with `@entity` directives in your schema will be treated as entities and must have an `ID` field. +سيتم التعامل مع جميع أنواع GraphQL التي تحتوي على توجيهات `entity@ ` في مخططك على أنها كيانات ويجب أن تحتوي على حقل ` ID `. -> **Note:** Currently, all types in your schema must have an `@entity` directive. In the future, we will treat types without an `@entity` directive as value objects, but this is not yet supported. +> ** ملاحظة: ** في الوقت الحالي ، يجب أن تحتوي جميع الأنواع في مخططك على توجيه `entity@ `. في المستقبل ، سنتعامل مع الأنواع التي لا تحتوي على التوجيه `entity@ ` ككائنات، لكن هذا غير مدعوم حتى الآن. diff --git a/pages/ar/developer/publish-subgraph.mdx b/pages/ar/developer/publish-subgraph.mdx index 2f35f5eb1bae..3d51eccafeed 100644 --- a/pages/ar/developer/publish-subgraph.mdx +++ b/pages/ar/developer/publish-subgraph.mdx @@ -1,27 +1,27 @@ --- -title: Publish a Subgraph to the Decentralized Network +title: نشر Subgraph للشبكة اللامركزية --- -Once your subgraph has been [deployed to the Subgraph Studio](/studio/deploy-subgraph-studio), you have tested it out, and are ready to put it into production, you can then publish it to the decentralized network. +بمجرد أن الـ subgraph الخاص بك [قد تم نشره لـ Subgraph Studio](/studio/deploy-subgraph-studio) ، وقمت باختباره ، وأصبحت جاهزا لوضعه في الإنتاج ، يمكنك بعد ذلك نشره للشبكة اللامركزية. -Publishing a Subgraph to the decentralized network makes it available for [curators](/curating) to begin curating on it, and [indexers](/indexing) to begin indexing it. +يؤدي نشر Subgraph على الشبكة اللامركزية إلى الإتاحة [ للمنسقين ](/curating) لبدء التنسيق، و [ للمفهرسين](/indexing) لبدء الفهرسة. -For a walkthrough of how to publish a subgraph to the decentralized network, see [this video](https://youtu.be/HfDgC2oNnwo?t=580). +للحصول على إرشادات حول كيفية نشر subgraph على الشبكة اللامركزية ، راجع [ هذا الفيديو ](https://youtu.be/HfDgC2oNnwo؟t=580). -### Networks +### الشبكات -The decentralized network currently supports both Rinkeby and Ethereum Mainnet. +تدعم الشبكة اللامركزية حاليا كلا من Rinkeby و Ethereum Mainnet. -### Publishing a subgraph +### نشر subgraph -Subgraphs can be published to the decentralized network directly from the Subgraph Studio dashboard by clicking on the **Publish** button. Once a subgraph is published, it will be available to view in the [Graph Explorer](https://thegraph.com/explorer/). +يمكن نشر الـ Subgraphs على الشبكة اللامركزية مباشرة من Subgraph Studio dashboard بالنقر فوق الزر ** Publish **. بمجرد نشر الـ subgraph ، فإنه سيكون متاحا للعرض في [ Graph Explorer ](https://thegraph.com/explorer/). -- Subgraphs published to Rinkeby can index and query data from either the Rinkeby network or Ethereum Mainnet. +- يمكن لـ Subgraphs المنشور على Rinkeby فهرسة البيانات والاستعلام عنها من شبكة Rinkeby أو Ethereum Mainnet. -- Subgraphs published to Ethereum Mainnet can only index and query data from Ethereum Mainnet, meaning that you cannot publish subgraphs to the main decentralized network that index and query testnet data. +- يمكن لـ Subgraphs المنشور على Ethereum Mainnet فقط فهرسة البيانات والاستعلام عنها من Ethereum Mainnet ، مما يعني أنه لا يمكنك نشر الـ subgraphs على الشبكة اللامركزية الرئيسية التي تقوم بفهرسة بيانات testnet والاستعلام عنها. -- When publishing a new version for an existing subgraph the same rules apply as above. +- عند نشر نسخة جديدة لـ subgraph حالي ، تنطبق عليه نفس القواعد أعلاه. -### Updating metadata for a published subgraph +### تحديث بيانات الـ subgraph المنشور -Once your subgraph has been published to the decentralized network, you can modify the metadata at any time by making the update in the Subgraph Studio dashboard of the subgraph. After saving the changes and publishing your updates to the network, they will be reflected in the Graph Explorer. This won’t create a new version, as your deployment hasn’t changed. +بمجرد نشر الـ subgraph الخاص بك على الشبكة اللامركزية ، يمكنك تعديل البيانات الوصفية في أي وقت عن طريق إجراء التحديث في Subgraph Studio dashboard لـ subgraph. بعد حفظ التغييرات ونشر تحديثاتك على الشبكة ، ستنعكس في the Graph Explorer. لن يؤدي هذا إلى إنشاء إصدار جديد ، لأن النشر الخاص بك لم يتغير. diff --git a/pages/ar/developer/query-the-graph.mdx b/pages/ar/developer/query-the-graph.mdx index ae480b1e6883..776fbcb6bed1 100644 --- a/pages/ar/developer/query-the-graph.mdx +++ b/pages/ar/developer/query-the-graph.mdx @@ -1,14 +1,14 @@ --- -title: Query The Graph +title: الاستعلام عن The Graph --- -With the subgraph deployed, visit the [Graph Explorer](https://thegraph.com/explorer) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. +بالـ subgraph المنشور ، قم بزيارة [ Graph Explorer ](https://thegraph.com/explorer) لفتح واجهة [ GraphiQL ](https://github.com/graphql/graphiql) حيث يمكنك استكشاف GraphQL API المنشورة لـ subgraph عن طريق إصدار الاستعلامات وعرض المخطط. -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +تم توفير المثال أدناه ، ولكن يرجى الاطلاع على [Query API](/developer/graphql-api) للحصول على مرجع كامل حول كيفية الاستعلام عن كيانات الـ subgraph. -#### Example +#### مثال -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +يسرد هذا الاستعلام جميع العدادات التي أنشأها الـ mapping الخاص بنا. نظرا لأننا أنشأنا واحدا فقط ، فستحتوي النتيجة فقط على `default-counter`: ```graphql { @@ -19,14 +19,14 @@ This query lists all the counters our mapping has created. Since we only create } ``` -## Using The Graph Explorer +## استخدام The Graph Explorer -Each subgraph published to the decentralized Graph Explorer has a unique query URL that you can find by navigating to the subgraph details page and clicking on the "Query" button on the top right corner. This will open a side pane that will give you the unique query URL of the subgraph as well as some instructions about how to query it. +يحتوي كل subgraph منشور على Graph Explorer اللامركزي على عنوان URL فريد للاستعلام والذي يمكنك العثور عليه بالانتقال إلى صفحة تفاصيل الـ subgraph والنقر على "Query" في الزاوية اليمنى العليا. سيؤدي هذا إلى فتح نافذة جانبية والتي تمنحك عنوان URL فريد للاستعلام لـ subgraph بالإضافة إلى بعض الإرشادات حول كيفية الاستعلام عنه. -![Query Subgraph Pane](/img/query-subgraph-pane.png) +![نافذة الاستعلام عن Subgraph](/img/query-subgraph-pane.png) -As you can notice, this query URL must use a unique API key. You can create and manage your API keys in the [Subgraph Studio](https://thegraph.com/studio) in the "API Keys" section. Learn more about how to use Subgraph Studio [here](/studio/subgraph-studio). +كما يمكنك أن تلاحظ ، أنه يجب أن يستخدم عنوان الاستعلام URL مفتاح API فريد. يمكنك إنشاء وإدارة مفاتيح API الخاصة بك في [ Subgraph Studio ](https://thegraph.com/studio) في قسم "API Keys". تعرف على المزيد حول كيفية استخدام Subgraph Studio [ هنا ](/studio/subgraph-studio). -Querying subgraphs using your API keys will generate query fees that will be paid in GRT. You can learn more about billing [here](/studio/billing). +سيؤدي الاستعلام عن الـ subgraphs باستخدام مفاتيح API إلى إنشاء رسوم الاستعلام التي سيتم دفعها كـ GRT. يمكنك معرفة المزيد حول الفوترة [ هنا ](/studio/billing). -You can also use the GraphQL playground in the "Playground" tab to query a subgraph within The Graph Explorer. +يمكنك أيضا استخدام GraphQL playground في علامة التبويب "Playground" للاستعلام عن subgraph داخل The Graph Explorer. diff --git a/pages/ar/developer/querying-from-your-app.mdx b/pages/ar/developer/querying-from-your-app.mdx index c09c44efee72..f3decc0d1768 100644 --- a/pages/ar/developer/querying-from-your-app.mdx +++ b/pages/ar/developer/querying-from-your-app.mdx @@ -1,40 +1,40 @@ --- -title: Querying from an Application +title: الاستعلام من التطبيق --- -Once a subgraph is deployed to the Subgraph Studio or to the Graph Explorer, you will be given the endpoint for your GraphQL API that should look something like this: +بمجرد نشر ال Subgraph في Subgraph Studio أو في Graph Explorer ، سيتم إعطاؤك endpoint ل GraphQL API الخاصة بك والتي يجب أن تبدو كما يلي: -**Subgraph Studio (testing endpoint)** +**Subgraph Studio (اختبار endpoint)** ```sh -Queries (HTTP) +استعلامات (HTTP) https://api.studio.thegraph.com/query/// ``` **Graph Explorer** ```sh -Queries (HTTP) +استعلامات (HTTP) https://gateway.thegraph.com/api//subgraphs/id/ ``` -Using the GraphQL endpoint, you can use various GraphQL Client libraries to query the subgraph and populate your app with the data indexed by the subgraph. +باستخدام GraphQL endpoint ، يمكنك استخدام العديد من مكتبات GraphQL Client للاستعلام عن ال Subgraph وملء تطبيقك بالبيانات المفهرسة بواسطة ال Subgraph. Here are a couple of the more popular GraphQL clients in the ecosystem and how to use them: ### Apollo client -[Apollo client](https://www.apollographql.com/docs/) supports web projects including frameworks like React and Vue, as well as mobile clients like iOS, Android, and React Native. +[Apoolo client ](https://www.apollographql.com/docs/)يدعم مشاريع الويب بما في ال framework مثل React و Vue ، بالإضافة إلى mobile clients مثل iOS و Android و React Native. -Let's look at how fetch data from a subgraph with Apollo client in a web project. +لنلقِ نظرة على كيفية جلب البيانات من Subgraph وذلك باستخدام Apollo client في مشروع ويب. -First, install `@apollo/client` and `graphql`: +اولا قم بتثبيت `@apollo/client` and `graphql`: ```sh npm install @apollo/client graphql ``` -Then you can query the API with the following code: +بعد ذلك يمكنك الاستعلام عن API بالكود التالي: ```javascript import { ApolloClient, InMemoryCache, gql } from '@apollo/client' @@ -67,7 +67,7 @@ client }) ``` -To use variables, you can pass in a `variables` argument to the query: +لاستخدام المتغيرات، يمكنك التمرير في`variables`ل argument الاستعلام: ```javascript const tokensQuery = ` @@ -100,17 +100,17 @@ client ### URQL -Another option is [URQL](https://formidable.com/open-source/urql/), a somewhat lighter weight GraphQL client library. +هناك خيار آخر وهو [ URQL ](https://formidable.com/open-source/urql/) ، وهي مكتبة GraphQL client أخف وزنا إلى حد ما. -Let's look at how fetch data from a subgraph with URQL in a web project. +لنلقِ نظرة على كيفية جلب البيانات من Subgraph باستخدام URQL في مشروع ويب. -First, install `urql` and `graphql`: +اولا قم بتثبيت `urql` و `graphql`: ```sh npm install urql graphql ``` -Then you can query the API with the following code: +بعد ذلك يمكنك الاستعلام عن API بالكود التالي: ```javascript import { createClient } from 'urql' diff --git a/pages/ar/developer/quick-start.mdx b/pages/ar/developer/quick-start.mdx index 6893d424ddc2..5a245d65141a 100644 --- a/pages/ar/developer/quick-start.mdx +++ b/pages/ar/developer/quick-start.mdx @@ -1,17 +1,17 @@ --- -title: Quick Start +title: بداية سريعة --- -This guide will quickly take you through how to initialize, create, and deploy your subgraph on: +سيأخذك هذا الدليل سريعا ويعلمك كيفية تهيئة وإنشاء ونشر Subgraph الخاص بك على: - **Subgraph Studio** - used only for subgraphs that index **Ethereum mainnet** -- **Hosted Service** - used for subgraphs that index **other networks** outside of Ethereum mainnnet (e.g. Binance, Matic, etc) +- **Hosted Service** - يتم استخدامها ل Subgraphs التي تفهرس ** الشبكات الأخرى ** خارج Ethereum mainnet (مثل Binance و Matic والخ..) ## Subgraph Studio -### 1. Install the Graph CLI +### 1. قم بتثبيت Graph CLI -The Graph CLI is written in JavaScript and you will need to have either `npm` or `yarn` installed to use it. +تمت كتابة Graph CLI بلغة JavaScript وستحتاج إلى تثبيت إما `npm` أو `yarn` لاستخدامه. ```sh # NPM @@ -21,51 +21,51 @@ $ npm install -g @graphprotocol/graph-cli $ yarn global add @graphprotocol/graph-cli ``` -### 2. Initialize your Subgraph +### 2. قم بتهيئة Subgraph الخاص بك -- Initialize your subgraph from an existing contract. +- ابدأ ال Subgraph الخاص بك من عقد موجود. ```sh graph init --studio ``` -- Your subgraph slug is an identifier for your subgraph. The CLI tool will walk you through the steps for creating a subgraph, such as contract address, network, etc as you can see in the screenshot below. +- مؤشر ال Subgraph الخاص بك هو معرف ل Subgraph الخاص بك. ستوجهك أداة CLI لخطوات إنشاء Subgraph ، مثل عنوان العقد والشبكة الخ.. كما ترى في لقطة الشاشة أدناه. -![Subgraph command](/img/Subgraph-Slug.png) +![أمر Subgraph](/img/Subgraph-Slug.png) -### 3. Write your Subgraph +### 3. اكتب subgraph الخاص بك -The previous commands creates a scaffold subgraph that you can use as a starting point for building your subgraph. When making changes to the subgraph, you will mainly work with three files: +تقوم الأوامر السابقة بإنشاء ركيزة ال Subgraph والتي يمكنك استخدامها كنقطة بداية لبناء subgraph الخاص بك. عند إجراء تغييرات على ال subgraph ، ستعمل بشكل أساسي على ثلاثة ملفات: -- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraphs will index. -- Schema (schema.graphql) - The GraphQL schema defines what data you wish to retreive from the subgraph. -- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema. +- : (Manifest(subgraph.yaml يحدد ال manifest مصادر البيانات التي سيقوم Subgraphs الخاص بك بفهرستها. +- مخطط (schema.graphql) - يحدد مخطط GraphQL البيانات التي ترغب في استردادها من Subgraph. +- (AssemblyScript Mappings (mapping.ts هذا هو الكود الذي يترجم البيانات من مصادر البيانات الخاصة بك إلى الكيانات المحددة في المخطط. -For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). +لمزيد من المعلومات حول كيفية كتابة Subgraph ، راجع [ إنشاء Subgraph ](/developer/create-subgraph-hosted). ### 4. Deploy to the Subgraph Studio -- Go to the Subgraph Studio [https://thegraph.com/studio/](https://thegraph.com/studio/) and connect your wallet. +- انتقل إلى Subgraph Studio [ https://thegraph.com/studio/ ](https://thegraph.com/studio/) وقم بتوصيل محفظتك. - Click "Create" and enter the subgraph slug you used in step 2. -- Run these commands in the subgraph folder +- قم بتشغيل هذه الأوامر في مجلد Subgraph ```sh $ graph codegen $ graph build ``` -- Authenticate and deploy your subgraph. The deploy key can be found on the Subgraph page in Subgraph Studio. +- وثق وأنشر ال Subgraph الخاص بك. يمكن العثور على مفتاح النشر في صفحة Subgraph في Subgraph Studio. ```sh $ graph auth --studio $ graph deploy --studio ``` -- You will be asked for a version label. It's strongly recommended to use the following conventions for naming your versions. Example: `0.0.1`, `v1`, `version1` +- سيتم طلب منك تسمية الإصدار. يوصى بشدة باستخدام المصطلحات التالية لتسمية الإصدارات الخاصة بك. مثال: `0.0.1` ، `v1` ، `version1` -### 5. Check your logs +### 5. تحقق من السجلات الخاصة بك -The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: +السجلات ستخبرك في حالة وجود أخطاء. في حالة فشل Subgraph ، يمكنك الاستعلام عن صحة Subgraph وذلك باستخدام [ GraphiQL Playground ](https://graphiql-online.com/). استخدم [ لهذا ال endpoint ](https://api.thegraph.com/index-node/graphql). لاحظ أنه يمكنك الاستفادة من الاستعلام أدناه وإدخال ID النشر ل Subgraph الخاص بك. في هذه الحالة ، `Qm...` هو ID النشر (والذي يمكن أن يوجد في صفحة ال Subgraph ضمن ** التفاصيل **). سيخبرك الاستعلام أدناه عند فشل Subgraph حتى تتمكن من تصحيح الأخطاء وفقًا لذلك: ```sh { @@ -109,15 +109,15 @@ The logs should tell you if there are any errors. If your subgraph is failing, y } ``` -### 6. Query your Subgraph +### 6. الاستعلام عن ال Subgraph الخاص بك -You can now query your subgraph by following [these instructions](/developer/query-the-graph). You can query from your dapp if you don't have your API key via the free, rate limited temporary query URL that can be used for development and staging. You can read the additional instructions for how to query a subgraph from a frontend application [here](/developer/querying-from-your-app). +يمكنك الآن الاستعلام عن Subgraph باتباع [ هذه الإرشادات ](/developer/query-the-graph). يمكنك الاستعلام من ال dapp الخاص بك إذا لم يكن لديك API Key الخاص بك وذلك عبر عنوان URL الخاص بالاستعلام المؤقت المجاني والمحدود والذي يمكن استخدامه للتطوير والتشغيل. يمكنك قراءة الإرشادات الإضافية حول كيفية الاستعلام عن رسم بياني فرعي من [ هنا ](/developer/querying-from-your-app). -## Hosted Service +## الخدمة المستضافة -### 1. Install the Graph CLI +### 1. قم بتثبيت Graph CLI -"The Graph CLI is an npm package and you will need `npm` or `yarn` installed to use it. +"Graph CLI عبارة عن حزمة npm وستحتاج إلى تثبيت `npm` أو `yarn` لاستخدامها. ```sh # NPM @@ -127,15 +127,15 @@ $ npm install -g @graphprotocol/graph-cli $ yarn global add @graphprotocol/graph-cli ``` -### 2. Initialize your Subgraph +### 2. قم بتهيئة Subgraph الخاص بك -- Initialize your subgraph from an existing contract. +- ابدأ ال Subgraph الخاص بك من عقد موجود. ```sh $ graph init --product hosted-service --from-contract
``` -- You will be asked for a subgraph name. The format is `/`. Ex: `graphprotocol/examplesubgraph` +- سيُطلب منك اسم Subgraph. التنسيق هو `/`. مثال: `graphprotocol/examplesubgraph` - If you'd like to initialize from an example, run the command below: @@ -143,23 +143,23 @@ $ graph init --product hosted-service --from-contract
$ graph init --product hosted-service --from-example ``` -- In the case of the example, the subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. +- في حالة المثال ، يعتمد Subgraph على عقد Gravity بواسطة Dani Grant الذي يدير ال avatars للمستخدم ويصدر أحداث `NewGravatar` أو `UpdateGravatar` كلما تم إنشاء ال avatars أو تحديثها. -### 3. Write your Subgraph +### 3. اكتب subgraph الخاص بك -The previous command will have created a scaffold from where you can build your subgraph. When making changes to the subgraph, you will mainly work with three files: +سيكون الأمر السابق قد أنشأ ركيزة حيث يمكنك Subgraph الخاص بك. عند إجراء تغييرات على ال subgraph ، ستعمل بشكل أساسي على ثلاثة ملفات: -- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraph will index -- Schema (schema.graphql) - The GraphQL schema define what data you wish to retrieve from the subgraph -- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema +- : (Manifest(subgraph.yaml يحدد ال manifest مصادر البيانات التي سيفهرسها ال Subgraph +- مخطط (schema.graphql) - يحدد مخطط GraphQL البيانات التي ترغب في جلبها من Subgraph +- (AssemblyScript Mappings (mapping.ts هذا هو الكود الذي يترجم البيانات من مصادر البيانات الخاصة بك إلى الكيانات المحددة في المخطط -For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). +لمزيد من المعلومات حول كيفية كتابة Subgraph ، راجع [ إنشاء Subgraph ](/developer/create-subgraph-hosted). -### 4. Deploy your Subgraph +### 4. انشر ال subgraph الخاص بك -- Sign into the [Hosted Service](https://thegraph.com/hosted-service/) using your github account -- Click Add Subgraph and fill out the required information. Use the same subgraph name as in step 2. -- Run codegen in the subgraph folder +- سجّل الدخول إلى [ الخدمة المستضافة ](https://thegraph.com/hosted-service/) باستخدام حسابك على github +- انقر فوق إضافة Subgraph واملأ المعلومات المطلوبة. استخدم نفس اسم ال Subgraph كما في الخطوة 2. +- قم بتشغيل codegen في مجلد ال Subgraph ```sh # NPM @@ -169,16 +169,16 @@ $ npm run codegen $ yarn codegen ``` -- Add your Access token and deploy your subgraph. The access token is found on your dashboard in the Hosted Service. +- أضف توكن الوصول الخاص بك وانشر ال Subgraph الخاص بك. يتم العثور على توكن الوصول في لوحة التحكم في ال Hosted service. ```sh $ graph auth --product hosted-service $ graph deploy --product hosted-service / ``` -### 5. Check your logs +### 5. تحقق من السجلات الخاصة بك -The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: +السجلات ستخبرك في حالة وجود أخطاء. في حالة فشل Subgraph ، يمكنك الاستعلام عن صحة Subgraph وذلك باستخدام [ GraphiQL Playground ](https://graphiql-online.com/). استخدم [ لهذا ال endpoint ](https://api.thegraph.com/index-node/graphql). لاحظ أنه يمكنك الاستفادة من الاستعلام أدناه وإدخال ID النشر ل Subgraph الخاص بك. في هذه الحالة ، `Qm...` هو ID النشر (والذي يمكن أن يوجد في صفحة ال Subgraph ضمن ** التفاصيل **). سيخبرك الاستعلام أدناه عند فشل Subgraph حتى تتمكن من تصحيح الأخطاء وفقًا لذلك: ```sh { @@ -222,6 +222,6 @@ The logs should tell you if there are any errors. If your subgraph is failing, y } ``` -### 6. Query your Subgraph +### 6. الاستعلام عن ال Subgraph الخاص بك -Follow [these instructions](/hosted-service/query-hosted-service) to query your subgraph on the Hosted Service. +اتبع [ هذه الإرشادات ](/hosted-service/query-hosted-service) للاستعلام عن ال Subgraph الخاص بك على ال Hosted service. diff --git a/pages/ar/explorer.mdx b/pages/ar/explorer.mdx index c12ecf1ce809..ae31b016d8a4 100644 --- a/pages/ar/explorer.mdx +++ b/pages/ar/explorer.mdx @@ -11,7 +11,7 @@ title: مستكشف title="مشغل فيديو يوتيوب" frameBorder="0" allowFullScreen - > +> ## Subgraphs diff --git a/pages/ar/hosted-service/migrating-subgraph.mdx b/pages/ar/hosted-service/migrating-subgraph.mdx index 2fc480afa395..9f314e8e9034 100644 --- a/pages/ar/hosted-service/migrating-subgraph.mdx +++ b/pages/ar/hosted-service/migrating-subgraph.mdx @@ -2,7 +2,7 @@ title: Migrating an Existing Subgraph to The Graph Network --- -## Introduction +## مقدمة This is a guide for the migration of subgraphs from the Hosted Service (also known as 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. @@ -142,7 +142,7 @@ If you're still confused, fear not! Check out the following resources or watch o title="مشغل فيديو يوتيوب" frameBorder="0" allowFullScreen - > +> - [The Graph Network Contracts](https://github.com/graphprotocol/contracts) diff --git a/pages/ar/hosted-service/query-hosted-service.mdx b/pages/ar/hosted-service/query-hosted-service.mdx index 731e3a3120b2..fd7de3b535a2 100644 --- a/pages/ar/hosted-service/query-hosted-service.mdx +++ b/pages/ar/hosted-service/query-hosted-service.mdx @@ -4,11 +4,11 @@ title: Query the Hosted Service With the subgraph deployed, visit the [Hosted Service](https://thegraph.com/hosted-service/) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +تم توفير المثال أدناه ، ولكن يرجى الاطلاع على [Query API](/developer/graphql-api) للحصول على مرجع كامل حول كيفية الاستعلام عن كيانات الـ subgraph. -#### Example +#### مثال -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +يسرد هذا الاستعلام جميع العدادات التي أنشأها الـ mapping الخاص بنا. نظرا لأننا أنشأنا واحدا فقط ، فستحتوي النتيجة فقط على `default-counter`: ```graphql { diff --git a/pages/ar/hosted-service/what-is-hosted-service.mdx b/pages/ar/hosted-service/what-is-hosted-service.mdx index 7f604c8dc31a..491b79119f4f 100644 --- a/pages/ar/hosted-service/what-is-hosted-service.mdx +++ b/pages/ar/hosted-service/what-is-hosted-service.mdx @@ -6,7 +6,7 @@ This section will walk you through deploying a subgraph to the Hosted Service, o If you don't have an account on the Hosted Service, you can signup with your Github account. Once you authenticate, you can start creating subgraphs through the UI and deploying them from your terminal. Graph Node supports a number of Ethereum testnets (Rinkeby, Ropsten, Kovan) in addition to mainnet. -## Create a Subgraph +## إنشاء الـ Subgraph First follow the instructions [here](/developer/define-subgraph-hosted) to install the Graph CLI. Create a subgraph by passing in `graph init --product hosted service` @@ -34,13 +34,13 @@ The `` in this case is your github user or organization name, `/ [] ``` -The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. Continue on to the [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) to better understand which events from your smart contracts to pay attention to, mappings, and more. +يعتمد مثال الـ subgraph على عقد Gravity بواسطة Dani Grant الذي يدير avatars للمستخدم ويصدر أحداث ` NewGravatar ` أو ` UpdateGravatar ` كلما تم إنشاء avatars أو تحديثها. يعالج الـ subgraph هذه الأحداث عن طريق كتابة كيانات ` Gravatar ` إلى مخزن Graph Node والتأكد من تحديثها وفقا للأحداث. Continue on to the [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) to better understand which events from your smart contracts to pay attention to, mappings, and more. ## Supported Networks on the Hosted Service diff --git a/pages/ar/indexing.mdx b/pages/ar/indexing.mdx index 3c05105e8ce0..c28f9bed30b5 100644 --- a/pages/ar/indexing.mdx +++ b/pages/ar/indexing.mdx @@ -60,7 +60,7 @@ query indexerAllocations { } ``` -Use Etherscan to call `getRewards()`: +استخدم Etherscan لاستدعاء `()getRewards`: - انتقل إلى [ واجهة Etherscan لعقد المكافآت Rewards contract ](https://etherscan.io/address/0x9Ac758AB77733b4150A901ebd659cbF8cB93ED66#readProxyContract) @@ -79,7 +79,7 @@ Use Etherscan to call `getRewards()`: - إذا تمت تسوية الاعتراض بالتعادل، فسيتم إرجاع وديعة ال Fishermen ، ولن يتم شطب المفهرس المعترض عليه. - إذا تم قبول الاعتراض، فسيتم إرجاع GRT التي أودعها الFishermen ، وسيتم شطب المفهرس المعترض عليه وسيكسب Fishermen ال 50٪ من GRT المشطوبة. -Disputes can be viewed in the UI in an Indexer's profile page under the `Disputes` tab. +يمكن عرض الاعتراضات في واجهة المستخدم في بروفايل المفهرس ضمن علامة التبويب ` Disputes`. ### ما هي خصومات رسوم الاستعلام ومتى يتم توزيعها؟ @@ -112,7 +112,7 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute - **صغيرة**ـ يكفي لبدء فهرسة العديد من ال subgraphs، من المحتمل أن تحتاج إلى توسيع. - ** قياسية ** - هو الإعداد الافتراضي ، ويتم استخدامه في مثال بيانات نشر k8s / terraform. - **متوسطة** - مؤشر انتاج ​​يدعم 100 subgraphs و 200-500 طلب في الثانية. -- **كبيرة** - مُعدة لفهرسة جميع ال subgraphs المستخدمة حاليا وأيضا لخدمة طلبات حركة المرور البيانات ذات الصلة. +- **كبيرة** - مُعدة لفهرسة جميع ال subgraphs المستخدمة حاليا وأيضا لخدمة طلبات حركة مرور البيانات ذات الصلة. | Setup | (CPUs) | (memory in GB) | (disk in TBs) | (CPUs) | (memory in GB) | | ----- | :----: | :------------: | :-----------: | :----: | :------------: | diff --git a/pages/ar/studio/billing.mdx b/pages/ar/studio/billing.mdx index 4e2e3d0c945e..67a5a8c1420e 100644 --- a/pages/ar/studio/billing.mdx +++ b/pages/ar/studio/billing.mdx @@ -2,7 +2,7 @@ title: Billing on the Subgraph Studio --- -### Overview +### نظره عامة Invoices are statements of payment amounts owed by a customer and are typically generated on a weekly basis in the system. You’ll be required to pay fees based on the query fees you generate using your API keys. The billing contract lives on the [Polygon](https://polygon.technology/) network. It’ll allow you to: @@ -46,7 +46,7 @@ For a quick demo of how billing works on the Subgraph Studio, check out the vide title="مشغل فيديو يوتيوب" frameBorder="0" allowFullScreen - > +> ### Multisig Users diff --git a/pages/ar/studio/deploy-subgraph-studio.mdx b/pages/ar/studio/deploy-subgraph-studio.mdx index 2155d8fe8976..b9d406812541 100644 --- a/pages/ar/studio/deploy-subgraph-studio.mdx +++ b/pages/ar/studio/deploy-subgraph-studio.mdx @@ -13,13 +13,13 @@ Deploying a Subgraph to the Subgraph Studio is quite simple. This will take you We are using the same CLI to deploy subgraphs to our [hosted service](https://thegraph.com/hosted-service/) and to the [Subgraph Studio](https://thegraph.com/studio/). Here are the commands to install graph-cli. This can be done using npm or yarn. -**Install with yarn:** +**التثبيت بواسطة yarn:** ```bash yarn global add @graphprotocol/graph-cli ``` -**Install with npm:** +**التثبيت بواسطة npm:** ```bash npm install -g @graphprotocol/graph-cli @@ -29,7 +29,7 @@ npm install -g @graphprotocol/graph-cli Before deploying your actual subgraph you need to create a subgraph in [Subgraph Studio](https://thegraph.com/studio/). We recommend you read our [Studio documentation](/studio/subgraph-studio) to learn more about this. -## Initialize your Subgraph +## قم بتهيئة Subgraph الخاص بك Once your subgraph has been created in Subgraph Studio you can initialize the subgraph code using this command: diff --git a/pages/ar/studio/multisig.mdx b/pages/ar/studio/multisig.mdx index 164835bdb8a4..555ba11f9da9 100644 --- a/pages/ar/studio/multisig.mdx +++ b/pages/ar/studio/multisig.mdx @@ -4,7 +4,7 @@ title: Using a Multisig Wallet Subgraph Studio currently doesn't support signing with multisig wallets. Until then, you can follow this guide on how to publish your subgraph by invoking the [GNS contract](https://github.com/graphprotocol/contracts/blob/dev/contracts/discovery/GNS.sol) functions. -### Create a Subgraph +### إنشاء الـ Subgraph Similary to using a regular wallet, you can create a subgraph by connecting your non-multisig wallet in Subgraph Studio. Once you connect the wallet, simply create a new subgraph. Make sure you fill out all the details, such as subgraph name, description, image, website, and source code url if applicable. diff --git a/pages/ar/studio/studio-faq.mdx b/pages/ar/studio/studio-faq.mdx index 4db4d7ccddaa..20b2ffb13a5e 100644 --- a/pages/ar/studio/studio-faq.mdx +++ b/pages/ar/studio/studio-faq.mdx @@ -1,14 +1,14 @@ --- -title: Subgraph Studio FAQs +title: الأسئلة الشائعة حول Subgraph Studio --- -### 1. How do I create an API Key? +### 1. كيف يمكنني إنشاء مفتاح API؟ -In the Subgraph Studio, you can create API Keys as needed and add security settings to each of them. +في Subgraph Studio ، يمكنك إنشاء API Keys وذلك حسب الحاجة وإضافة إعدادات الأمان لكل منها. -### 2. Can I create multiple API Keys? +### 2. هل يمكنني إنشاء أكثر من API Keys؟ -A: Yes! You can create multiple API Keys to use in different projects. Check out the link [here](https://thegraph.com/studio/apikeys/). +A: نعم يمكنك إنشاء أكثر من API Keys وذلك لاستخدامها في مشاريع مختلفة. تحقق من الرابط [هنا](https://thegraph.com/studio/apikeys/). ### 3. How do I restrict a domain for an API Key? diff --git a/pages/ar/studio/subgraph-studio.mdx b/pages/ar/studio/subgraph-studio.mdx index 0dfc28807462..d4e82eeef02e 100644 --- a/pages/ar/studio/subgraph-studio.mdx +++ b/pages/ar/studio/subgraph-studio.mdx @@ -36,7 +36,7 @@ The best part! When you first create a subgraph, you’ll be directed to fill ou - Your Subgraph Name - Image -- Description +- الوصف - Categories - Website @@ -47,7 +47,7 @@ The Graph Network is not yet able to support all of the data-sources & features - Index mainnet Ethereum - Must not use any of the following features: - ipfs.cat & ipfs.map - - Non-fatal errors + - أخطاء غير فادحة - Grafting More features & networks will be added to The Graph Network incrementally. @@ -73,7 +73,7 @@ You’ve made it this far - congrats! Publishing your subgraph means that an IPF title="مشغل فيديو يوتيوب" frameBorder="0" allowFullScreen - > +> Remember, while you’re going through your publishing flow, you’ll be able to push to either mainnet or Rinkeby, the testnet we support. If you’re a first time subgraph developer, we highly suggest you start with publishing to Rinkeby, which is free to do. This will allow you to see how the subgraph will work in The Graph Explorer and will allow you to test curation elements. diff --git a/pages/es/about/introduction.mdx b/pages/es/about/introduction.mdx index baa0e542240a..70290d8c3649 100644 --- a/pages/es/about/introduction.mdx +++ b/pages/es/about/introduction.mdx @@ -4,31 +4,31 @@ title: Introducción En esta página se explica qué es The Graph y cómo puedes empezar a utilizarlo. -## Qué es The Graph +## ¿Qué es The Graph? -The Graph es un protocolo descentralizado para indexar y consultar los datos de las blockchains, empezando por Ethereum. Permite consultar datos que son difíciles de consultar directamente. +The Graph es un protocolo descentralizado que permite indexar y consultar los datos de diferentes blockchains, el cual empezó por Ethereum. Permite consultar datos los cuales pueden ser difíciles de consultar directamente. Los proyectos con contratos inteligentes complejos como [Uniswap](https://uniswap.org/) y las iniciativas de NFTs como [Bored Ape Yacht Club](https://boredapeyachtclub.com/) almacenan los datos en la blockchain de Ethereum, lo que hace realmente difícil leer algo más que los datos básicos directamente desde la blockchain. -En el caso de Bored Ape Yacht Club, podemos realizar operaciones de lectura básicas en [the contract](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) como obtener el propietario de un determinado Ape, obtener el URI de contenido de un Ape con base en su ID, o el supply total, ya que estas operaciones de lectura están programadas directamente en el contrato inteligente, pero no son posibles las consultas y operaciones más avanzadas del mundo real como la agregación, la búsqueda, las relaciones y el filtrado no trivial. Por ejemplo, si quisiéramos consultar los apes que son propiedad de una determinada dirección, y filtrar por una de sus características, no podríamos obtener esa información interactuando directamente con el propio contrato. +En el caso de Bored Ape Yacht Club, podemos realizar operaciones de lecturas básicas en [su contrato](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code), para obtener el propietario de un determinado Ape, obtener el URI de un Ape en base a su ID, o el supply total, ya que estas operaciones de lectura están programadas directamente en el contrato inteligente, pero no son posibles las consultas y operaciones más avanzadas del mundo real como la adición, consultas, las relaciones y el filtrado no trivial. Por ejemplo, si quisiéramos consultar los Apes que son propiedad de una dirección en concreto, y filtrar por una de sus características, no podríamos obtener esa información interactuando directamente con el contrato. -Para obtener estos datos, tendríamos que procesar cada uno de los eventos de [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) emitidos, leer los metadatos de IPFS utilizando el ID del Token y el hash de IPFS, y luego agregarlos. Incluso para este tipo de preguntas relativamente sencillas, una aplicación descentralizada (dapp) que se ejecutara en un navegador tardaría **horas o incluso días** en obtener una respuesta. +Para obtener estos datos, tendríamos que procesar cada uno de los eventos de [`transferencia`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) que se hayan emitido, leer los metadatos de IPFS utilizando el ID del token y el hash del IPFS, con el fin de luego agregarlos. Incluso para este tipo de preguntas relativamente sencillas, una aplicación descentralizada (dapp) que se ejecutara en un navegador tardaría **horas o incluso días** en obtener una respuesta. -También podrías construir tu propio servidor, procesar las transacciones allí, guardarlas en una base de datos y construir un endpoint de la API sobre todo ello para consultar los datos. Sin embargo, esta opción requiere recursos intensivos, necesita mantenimiento, presenta un único punto de fallo y rompe importantes propiedades de seguridad necesarias para la descentralización. +También podrías construir tu propio servidor, procesar las transacciones allí, guardarlas en una base de datos y construir un endpoint de la API sobre todo ello para consultar los datos. Sin embargo, esta opción requiere recursos intensivos, necesita mantenimiento, y si llegase a presentar algún tipo de fallo podría incluso vulnerar algunos protocolos de seguridad que son necesarios para la descentralización. **Indexar los datos de la blockchain es muy, muy difícil.** -Las propiedades de la blockchain, como la finalidad, las reorganizaciones de la cadena o los bloques sin cerrar, complican aún más este proceso y hacen que no sólo se consuma tiempo, sino que sea conceptualmente difícil recuperar los resultados correctos de las consultas de los datos de la blockchain. +Las propiedades de la blockchain, su finalidad, la reorganización de la cadena o los bloques que están por cerrarse, complican aún más este proceso y hacen que no solo se consuma tiempo, sino que sea conceptualmente difícil recuperar los resultados correctos proporcionados por la blockchain. -The Graph resuelve esto con un protocolo descentralizado que indexa y permite la consulta eficiente y de alto rendimiento de los datos de la blockchain. Estas APIs ("subgrafos" indexados) pueden consultarse después con una API GraphQL estándar. Actualmente, existe un servicio alojado (hosted) y un protocolo descentralizado con las mismas capacidades. Ambos están respaldados por la implementación de código abierto de [Graph Node](https://github.com/graphprotocol/graph-node). +The Graph resuelve esto con un protocolo descentralizado que indexa y permite una consulta eficiente y de alto rendimiento para recibir los datos de la blockchain. Estas APIs ("subgrafos" indexados) pueden consultarse después con una API de GraphQL estándar. Actualmente, existe un servicio alojado (hosted) y un protocolo descentralizado con las mismas capacidades. Ambos están respaldados por la implementación de código abierto de [Graph Node](https://github.com/graphprotocol/graph-node). -## Cómo Funciona The Graph +## ¿Cómo funciona The Graph? -The Graph aprende qué y cómo indexar los datos de Ethereum basándose en las descripciones de los subgrafos, conocidas como el manifiesto de los subgrafos. La descripción del subgrafo define los contratos inteligentes de interés para un subgrafo, los eventos en esos contratos a los que prestar atención, y cómo mapear los datos de los eventos a los datos que The Graph almacenará en su base de datos. +The Graph aprende, qué y cómo indexar los datos de Ethereum, basándose en las descripciones de los subgrafos, conocidas como el manifiesto de los subgrafos. La descripción del subgrafo define los contratos inteligentes de interés para este subgrafo, los eventos en esos contratos a los que prestar atención, y cómo mapear los datos de los eventos a los datos que The Graph almacenará en su base de datos. -Una vez que has escrito el `subgraph manifest`, utilizas la CLI de The Graph para almacenar la definición en IPFS y decirle al indexador que empiece a indexar los datos de ese subgrafo. +Una vez que has escrito el `subgraph manifest`, utilizas el CLI de The Graph para almacenar la definición en IPFS y decirle al indexador que empiece a indexar los datos de ese subgrafo. -Este diagrama ofrece más detalles sobre el flujo de datos una vez que se ha desplegado un manifiesto de subgrafo, que trata de las transacciones de Ethereum: +Este diagrama ofrece más detalles sobre el flujo de datos una vez que se ha desplegado en el manifiesto para un subgrafo, que trata de las transacciones en Ethereum: ![](/img/graph-dataflow.png) @@ -36,12 +36,12 @@ El flujo sigue estos pasos: 1. Una aplicación descentralizada añade datos a Ethereum a través de una transacción en un contrato inteligente. 2. El contrato inteligente emite uno o más eventos mientras procesa la transacción. -3. Graph Node escanea continuamente Ethereum en busca de nuevos bloques y los datos de su subgrafo que puedan contener. -4. Graph Node encuentra los eventos de Ethereum para tu subgrafo en estos bloques y ejecuta los mapping handlers que proporcionaste. El mapeo (mapping) es un módulo WASM que crea o actualiza las entidades de datos que Graph Node almacena en respuesta a los eventos de Ethereum. -5. La aplicación descentralizada consulta a Graph Node los datos indexados de la blockchain, utilizando el [GraphQL endpoint](https://graphql.org/learn/) del nodo. El Nodo The Graph, a su vez, traduce las consultas GraphQL en consultas para su almacén de datos subyacente con el fin de obtener estos datos, haciendo uso de las capacidades de indexación del almacén. La aplicación descentralizada muestra estos datos en una rica interfaz de usuario para los usuarios finales, que utilizan para emitir nuevas transacciones en Ethereum. El ciclo se repite. +3. Graph Node escanea continuamente la red de Ethereum en busca de nuevos bloques y los datos de su subgrafo que puedan contener. +4. Graph Node encuentra los eventos de la red Ethereum, a fin de proveerlos en tu subgrafo mediante estos bloques y ejecuta los mapping handlers que proporcionaste. El mapeo (mapping) es un módulo WASM que crea o actualiza las entidades de datos que Graph Node almacena en respuesta a los eventos de Ethereum. +5. La aplicación descentralizada consulta a través de Graph Node los datos indexados de la blockchain, utilizando el [GraphQL endpoint](https://graphql.org/learn/) del nodo. El Nodo de The Graph, a su vez, traduce las consultas GraphQL en consultas para su almacenamiento de datos subyacentes con el fin de obtener estos datos, haciendo uso de las capacidades de indexación que ofrece el almacenamiento. La aplicación descentralizada muestra estos datos en una interfaz muy completa para el usuario, a fin de que los cliente que usan este subgrafo puedan emitir nuevas transacciones en Ethereum. Y así... el ciclo se repite continuamente. -## Próximos Pasos +## Próximos puntos -En las siguientes secciones entraremos en más detalles sobre cómo definir subgrafos, cómo desplegarlos y cómo consultar los datos de los índices que construye Graph Node. +En las siguientes secciones entraremos en más detalles sobre cómo definir subgrafos, cómo desplegarlos y cómo consultar los datos de los índices que construye el Graph Node. -Antes de que empieces a escribir tu propio subgrafo, puede que quieras echar un vistazo a The Graph Explorer y explorar algunos de los subgrafos que ya han sido desplegados. La página de cada subgrafo contiene un playground que te permite consultar los datos de ese subgrafo con GraphQL. +Antes de que empieces a escribir tu propio subgrafo, es posible que debas echar un vistazo a The Graph Explorer para explorar algunos de los subgrafos que ya han sido desplegados. La página de cada subgrafo contiene un playground que te permite consultar los datos de ese subgrafo usando GraphQL. diff --git a/pages/es/about/network.mdx b/pages/es/about/network.mdx index 316fd3e082f9..a81e6ef93cbb 100644 --- a/pages/es/about/network.mdx +++ b/pages/es/about/network.mdx @@ -1,15 +1,15 @@ --- -title: Visión General de la Red +title: Visión general de la red --- -The Graph Network es un protocolo de indexación descentralizado para organizar los datos de la blockchain. Las aplicaciones utilizan GraphQL para consultar APIs abiertas llamadas subgrafos, para recuperar los datos que están indexados en la red. Con The Graph, los desarrolladores pueden construir aplicaciones sin servidor que se ejecutan completamente en la infraestructura pública. +The Graph Network es un protocolo de indexación descentralizado, el cual permite organizar los datos de la blockchain. Las aplicaciones utilizan GraphQL para consultar APIs públicas, llamadas subgrafos, que sirven para recuperar los datos que están indexados en la red. Con The Graph, los desarrolladores pueden construir sus aplicaciones completamente en una infraestructura pública. -> Dirección del token GRT [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) +> GRT Token Address: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) ## Descripción -The Graph Network está formada por Indexadores, Curadores y Delegadores que proporcionan servicios a la red y sirven datos a las aplicaciones Web3. Los consumidores utilizan las aplicaciones y consumen los datos. +The Graph Network está formada por Indexadores, Curadores y Delegadores que proporcionan servicios a la red y proveen datos a las aplicaciones Web3. Los clientes utilizan estas aplicaciones y consumen los datos. -![Economía de los Tokens](/img/Network-roles@2x.png) +![Economía de los tokens](/img/Network-roles@2x.png) -Para garantizar la seguridad económica de The Graph Network y la integridad de los datos que se consultan, los participantes ponen en staking y utilizan Graph Tokens (GRT). GRT es un token de trabajo que es un ERC-20 en la blockchain de Ethereum, utilizado para asignar recursos en la red. Los Indexadores, Curadores y Delegadores activos pueden prestar servicios y obtener ingresos de la red, proporcionales a la cantidad de trabajo que realizan y a su participación en GRT. +Para garantizar la seguridad económica de The Graph Network y la integridad de los datos que se consultan, los participantes colocan en staking sus Graph Tokens (GRT). GRT es un token alojado en el protocolo ERC-20 de la blockchain Ethereum, utilizado para asignar recursos en la red. Los Indexadores, Curadores y Delegadores pueden prestar sus servicios y obtener ingresos por medio de la red, en proporción a su desempeño y la cantidad de GRT que hayan colocado en staking. diff --git a/pages/es/curating.mdx b/pages/es/curating.mdx index 0b50efa83cc4..425cb5608b6f 100644 --- a/pages/es/curating.mdx +++ b/pages/es/curating.mdx @@ -64,7 +64,7 @@ Los Indexadores pueden encontrar subgrafos para indexar en función de las seña 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\] (https://thegraph.com/docs/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. You can then signal on the new subgraph version, thus incurring a 1% curation tax. + - 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%. ## Preguntas frecuentes sobre Curación @@ -91,7 +91,7 @@ Se sugiere que no actualices tus subgrafos con demasiada frecuencia. Consulta la 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. -Still confused? Still confused? Check out our Curation video guide below: +¿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/pages/es/delegating.mdx b/pages/es/delegating.mdx index e92e8cb8a7d0..30e6905758a4 100644 --- a/pages/es/delegating.mdx +++ b/pages/es/delegating.mdx @@ -2,11 +2,11 @@ title: delegación --- -Delegators cannot be slashed for bad behavior, but there is a deposit tax on Delegators to disincentivize poor decision making that could harm the integrity of the network. +Los delegadores no pueden ser penalizados por mal comportamiento, pero existe una tarifa inicial de depósitos que desalienta a los delegadores a tomar malas decisiones que puedan comprometer la integridad de la red. ## Guía del delegador -This guide will explain how to be an effective delegator in the Graph Network. Delegators share earnings of the protocol alongside all indexers on their delegated stake. A Delegator must use their best judgement to choose Indexers based on multiple factors. Please note this guide will not go over steps such as setting up Metamask properly, as that information is widely available on the internet. There are three sections in this guide: +Esta guía explicará cómo ser un delegador efectivo en Graph Network. Los delegadores comparten las ganancias del protocolo junto con todos los indexadores en base a participación delegada. Un delegador deberá usar su propio discernimiento para elegir los mejores indexadores, en base a una serie de factores. Tenga en cuenta que esta guía no expondrá los pasos necesarios para la configuración adecuada de Metamask, ya que esa información está expuesta en internet. Hay tres secciones en está guía: - Los riesgos de delegar tokens en la red de The Graph - Cómo calcular los rendimientos que te esperan siendo delegador @@ -67,9 +67,9 @@ Otra cosa que un delegador debe considerar es la participación que tendrá dent ![Fórmula compartida](/img/Share-Forumla.png) -Por ende, un delegador puede hacer su propio analista a fin de determinar que el Indexador que ofrece el 20% a sus delegadores, realmente está ofreciendo un mejor rendimiento. +Usando esta fórmula, podemos ver que en realidad es posible que un indexador que ofrece solo el 20% a los delegadores, en realidad les dé a sus delegadores una recompensa aún mejor que un indexador que les da el 90%. -A delegator can therefore do the math to determine that the Indexer offering 20% to delegators, is offering a better return. +Por lo tanto, un delegador puede hacer sus propios cálculos a fin de determinar que, el Indexador que ofrece un 20% a los delegadores ofrece un mejor rendimiento. ### Considerar la capacidad de delegación @@ -90,5 +90,5 @@ Utilizando está formula, podemos discernir qué un Indexer el cual está ofreci title="Reproductor de video de YouTube" frameBorder="0" allowFullScreen - > +> diff --git a/pages/es/developer/assemblyscript-api.mdx b/pages/es/developer/assemblyscript-api.mdx index 2b6aa855c4a3..98e4e1fbdb06 100644 --- a/pages/es/developer/assemblyscript-api.mdx +++ b/pages/es/developer/assemblyscript-api.mdx @@ -2,60 +2,60 @@ title: AssemblyScript API --- -> Note: if you created a subgraph prior to `graph-cli`/`graph-ts` version `0.22.0`, you're using an older version of AssemblyScript, we recommend taking a look at the [`Migration Guide`](/developer/assemblyscript-migration-guide) +> 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`](/developer/assemblyscript-migration-guide) tu código -This page documents what built-in APIs can be used when writing subgraph mappings. Two kinds of APIs are available out of the box: +Está página explica que APIs usar para recibir ciertos datos de los subgrafos. Dos tipos de estas APIs se describen a continuación: -- the [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) and -- code generated from subgraph files by `graph codegen`. +- 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`. -It is also possible to add other libraries as dependencies, as long as they are compatible with [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Since this is the language mappings are written in, the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) is a good source for language and standard library features. +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. -## Installation +## Instalación -Subgraphs created with [`graph init`](/developer/create-subgraph-hosted) come with preconfigured dependencies. All that is required to install these dependencies is to run one of the following commands: +Los subgrafos creados con [`graph init`](/developer/create-subgraph-hosted) vienen configurados previamente. Todo lo necesario para instalar estás configuraciones lo podrás encontrar en uno de los siguientes comandos: ```sh yarn install # Yarn npm install # NPM ``` -If the subgraph was created from scratch, one of the following two commands will install the Graph TypeScript library as a dependency: +Si el subgrafo fue creado con scratch, uno de los siguientes dos comandos podrá instalar la librería TypeScript como una dependencia: ```sh yarn add --dev @graphprotocol/graph-ts # Yarn npm install --save-dev @graphprotocol/graph-ts # NPM ``` -## API Reference +## Referencias de API -The `@graphprotocol/graph-ts` library provides the following APIs: +La librería de `@graphprotocol/graph-ts` proporciona las siguientes APIs: -- An `ethereum` API for working with Ethereum smart contracts, events, blocks, transactions, and Ethereum values. -- A `store` API to load and save entities from and to the Graph Node store. -- A `log` API to log messages to the Graph Node output and the Graph Explorer. -- An `ipfs` API to load files from IPFS. -- A `json` API to parse JSON data. -- A `crypto` API to use cryptographic functions. -- Low-level primitives to translate between different type systems such as Ethereum, JSON, GraphQL and AssemblyScript. +- 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. +- 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. -### Versions +### Versiones -The `apiVersion` in the subgraph manifest specifies the mapping API version which is run by Graph Node for a given subgraph. The current mapping API version is 0.0.6. +La `apiVersion` en el manifiesto del subgrafo especifica la versión de la API correspondiente al mapeo que está siendo ejecutado en el Graph Node de un subgrafo en específico. La versión actual para la APÍ de mapeo es la 0.0.6. -| Version | Release notes | +| Version | Notas del lanzamiento | | :-: | --- | -| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | -| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | -| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | -| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | -| 0.0.2 | Added `input` field to the Ethereum Transaction object | +| 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`](/developer/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 | ### Built-in Types -Documentation on the base types built into AssemblyScript can be found in the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types). +La documentación sobre las actualizaciones integradas en AssemblyScript puedes encontrarla en la [wiki de AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki/Types). -The following additional types are provided by `@graphprotocol/graph-ts`. +Las siguientes integraciones son proporcionada por `@graphprotocol/graph-ts`. #### ByteArray @@ -63,24 +63,24 @@ The following additional types are provided by `@graphprotocol/graph-ts`. import { ByteArray } from '@graphprotocol/graph-ts' ``` -`ByteArray` represents an array of `u8`. +`ByteArray` representa una matriz de `u8`. -_Construction_ +_Construcción_ -- `fromI32(x: i32): ByteArray` - Decomposes `x` into bytes. -- `fromHexString(hex: string): ByteArray` - Input length must be even. Prefixing with `0x` is optional. +- `fromI32(x: i32): ByteArray` - Descompuesta en `x` bytes. +- `fromHexString(hex: string): ByteArray` - La longitud de la entrada debe ser uniforme. Prefijo `0x` es opcional. -_Type conversions_ +_Tipo de conversiones_ -- `toHexString(): string` - Converts to a hex string prefixed with `0x`. -- `toString(): string` - Interprets the bytes as a UTF-8 string. -- `toBase58(): string` - Encodes the bytes into a base58 string. -- `toU32(): u32` - Interprets the bytes as a little-endian `u32`. Throws in case of overflow. -- `toI32(): i32` - Interprets the byte array as a little-endian `i32`. Throws in case of overflow. +- `toHexString(): string` - Convierte un prefijo hexadecimal iniciado con `0x`. +- `toString(): string` - Interpreta los bytes en 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. -_Operators_ +_Operadores_ -- `equals(y: ByteArray): bool` – can be written as `x == y`. +- `equals(y: ByteArray): bool` – se puede escribir como `x == y`. #### BigDecimal @@ -88,30 +88,30 @@ _Operators_ import { BigDecimal } from '@graphprotocol/graph-ts' ``` -`BigDecimal` is used to represent arbitrary precision decimals. +`BigDecimal` se usa para representar una precisión decimal arbitraria. -_Construction_ +_Construcción_ -- `constructor(bigInt: BigInt)` – creates a `BigDecimal` from an `BigInt`. -- `static fromString(s: string): BigDecimal` – parses from a decimal string. +- `constructor(bigInt: BigInt)` – creará un `BigDecimal` en base a un`BigInt`. +- `static fromString(s: string): BigDecimal` – analizará una cadena de decimales. -_Type conversions_ +_Tipo de conversiones_ -- `toString(): string` – prints to a decimal string. +- `toString(): string` – colocará una cadena de decimales. -_Math_ +_Matemática_ -- `plus(y: BigDecimal): BigDecimal` – can be written as `x + y`. -- `minus(y: BigDecimal): BigDecimal` – can be written as `x - y`. -- `times(y: BigDecimal): BigDecimal` – can be written as `x * y`. -- `div(y: BigDecimal): BigDecimal` – can be written as `x / y`. -- `equals(y: BigDecimal): bool` – can be written as `x == y`. -- `notEqual(y: BigDecimal): bool` – can be written as `x != y`. -- `lt(y: BigDecimal): bool` – can be written as `x < y`. -- `le(y: BigDecimal): bool` – can be written as `x <= y`. -- `gt(y: BigDecimal): bool` – can be written as `x > y`. -- `ge(y: BigDecimal): bool` – can be written as `x >= y`. -- `neg(): BigDecimal` - can be written as `-x`. +- `plus(y: BigDecimal): BigDecimal` – puede escribirse como `x + y`. +- `minus(y: BigDecimal): BigDecimal` – puede escribirse como `x - y`. +- `times(y: BigDecimal): BigDecimal` – puede escribirse como `x * y`. +- `div(y: BigDecimal): BigDecimal` – puede escribirse como `x / y`. +- `equals(y: BigDecimal): bool` – puede escribirse como `x == y`. +- `notEqual(y: BigDecimal): bool` – puede escribirse como `x != y`. +- `lt(y: BigDecimal): bool` – puede escribirse como `x < y`. +- `lt(y: BigDecimal): bool` – puede escribirse como `x < y`. +- `gt(y: BigDecimal): bool` – puede escribirse como `x > y`. +- `ge(y: BigDecimal): bool` – puede escribirse como `x >= y`. +- `neg(): BigDecimal` - puede escribirse como `-x`. #### BigInt @@ -119,47 +119,47 @@ _Math_ import { BigInt } from '@graphprotocol/graph-ts' ``` -`BigInt` is used to represent big integers. This includes Ethereum values of type `uint32` to `uint256` and `int64` to `int256`. Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. - -The `BigInt` class has the following API: - -_Construction_ - -- `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32`. -- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string. -- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interprets `bytes` as an unsigned, little-endian integer. If your input is big-endian, call `.reverse()` first. -- `BigInt.fromSignedBytes(x: Bytes): BigInt` – Interprets `bytes` as a signed, little-endian integer. If your input is big-endian, call `.reverse()` first. - - _Type conversions_ - -- `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.toBigDecimal(): BigDecimal` - converts into a decimal with no fractional part. - -_Math_ - -- `x.plus(y: BigInt): BigInt` – can be written as `x + y`. -- `x.minus(y: BigInt): BigInt` – can be written as `x - y`. -- `x.times(y: BigInt): BigInt` – can be written as `x * y`. -- `x.div(y: BigInt): BigInt` – can be written as `x / y`. -- `x.mod(y: BigInt): BigInt` – can be written as `x % y`. -- `x.equals(y: BigInt): bool` – can be written as `x == y`. -- `x.notEqual(y: BigInt): bool` – can be written as `x != y`. -- `x.lt(y: BigInt): bool` – can be written as `x < y`. -- `x.le(y: BigInt): bool` – can be written as `x <= y`. -- `x.gt(y: BigInt): bool` – can be written as `x > y`. -- `x.ge(y: BigInt): bool` – can be written as `x >= y`. -- `x.neg(): BigInt` – can be written as `-x`. -- `x.divDecimal(y: BigDecimal): BigDecimal` – divides by a decimal, giving a decimal result. -- `x.isZero(): bool` – Convenience for checking if the number is zero. -- `x.isI32(): bool` – Check if the number fits in an `i32`. -- `x.abs(): BigInt` – Absolute value. -- `x.pow(exp: u8): BigInt` – Exponentiation. -- `bitOr(x: BigInt, y: BigInt): BigInt` – can be written as `x | y`. -- `bitAnd(x: BigInt, y: BigInt): BigInt` – can be written as `x & y`. -- `leftShift(x: BigInt, bits: u8): BigInt` – can be written as `x << y`. -- `rightShift(x: BigInt, bits: u8): BigInt` – can be written as `x >> y`. +`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`. + +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()`. + + _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.toBigDecimal(): BigDecimal` - se convierte en un decimal sin parte fraccionaria. + +_Matemática_ + +- `x.plus(y: BigInt): BigInt` – puede ser escrito como `x + y`. +- `x.minus(y: BigInt): BigInt` – puede ser escrito como `x - y`. +- `x.times(y: BigInt): BigInt` – puede ser escrito como `x * y`. +- `x.div(y: BigInt): BigInt` – puede ser escrito como `x / y`. +- `x.mod(y: BigInt): BigInt` – puede ser escrito como `x % y`. +- `x.equals(y: BigInt): bool` – puede ser escrito como `x == y`. +- `x.notEqual(y: BigInt): bool` – puede ser escrito como `x != y`. +- `x.lt(y: BigInt): bool` – puede ser escrito como `x < y`. +- `x.le(y: BigInt): bool` – puede ser escrito como `x <= y`. +- `x.gt(y: BigInt): bool` – puede ser escrito como `x > y`. +- `x.ge(y: BigInt): bool` – puede ser escrito como `x >= y`. +- `x.neg(): BigInt` – puede ser escrito como `-x`. +- `x.divDecimal(y: BigDecimal): BigDecimal` – divide por un decimal, dando un resultado decimal. +- `x.isZero(): bool` – Conveniencia para comprobar si el número es cero. +- `x.isI32(): bool` – Comprueba si el número encaja en un `i32`. +- `x.abs(): BigInt` –Valor absoluto. +- `x.pow(exp: u8): BigInt` – Exponenciación. +- `bitOr(x: BigInt, y: BigInt): BigInt` puede ser escrito como `x | y`. +- `bitAnd(x: BigInt, y: BigInt): BigInt` – puede ser escrito como `x & y`. +- `leftShift(x: BigInt, bits: u8): BigInt` – puede ser escrito como `x << y`. +- `rightShift(x: BigInt, bits: u8): BigInt` – puede ser escrito como `x >> y`. #### TypedMap @@ -167,15 +167,15 @@ _Math_ import { TypedMap } from '@graphprotocol/graph-ts' ``` -`TypedMap` can be used to stored key-value pairs. See [this example](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). +`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). -The `TypedMap` class has the following API: +La `TypedMap` clase tiene la siguiente 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` -- `map.getEntry(key: K): TypedMapEntry | null` – returns the key-value pair for a `key` or `null` if the `key` does not exist in the map -- `map.get(key: K): V | null` – returns the value for a `key` or `null` if the `key` does not exist in the map -- `map.isSet(key: K): bool` – returns `true` if the `key` exists in the map and `false` if it does not +- `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.isSet(key: K): bool` – returna `true` si el `key` existe en el mapa y `false` no es asi #### Bytes @@ -183,13 +183,13 @@ The `TypedMap` class has the following API: import { Bytes } from '@graphprotocol/graph-ts' ``` -`Bytes` is used to represent arbitrary-length arrays of bytes. This includes Ethereum values of type `bytes`, `bytes32` etc. +`Bytes` se utiliza para representar matrices de bytes de longitud arbitraria. Esto incluye los valores de Ethereum de tipo `bytes`, `bytes32` etc. -The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) and this supports all the `Uint8Array` functionality, plus the following new methods: +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: -- `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 un string hexadecimal que representa los bytes de la matriz +- `b.toString()` – convierte los bytes de la matriz en un string de caracteres unicode +- `b.toBase58()` –convierte un valor de Ethereum Bytes en codificación base58 (utilizada para los hashes IPFS) #### Address @@ -197,11 +197,11 @@ The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/Assem 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: +Agrega el siguiente método sobre la API `Bytes`: -- `Address.fromString(s: string): Address` – creates an `Address` from a hexadecimal string +- `Address.fromString(s: string): Address` – crea un `Address` desde un string hexadecimal ### Store API @@ -209,13 +209,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 almacén se asignan uno a uno con los tipos `@entity` definidos en el esquema GraphQL del subgrafo. Para hacer que el trabajo con estas entidades sea conveniente, el comando `graph codegen` provisto por el [Graph CLI](https://github.com/graphprotocol/graph-cli) genera clases de entidades, que son subclases del tipo construido `Entity`, con captadores y seteadores de propiedades para los campos del esquema, así como métodos para cargar y guardar estas entidades. -#### Creating entities +#### 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 @@ -241,13 +241,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 un evento `Transfer` es encontrado mientras se procesa la cadena, es pasado al evento handler `handleTransfer` usando 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 parent 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 ID ú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. -#### Loading entities from the store +#### Carga de entidades desde el almacén -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 almacén con lo siguiente: ```typescript let id = event.transaction.hash.toHex() // or however the ID is constructed @@ -259,18 +259,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 `load` metodo returna al valor del tipo `Transfer | null`. Por lo tanto, puede ser necesario comprobar el caso `null` antes de utilizar el valor. -> **Note:** Loading entities is only necessary if the changes made in the mapping depend on the previous data of an entity. See the next section for the two ways of updating existing entities. +> **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. -#### Updating existing entities +#### Actualización de las entidades existentes -There are two ways to update an existing entity: +Hay dos maneras de actualizar una entidad existente: -1. Load the entity with e.g. `Transfer.load(id)`, set properties on the entity, then `.save()` it back to the store. -2. Simply create the entity with e.g. `new Transfer(id)`, set properties on the entity, then `.save()` it to the store. If the entity already exists, the changes are merged into it. +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. -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 seteadores de propiedades generados: ```typescript let transfer = new Transfer(id) @@ -279,16 +279,16 @@ 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 serian `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. El siguiente asume `entity` tiene un `numbers: [BigInt!]!` campo. ```typescript // This won't work @@ -302,9 +302,9 @@ entity.numbers = numbers entity.save() ``` -#### Removing entities from the store +#### Eliminar entidades del almacen -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 remover una entidad a través de los tipos generados. En cambio, para remover una entidad es necesario pasar el nombre del tipo de entidad y el ID de la misma a `store.remove`: ```typescript import { store } from '@graphprotocol/graph-ts' @@ -313,17 +313,17 @@ let id = event.transaction.hash.toHex() store.remove('Transfer', id) ``` -### Ethereum API +### 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. -#### Support for Ethereum Types +#### 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, los ABIs del contrato 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 [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 { @@ -333,7 +333,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 `Transfer(address,address,uint256)` evento firmado en Ethereum, los valores `from`, `to` y `amount` del tipo `address`, `address` y `uint256` se convierten en `Address` y `BigInt`, permitiendo que se transmitan al `Bytes!` y `BigInt!` las propiedades de la `Transfer` entidad: ```typescript let id = event.transaction.hash.toHex() @@ -344,9 +344,9 @@ transfer.amount = event.params.amount transfer.save() ``` -#### Events and Block/Transaction Data +#### 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 manejadores 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 parent y al bloque del que forman parte. Los siguientes datos pueden ser obtenidos desde las instancias de `event` (estas clases forman parte del módulo `ethereum` en `graph-ts`): ```typescript class Event { @@ -390,11 +390,11 @@ class Transaction { } ``` -#### Access to Smart Contract State +#### 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. Se pueden utilizar para acceder a variables de estado públicas y llamar a 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 // Import the generated contract class @@ -411,13 +411,13 @@ 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. +Mientras el `ERC20Contract` en 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. -#### Handling Reverted Calls +#### 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) @@ -429,11 +429,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. -#### Encoding/Decoding ABI +#### 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 codificarse y descodificarse de acuerdo con el formato de codificación ABI de Ethereum utilizando las funciones `encode` y `decode` en el modulo `ethereum`. ```typescript import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts' @@ -450,39 +450,39 @@ 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). -### Logging API +### API de Registro ```typescript 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 Graph Node así como en Graph Explorer. Los mensajes pueden ser registrados utilizando diferentes niveles de registro. Se proporciona una sintaxis de string de formato básico para componer los 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.info(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 error de mensaje. +- `log.critical(fmt: string, args: Array): void` – registra un mensaje critico _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 un formato string y una matriz de valores de string. A continuación, sustituye los marcadores de posición por los valores de string de la matriz. El primer `{}` marcador de posición se sustituye por el primer valor de la matriz, el segundo marcador de posición `{}` se sustituye por el segundo valor y así sucesivamente. ```typescript log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue.toString(), 'already a string']) ``` -#### Logging one or more values +#### Registro de uno o varios valores -##### Logging a single value +##### Registro de un valor -In the example below, the string value "A" is passed into an array to become`['A']` before being logged: +En el siguiente ejemplo, el valor del string "A" se pasa a una matriz para convertirse en`['A']` antes de ser registrado: ```typescript let myValue = 'A' @@ -493,9 +493,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -##### Logging a single entry from an existing array +##### 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'] @@ -506,9 +506,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -#### Logging multiple entries from an existing array +#### 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 de la matriz 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 de `myArray` se registran. ```typescript let myArray = ['A', 'B', 'C'] @@ -519,9 +519,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -##### Logging a specific entry from an existing array +##### 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 la matriz, se debe proporcionar el valor indexado. ```typescript export function handleSomeEvent(event: SomeEvent): void { @@ -530,9 +530,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -##### Logging event information +##### 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 de bloque y el hash de transacción de un evento: ```typescript import { log } from '@graphprotocol/graph-ts' @@ -546,15 +546,15 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -### IPFS API +### API IPFS ```typescript 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 que las asignaciones obtengan los hashes de IPFS del contrato y lean los archivos correspondientes de IPFS. Los datos del archivo se devolverán en forma de `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 // Put this inside an event handler in the mapping @@ -567,9 +567,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](/developer/create-subgraph-hosted#ipfs-pinning) section for more information. +**Nota:** `ipfs.cat` no es deterministico en este momento. Si no se puede recuperar el archivo a través de la red IPFS antes de que se agote el tiempo de la solicitud, devolverá `null`. Debido a esto, siempre vale la pena comprobar el resultado para `null`. Para asegurar que los archivos puedan ser recuperados, tienen que estar anclados al nodo IPFS al que se conecta Graph Node. En el [servicio de host](https://thegraph.com/hosted-service), esto es [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs). Mira la seccion [IPFS pinning](/developer/create-subgraph-hosted#ipfs-pinning) para mayor informacion. -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 streaming con `ipfs.map`. La función espera el hash o la ruta de un archivo IPFS, el nombre de una llamada de retorno y banderas para modificar su comportamiento: ```typescript import { JSONValue, Value } from '@graphprotocol/graph-ts' @@ -599,34 +599,34 @@ 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 que se admite actualmente es `json`, que debe ser pasada por `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 llamada de retorno para cada una de ellas. El callback puede entonces utilizar operaciones de entidad para almacenar los datos del `JSONValue`. Los cambios de entidad se almacenan sólo cuando el manejador que llamó `ipfs.map` termina con éxito; mientras tanto, se mantienen en la memoria, y el tamaño del archivo que `ipfs.map` puede procesar es, por lo 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. +Si es exitoso, `ipfs.map` retorna `void`. Si alguna invocación de la devolución de llamada causa un error, el manejador que invocó `ipfs.map` es abortado, y el subgrafo es marcado como fallido. -### Crypto API +### API Cripto ```typescript 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 de los usuarios funciones criptográficas para su uso en mapeos. En este momento, sólo hay una: - `crypto.keccak256(input: ByteArray): ByteArray` -### JSON API +### API JSON ```typescript import { json, JSONValueKind } from '@graphprotocol/graph-ts' ``` -JSON data can be parsed using the `json` API: +Los datos JSON pueden ser analizados usando la API `json`: -- `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: Bytes): JSONValue` – parses JSON data from a valid UTF-8 `String` -- `json.try_fromString(data: Bytes): Result` – safe version of `json.fromString`, it returns an error variant if the parsing failed +- `json.fromBytes(data: Bytes): JSONValue` – analiza datos JSON desde una matriz `Bytes` +- `json.try_fromBytes(data: Bytes): Result` – version segura de `json.fromBytes`, devuelve una variante de error si el análisis falla +- `json.fromString(data: Bytes): JSONValue` – analiza datos de JSON desde un valido UTF-8 `String` +- `json.try_fromString(data: Bytes): Result` – version segura de `json.fromString`, devuelve una variante de error si el analisis falla -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 `JSONValue` clase 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(...) @@ -635,22 +635,22 @@ if (value.kind == JSONValueKind.BOOL) { } ``` -In addition, there is a method to check if the value is `null`: +Además, hay 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 convierte `JSONValue` con uno de los 5 metodos anteriores) -### Type Conversions Reference +### Referencias de Tipo de Conversiones -| Source(s) | Destination | Conversion function | +| Origen(es) | Destino | Funcion de Conversion | | -------------------- | -------------------- | ---------------------------- | | Address | Bytes | none | | Address | ID | s.toHexString() | @@ -688,17 +688,17 @@ When the type of a value is certain, it can be converted to a [built-in type](#b | String (hexadecimal) | Bytes | ByteArray.fromHexString(s) | | String (UTF-8) | Bytes | ByteArray.fromUTF8(s) | -### Data Source Metadata +### 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 manejador a través del namespaces `dataSource`: - `dataSource.address(): Address` - `dataSource.network(): string` - `dataSource.context(): DataSourceContext` -### Entity and DataSourceContext +### 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 dinámicamente: - `setString(key: string, value: string): void` - `setI32(key: string, value: i32): void` diff --git a/pages/es/developer/assemblyscript-migration-guide.mdx b/pages/es/developer/assemblyscript-migration-guide.mdx index c63a1af95d7b..acdc2366df9b 100644 --- a/pages/es/developer/assemblyscript-migration-guide.mdx +++ b/pages/es/developer/assemblyscript-migration-guide.mdx @@ -1,50 +1,50 @@ --- -title: AssemblyScript Migration Guide +title: Guia de Migracion de AssemblyScript --- -Up until now, subgraphs have been using one of the [first versions of AssemblyScript](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). Finally we've added support for the [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 [newest one available](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉! 🎉 -That will enable subgraph developers to use newer features of the AS language and standard library. +Esto permitirá a los desarrolladores de subgrafos utilizar las nuevas características del lenguaje AS y la libreria estándar. -This guide is applicable for anyone using `graph-cli`/`graph-ts` below version `0.22.0`. If you're already at a higher than (or equal) version to that, you've already been using version `0.19.10` of AssemblyScript 🙂 +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 🙂 -> Note: As of `0.24.0`, `graph-node` can support both versions, depending on the `apiVersion` specified in the subgraph manifest. +> Nota: A partir de `0.24.0`, `graph-node` puede soportar ambas versiones, dependiendo del `apiVersion` especificado en el manifiesto del subgrafo. -## Features +## Caracteristicas -### New functionality +### Nueva Funcionalidad -- `TypedArray`s can now be built from `ArrayBuffer`s by using the [new `wrap` static method](https://www.assemblyscript.org/stdlib/typedarray.html#static-members) ([v0.8.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.8.1)) -- New standard library functions: `String#toUpperCase`, `String#toLowerCase`, `String#localeCompare`and `TypedArray#set` ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Added support for x instanceof GenericClass ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) -- Added `StaticArray`, a more efficient array variant ([v0.9.3](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.3)) -- Added `Array#flat` ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -- Implemented `radix` argument on `Number#toString` ([v0.10.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.1)) -- Added support for separators in floating point literals ([v0.13.7](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.13.7)) -- Added support for first class functions ([v0.14.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.0)) -- Add builtins: `i32/i64/f32/f64.add/sub/mul` ([v0.14.13](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.13)) -- Implement `Array/TypedArray/String#at` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) -- Added support for template literal strings ([v0.18.17](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.17)) -- Add `encodeURI(Component)` and `decodeURI(Component)` ([v0.18.27](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.27)) -- Add `toString`, `toDateString` and `toTimeString` to `Date` ([v0.18.29](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.29)) -- Add `toUTCString` for `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) -- Add `nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) +- `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)) +- 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 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)) -### Optimizations +### Optimizaciones -- `Math` functions such as `exp`, `exp2`, `log`, `log2` and `pow` have been replaced by faster variants ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Slightly optimize `Math.mod` ([v0.17.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.1)) -- Cache more field accesses in std Map and Set ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) -- Optimize for powers of two in `ipow32/64` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) +- `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)) +- 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)) -### Other +### Otros -- The type of an array literal can now be inferred from its contents ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) -- Updated stdlib to Unicode 13.0.0 ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- 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)) +- Actualizado stdlib a Unicode 13.0.0 ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -## How to upgrade? +## Como actualizar? -1. Change your mappings `apiVersion` in `subgraph.yaml` to `0.0.6`: +1. Cambiar tus asignaciones `apiVersion` en `subgraph.yaml` a `0.0.6`: ```yaml ... @@ -56,7 +56,7 @@ dataSources: ... ``` -2. Update the `graph-cli` you're using to the `latest` version by running: +2. Actualiza la `graph-cli` que usas a la `latest` version ejecutando: ```bash # if you have it globally installed @@ -66,20 +66,20 @@ npm install --global @graphprotocol/graph-cli@latest npm install --save-dev @graphprotocol/graph-cli@latest ``` -3. Do the same for `graph-ts`, but instead of installing globally, save it in your main dependencies: +3. Haz lo mismo con `graph-ts`, pero en lugar de instalarlo globalmente, guárdalo en tus dependencias principales: ```bash npm install --save @graphprotocol/graph-ts@latest ``` -4. Follow the rest of the guide to fix the language breaking changes. -5. Run `codegen` and `deploy` again. +4. Sigue el resto de la guía para arreglar los cambios que rompen el idioma. +5. Ejecuta `codegen` y `deploy` nuevamente. -## Breaking changes +## Rompiendo los esquemas -### Nullability +### Anulabilidad -On the older version of AssemblyScript, you could create code like this: +En la versión anterior de AssemblyScript, podías crear un código como el siguiente: ```typescript function load(): Value | null { ... } @@ -88,7 +88,7 @@ let maybeValue = load(); maybeValue.aMethod(); ``` -However on the newer version, because the value is nullable, it requires you to check, like this: +Sin embargo, en la versión más reciente, debido a que el valor es anulable, es necesario que lo compruebes, así: ```typescript let maybeValue = load() @@ -98,7 +98,7 @@ if (maybeValue) { } ``` -Or force it like this: +O forzarlo asi: ```typescript let maybeValue = load()! // breaks in runtime if value is null @@ -106,11 +106,11 @@ let maybeValue = load()! // breaks in runtime if value is null maybeValue.aMethod() ``` -If you are unsure which to choose, we recommend always using the safe version. If the value doesn't exist you might want to just do an early if statement with a return in you subgraph handler. +Si no estás seguro de cuál elegir, te recomendamos que utilices siempre la versión segura. Si el valor no existe, es posible que quieras hacer una declaración if temprana con un retorno en tu handler de subgrafo. ### Variable Shadowing -Before you could do [variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) and code like this would work: +Antes podías hacer [variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) y un código como este funcionaría: ```typescript let a = 10 @@ -118,7 +118,7 @@ let b = 20 let a = a + b ``` -However now this isn't possible anymore, and the compiler returns this error: +Sin embargo, ahora esto ya no es posible, y el compilador devuelve este error: ```typescript ERROR TS2451: Cannot redeclare block-scoped variable 'a' @@ -127,12 +127,9 @@ ERROR TS2451: Cannot redeclare block-scoped variable 'a' ~~~~~~~~~~~~~ in assembly/index.ts(4,3) ``` - -You'll need to rename your duplicate variables if you had variable shadowing. - -### Null Comparisons - -By doing the upgrade on your subgraph, sometimes you might get errors like these: +Tendrás que cambiar el nombre de las variables duplicadas si tienes una variable shadowing. +### Comparaciones Nulas +Al hacer la actualización en ut 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'. @@ -140,8 +137,7 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i ~~~~ in src/mappings/file.ts(41,21) ``` - -To solve you can simply change the `if` statement to something like this: +Para solucionarlo puedes simplemente cambiar la declaracion `if` por algo así: ```typescript if (!decimals) { @@ -151,23 +147,23 @@ To solve you can simply change the `if` statement to something like this: if (decimals === null) { ``` -The same applies if you're doing != instead of ==. +Lo mismo ocurre si haces != en lugar de ==. ### Casting -The common way to do casting before was to just use the `as` keyword, like this: +La forma común de hacer el casting antes era simplemente usar la palabra clave `as`, así: ```typescript let byteArray = new ByteArray(10) let uint8Array = byteArray as Uint8Array // equivalent to: byteArray ``` -However this only works in two scenarios: +Sin embargo, esto sólo funciona en dos casos: -- Primitive casting (between types such as `u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); -- Upcasting on class inheritance (subclass → superclass) +- 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) -Examples: +Ejemplos: ```typescript // primitive casting @@ -183,10 +179,10 @@ class Bytes extends Uint8Array {} let bytes = new Bytes(2) < Uint8Array > bytes // same as: bytes as Uint8Array ``` -There are two scenarios where you may want to cast, but using `as`/`var` **isn't safe**: +Hay dos escenarios en los que puede querer cast, pero usando `as`/`var` **no es seguro**: -- Downcasting on class inheritance (superclass → subclass) -- Between two types that share a superclass +- Downcasting en la herencia de clases (superclase → subclase) +- Entre dos tipos que comparten una superclase ```typescript // downcasting on class inheritance @@ -203,7 +199,7 @@ class ByteArray extends Uint8Array {} let bytes = new Bytes(2) < ByteArray > bytes // breaks in runtime :( ``` -For those cases, you can use the `changetype` function: +Para esos casos, puedes usar la funcion`changetype`: ```typescript // downcasting on class inheritance @@ -222,7 +218,7 @@ let bytes = new Bytes(2) changetype(bytes) // works :) ``` -If you just want to remove nullability, you can keep using the `as` operator (or `variable`), but make sure you know that value can't be null, otherwise it will break. +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á. ```typescript // remove nullability @@ -235,18 +231,18 @@ if (previousBalance != null) { let newBalance = new AccountBalance(balanceId) ``` -For the nullability case we recommend taking a look at the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks), it will make your code cleaner 🙂 +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 🙂 -Also we've added a few more static methods in some types to ease casting, they are: +También hemos añadido algunos métodos estáticos más en algunos tipos para facilitar el casting, son: - Bytes.fromByteArray - Bytes.fromUint8Array - BigInt.fromByteArray - ByteArray.fromBigInt -### Nullability check with property access +### Comprobación de anulabilidad con acceso a la propiedad -To use the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks) you can use either `if` statements or the ternary operator (`?` and `:`) like this: +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: ```typescript let something: string | null = 'data' @@ -264,7 +260,7 @@ if (something) { } ``` -However that only works when you're doing the `if` / ternary on a variable, not on a property access, like this: +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: ```typescript class Container { @@ -277,7 +273,7 @@ container.data = 'data' let somethingOrElse: string = container.data ? container.data : 'else' // doesn't compile ``` -Which outputs this error: +Lo que produce este error: ```typescript ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/string/String'. @@ -285,8 +281,7 @@ ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/s let somethingOrElse: string = container.data ? container.data : "else"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` - -To fix this issue, you can create a variable for that property access so that the compiler can do the nullability check magic: +Para solucionar este problema, puedes crear una variable para ese acceso a la propiedad de manera que el compilador pueda hacer la magia de la comprobación de nulidad: ```typescript class Container { @@ -301,9 +296,9 @@ let data = container.data let somethingOrElse: string = data ? data : 'else' // compiles just fine :) ``` -### Operator overloading with property access +### Sobrecarga de operadores con acceso a propiedades -If you try to sum (for example) a nullable type (from a property access) with a non nullable one, the AssemblyScript compiler instead of giving a compile time error warning that one of the values is nullable, it just compiles silently, giving chance for the code to break at runtime. +Si intentas sumar (por ejemplo) un tipo anulable (desde un acceso a una propiedad) con otro no anulable, el compilador de AssemblyScript en lugar de dar un error en el tiempo de compilación advirtiendo que uno de los valores es anulable, simplemente compila en silencio, dando oportunidad a que el código se rompa en tiempo de ejecución. ```typescript class BigInt extends Uint8Array { @@ -327,7 +322,7 @@ let wrapper = new Wrapper(y) wrapper.n = wrapper.n + x // doesn't give compile time errors as it should ``` -We've opened a issue on the AssemblyScript compiler for this, but for now if you do these kind of operations in your subgraph mappings, you should change them to do a null check before it. +Hemos abierto un tema en el compilador de AssemblyScript para esto, pero por ahora si haces este tipo de operaciones en tus mapeos de subgrafos, deberías cambiarlos para hacer una comprobación de nulos antes de ello. ```typescript let wrapper = new Wrapper(y) @@ -339,9 +334,9 @@ if (!wrapper.n) { wrapper.n = wrapper.n + x // now `n` is guaranteed to be a BigInt ``` -### Value initialization +### Inicialización del valor -If you have any code like this: +Si tienes algún código como este: ```typescript var value: Type // null @@ -349,7 +344,7 @@ value.x = 10 value.y = 'content' ``` -It will compile but break at runtime, that happens because the value hasn't been initialized, so make sure your subgraph has initialized their values, like this: +Compilará pero se romperá en tiempo de ejecución, eso ocurre porque el valor no ha sido inicializado, así que asegúrate de que tu subgrafo ha inicializado sus valores, así: ```typescript var value = new Type() // initialized @@ -357,7 +352,7 @@ value.x = 10 value.y = 'content' ``` -Also if you have nullable properties in a GraphQL entity, like this: +También si tienes propiedades anulables en una entidad GraphQL, como esta: ```graphql type Total @entity { @@ -366,7 +361,7 @@ type Total @entity { } ``` -And you have code similar to this: +Y tienes un código similar a este: ```typescript let total = Total.load('latest') @@ -378,7 +373,7 @@ if (total === null) { total.amount = total.amount + BigInt.fromI32(1) ``` -You'll need to make sure to initialize the `total.amount` value, because if you try to access like in the last line for the sum, it will crash. So you either initialize it first: +Tendrás que asegurarte de inicializar el valor `total.amount`, porque si intentas acceder como en la última línea para la suma, se bloqueará. Así que o bien la inicializas primero: ```typescript let total = Total.load('latest') @@ -391,7 +386,7 @@ if (total === null) { total.tokens = total.tokens + BigInt.fromI32(1) ``` -Or you can just change your GraphQL schema to not use a nullable type for this property, then we'll initialize it as zero on the `codegen` step 😉 +O simplemente puedes cambiar tu esquema GraphQL para no usar un tipo anulable para esta propiedad, entonces la inicializaremos como cero en el paso `codegen` 😉 ```graphql type Total @entity { @@ -410,9 +405,9 @@ if (total === null) { total.amount = total.amount + BigInt.fromI32(1) ``` -### Class property initialization +### Inicialización de las propiedades de la clase -If you export any classes with properties that are other classes (declared by you or by the standard library) like this: +Si exportas alguna clase con propiedades que son otras clases (declaradas por ti o por la libreria estándar) así: ```typescript class Thing {} @@ -422,7 +417,7 @@ export class Something { } ``` -The compiler will error because you either need to add an initializer for the properties that are classes, or add the `!` operator: +El compilador dará un error porque tienes que añadir un inicializador para las propiedades que son clases, o añadir el operador `!`: ```typescript export class Something { @@ -446,11 +441,11 @@ export class Something { } ``` -### GraphQL schema +### Esquema GraphQL -This is not a direct AssemblyScript change, but you may have to update your `schema.graphql` file. +Esto no es un cambio directo de AssemblyScript, pero es posible que tengas que actualizar tu archivo `schema.graphql`. -Now you no longer can define fields in your types that are Non-Nullable Lists. If you have a schema like this: +Ahora ya no puedes definir campos en tus tipos que sean Listas No Anulables. Si tienes un esquema como este: ```graphql type Something @entity { @@ -463,7 +458,7 @@ type MyEntity @entity { } ``` -You'll have to add an `!` to the member of the List type, like this: +Tendrás que añadir un `!` al miembro de la Lista tipo, así: ```graphql type Something @entity { @@ -476,14 +471,14 @@ type MyEntity @entity { } ``` -This changed because of nullability differences between AssemblyScript versions, and it's related to the `src/generated/schema.ts` file (default path, you might have changed this). +Esto ha cambiado 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). -### Other +### Otros -- Aligned `Map#set` and `Set#add` with the spec, returning `this` ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) -- Arrays no longer inherit from ArrayBufferView, but are now distinct ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -- 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)) -- Bug fix of relational string comparisons when sizes differ ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) +- 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)) +- 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)) +- 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/pages/es/developer/create-subgraph-hosted.mdx b/pages/es/developer/create-subgraph-hosted.mdx index 3b05b2548456..76a1af304e61 100644 --- a/pages/es/developer/create-subgraph-hosted.mdx +++ b/pages/es/developer/create-subgraph-hosted.mdx @@ -1,18 +1,18 @@ --- -title: Create a Subgraph +title: Crear un Subgrafo --- -Before being able to use the Graph CLI, you need to create your subgraph in [Subgraph Studio](https://thegraph.com/studio). You will then be able to setup your subgraph project and deploy it to the platform of your choice. Note that **subgraphs that do not index Ethereum mainnet will not be published to The Graph Network**. +Antes de poder utilizar el Graph CLI, tienes que crear tu subgrafo en [Subgraph Studio](https://thegraph.com/studio). A continuación, podrás configurar tu proyecto de subgrafo y desplegarlo en la plataforma que elijas. Ten en cuenta que **los subgrafos que no indexen Ethereum mainnet no se publicarán en The Graph Network**. -The `graph init` command can be used to set up a new subgraph project, either from an existing contract on any of the public Ethereum networks, or from an example subgraph. This command can be used to create a subgraph on the Subgraph Studio by passing in `graph init --product subgraph-studio`. If you already have a smart contract deployed to Ethereum mainnet or one of the testnets, bootstrapping a new subgraph from that contract can be a good way to get started. But first, a little about the networks The Graph supports. +El comando `graph init` se puede utilizar para configurar un nuevo proyecto de subgrafo, ya sea desde un contrato existente en cualquiera de las redes públicas de Ethereum, o desde un subgrafo de ejemplo. Este comando se puede utilizar para crear un subgrafo en el Subgraph Studio pasando `graph init --product subgraph-studio`. Si ya tienes un contrato inteligente desplegado en la red principal de Ethereum o en una de las redes de prueba, arrancar un nuevo subgrafo a partir de ese contrato puede ser una buena manera de empezar. Pero primero, un poco sobre las redes que admite The Graph. -## Supported Networks +## Redes Que Admite -The Graph Network supports subgraphs indexing mainnet Ethereum: +The Graph Network admite subgrafos que indexan la red principal de Ethereum: - `mainnet` -**Additional Networks are supported in beta on the Hosted Service**: +**El Servicio Alojado (Hosted Service) admite Redes Adicionales en la versión beta**: - `mainnet` - `kovan` @@ -44,13 +44,13 @@ The Graph Network supports subgraphs indexing mainnet Ethereum: - `aurora` - `aurora-testnet` -The Graph's Hosted Service relies on the stability and reliability of the underlying technologies, namely the provided JSON RPC endpoints. Newer networks will be marked as being in beta until the network has proven itself in terms of stability, reliability, and scalability. During this beta period, there is risk of downtime and unexpected behaviour. +El Hosted Service (servicio alojado) de The Graph se basa en la estabilidad y la fiabilidad de las tecnologías subyacentes, es decir, los endpoints JSON RPC proporcionados. Las redes más nuevas se marcarán como beta hasta que la red haya demostrado su estabilidad, fiabilidad y escalabilidad. Durante este período beta, existe el riesgo de que se produzcan tiempos de inactividad y comportamientos inesperados. -Remember that you will **not be able** to publish a subgraph that indexes a non-mainnet network to the decentralized Graph Network in [Subgraph Studio](/studio/subgraph-studio). +Recuerda que **no podrás** publicar un subgrafo que indexe una red no-mainnet a la Graph Network descentralizada en [Subgraph Studio](/studio/subgraph-studio). -## From An Existing Contract +## Desde un Contrato Existente -The following command creates a subgraph that indexes all events of an existing contract. It attempts to fetch the contract ABI from Etherscan and falls back to requesting a local file path. If any of the optional arguments are missing, it takes you through an interactive form. +El siguiente comando crea un subgrafo que indexa todos los eventos de un contrato existente. Intenta obtener la ABI del contrato desde Etherscan y vuelve a solicitar una ruta de archivo local. Si falta alguno de los argumentos opcionales, te lleva a través de un formulario interactivo. ```sh graph init \ @@ -61,23 +61,23 @@ graph init \ [] ``` -The `` is the ID of your subgraph in Subgraph Studio, it can be found on your subgraph details page. +El `` es el ID de tu subgrafo en Subgraph Studio, y se puede encontrar en la página de detalles de tu subgrafo. -## From An Example Subgraph +## Desde un Subgrafo de Ejemplo -The second mode `graph init` supports is creating a new project from an example subgraph. The following command does this: +El segundo modo que admite `graph init` es la creación de un nuevo proyecto a partir de un subgrafo de ejemplo. El siguiente comando lo hace: ``` graph init --studio ``` -The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. The following sections will go over the files that make up the subgraph manifest for this example. +El subgrafo de ejemplo se basa en el contrato Gravity de Dani Grant que gestiona los avatares de los usuarios y emite `NewGravatar` o `UpdateGravatar` cada vez que se crean o actualizan los avatares. El subgrafo maneja estos eventos escribiendo entidades `Gravatar` en el almacén de Graph Node y asegurándose de que éstas se actualicen según los eventos. Las siguientes secciones repasarán los archivos que componen el manifiesto del subgrafo para este ejemplo. -## The Subgraph Manifest +## El Manifiesto de Subgrafo -The subgraph manifest `subgraph.yaml` defines the smart contracts your subgraph indexes, which events from these contracts to pay attention to, and how to map event data to entities that Graph Node stores and allows to query. The full specification for subgraph manifests can be found [here](https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md). +El manifiesto del subgrafo `subgraph.yaml` define los contratos inteligentes que indexa tu subgrafo, a qué eventos de estos contratos prestar atención, y cómo mapear los datos de los eventos a las entidades que Graph Node almacena y permite consultar. La especificación completa de los manifiestos de subgrafos puede encontrarse en [here](https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md). -For the example subgraph, `subgraph.yaml` is: +Para este subgrafo de ejemplo, `subgraph.yaml` es: ```yaml specVersion: 0.0.4 @@ -118,59 +118,59 @@ dataSources: file: ./src/mapping.ts ``` -The important entries to update for the manifest are: +Las entradas importantes a actualizar para el manifiesto son: -- `description`: a human-readable description of what the subgraph is. This description is displayed by the Graph Explorer when the subgraph is deployed to the Hosted Service. +- `description`: una descripción legible para el ser humano de lo que es el subgrafo. Esta descripción es mostrada por The Graph Explorer cuando el subgrafo se despliega en el Servicio Alojado. -- `repository`: the URL of the repository where the subgraph manifest can be found. This is also displayed by the Graph Explorer. +- `repository`: la URL del repositorio donde se encuentra el manifiesto del subgrafo. Esto también lo muestra The Graph Explorer. -- `features`: a list of all used [feature](#experimental-features) names. +- `features`: una lista de todos los nombres de las [feature](#experimental-features) usadas. -- `dataSources.source`: the address of the smart contract the subgraph sources, and the abi of the smart contract to use. The address is optional; omitting it allows to index matching events from all contracts. +- `dataSources.source`: la address del contrato inteligente, las fuentes del subgrafo, y el abi del contrato inteligente a utilizar. La address es opcional; omitirla permite indexar los eventos coincidentes de todos los contratos. -- `dataSources.source.startBlock`: the optional number of the block that the data source starts indexing from. In most cases we suggest using the block in which the contract was created. +- `dataSources.source.startBlock`: el número opcional del bloque desde el que la fuente de datos comienza a indexar. En la mayoría de los casos, sugerimos utilizar el bloque en el que se creó el contrato. -- `dataSources.mapping.entities`: the entities that the data source writes to the store. The schema for each entity is defined in the the schema.graphql file. +- `dataSources.mapping.entities`: las entidades que la fuente de datos escribe en el almacén. El esquema de cada entidad se define en el archivo schema.graphql. -- `dataSources.mapping.abis`: one or more named ABI files for the source contract as well as any other smart contracts that you interact with from within the mappings. +- `dataSources.mapping.abis`: uno o más archivos ABI con nombre para el contrato fuente, así como cualquier otro contrato inteligente con el que interactúes desde los mapeos. -- `dataSources.mapping.eventHandlers`: lists the smart contract events this subgraph reacts to and the handlers in the mapping—./src/mapping.ts in the example—that transform these events into entities in the store. +- `dataSources.mapping.eventHandlers`: enumera los eventos de contratos inteligentes a los que reacciona este subgrafo y los handlers en el mapeo -./src/mapping.ts en el ejemplo- que transforman estos eventos en entidades en el almacén. -- `dataSources.mapping.callHandlers`: lists the smart contract functions this subgraph reacts to and handlers in the mapping that transform the inputs and outputs to function calls into entities in the store. +- `dataSources.mapping.callHandlers`: enumera las funciones de contrato inteligente a las que reacciona este subgrafo y los handlers en el mapeo que transforman las entradas y salidas a las llamadas de función en entidades en el almacén. -- `dataSources.mapping.blockHandlers`: lists the blocks this subgraph reacts to and handlers in the mapping to run when a block is appended to the chain. Without a filter, the block handler will be run every block. An optional filter can be provided with the following kinds: call`. A`call` filter will run the handler if the block contains at least one call to the data source contract. +- `dataSources.mapping.blockHandlers`: enumera los bloques a los que reacciona este subgrafo y los handlers en el mapeo que se ejecutan cuando un bloque se agrega a la cadena. Sin un filtro, el handler de bloque se ejecutará en cada bloque. Se puede proporcionar un filtro opcional con los siguientes tipos: call`. Un filtro `call` ejecutará el handler si el bloque contiene al menos una llamada al contrato de la fuente de datos. -A single subgraph can index data from multiple smart contracts. Add an entry for each contract from which data needs to be indexed to the `dataSources` array. +Un único subgrafo puede indexar datos de múltiples contratos inteligentes. Añade una entrada por cada contrato del que haya que indexar datos a la array `dataSources`. -The triggers for a data source within a block are ordered using the following process: +Los disparadores (triggers) de una fuente de datos dentro de un bloque se ordenan mediante el siguiente proceso: -1. Event and call triggers are first ordered by transaction index within the block. -2. Event and call triggers with in the same transaction are ordered using a convention: event triggers first then call triggers, each type respecting the order they are defined in the manifest. -3. Block triggers are run after event and call triggers, in the order they are defined in the manifest. +1. Los disparadores de eventos y llamadas se ordenan primero por el índice de la transacción dentro del bloque. +2. Los disparadores de eventos y llamadas dentro de la misma transacción se ordenan siguiendo una convención: primero los disparadores de eventos y luego los de llamadas, respetando cada tipo el orden en que se definen en el manifiesto. +3. Los disparadores de bloque se ejecutan después de los disparadores de eventos y llamadas, en el orden en que están definidos en el manifiesto. -These ordering rules are subject to change. +Estas normas de orden están sujetas a cambios. -### Getting The ABIs +### Obtención de ABIs -The ABI file(s) must match your contract(s). There are a few ways to obtain ABI files: +Los archivos ABI deben coincidir con tu(s) contrato(s). Hay varias formas de obtener archivos ABI: -- If you are building your own project, you will likely have access to your most current ABIs. -- If you are building a subgraph for a public project, you can download that project to your computer and get the ABI by using [`truffle compile`](https://truffleframework.com/docs/truffle/overview) or using solc to compile. -- You can also find the ABI on [Etherscan](https://etherscan.io/), but this isn't always reliable, as the ABI that is uploaded there may be out of date. Make sure you have the right ABI, otherwise running your subgraph will fail. +- Si estás construyendo tu propio proyecto, es probable que tengas acceso a tus ABIs más actuales. +- Si estás construyendo un subgrafo para un proyecto público, puedes descargar ese proyecto en tu computadora y obtener la ABI utilizando [`truffle compile`](https://truffleframework.com/docs/truffle/overview) or usando solc para compilar. +- También puedes encontrar la ABI en [Etherscan](https://etherscan.io/), pero no siempre es fiable, ya que la ABI que se sube allí puede estar desactualizada. Asegúrate de que tienes la ABI correcta, de lo contrario la ejecución de tu subgrafo fallará. -## The GraphQL Schema +## El Esquema GraphQL -The schema for your subgraph is in the file `schema.graphql`. GraphQL schemas are defined using the GraphQL interface definition language. If you've never written a GraphQL schema, it is recommended that you check out this primer on the GraphQL type system. Reference documentation for GraphQL schemas can be found in the [GraphQL API](/developer/graphql-api) section. +El esquema para tu subgrafo está en el archivo `schema.graphql`. Los esquemas de GraphQL se definen utilizando el lenguaje de definición de interfaces de GraphQL. Si nunca has escrito un esquema GraphQL, es recomendable que consultes este manual sobre el sistema de tipos GraphQL. La documentación de referencia para los esquemas de GraphQL se puede encontrar en la sección [GraphQL API](/developer/graphql-api). -## Defining Entities +## Definir Entidades -Before defining entities, it is important to take a step back and think about how your data is structured and linked. All queries will be made against the data model defined in the subgraph schema and the entities indexed by the subgraph. Because of this, it is good to define the subgraph schema in a way that matches the needs of your dapp. It may be useful to imagine entities as "objects containing data", rather than as events or functions. +Antes de definir las entidades, es importante dar un paso atrás y pensar en cómo están estructurados y vinculados los datos. Todas las consultas se harán contra el modelo de datos definido en el esquema del subgrafo y las entidades indexadas por el subgrafo. Debido a esto, es bueno definir el esquema del subgrafo de una manera que coincida con las necesidades de tu dapp. Puede ser útil imaginar las entidades como "objetos que contienen datos", más que como eventos o funciones. -With The Graph, you simply define entity types in `schema.graphql`, and Graph Node will generate top level fields for querying single instances and collections of that entity type. Each type that should be an entity is required to be annotated with an `@entity` directive. +Con The Graph, simplemente defines los tipos de entidad en `schema.graphql`, y Graph Node generará campos de nivel superior para consultar instancias individuales y colecciones de ese tipo de entidad. Cada tipo que deba ser una entidad debe ser anotado con una directiva `@entity`. -### Good Example +### Buen Ejemplo -The `Gravatar` entity below is structured around a Gravatar object and is a good example of how an entity could be defined. +La entidad `Gravatar` que aparece a continuación está estructurada en torno a un objeto Gravatar y es un buen ejemplo de cómo podría definirse una entidad. ```graphql type Gravatar @entity { @@ -182,9 +182,9 @@ type Gravatar @entity { } ``` -### Bad Example +### Mal Ejemplo -The example `GravatarAccepted` and `GravatarDeclined` entities below are based around events. It is not recommended to map events or function calls to entities 1:1. +El ejemplo las entidades `GravatarAccepted` y `GravatarDeclined` que aparecen a continuación se basan en eventos. No se recomienda asignar eventos o llamadas a funciones a entidades 1:1. ```graphql type GravatarAccepted @entity { @@ -202,35 +202,35 @@ type GravatarDeclined @entity { } ``` -### Optional and Required Fields +### Campos Opcionales y Obligatorios -Entity fields can be defined as required or optional. Required fields are indicated by the `!` in the schema. If a required field is not set in the mapping, you will receive this error when querying the field: +Los campos de la entidad pueden definirse como obligatorios u opcionales. Los campos obligatorios se indican con el `!` en el esquema. Si un campo obligatorio no está establecido en la asignación, recibirá este error al consultar el campo: ``` Null value resolved for non-null field 'name' ``` -Each entity must have an `id` field, which is of type `ID!` (string). The `id` field serves as the primary key, and needs to be unique among all entities of the same type. +Cada entidad debe tener un campo `id`, que es de tipo `ID!` (string). El campo `id` sirve de clave primaria y debe ser único entre todas las entidades del mismo tipo. -### Built-In Scalar Types +### Tipos de Scalars incorporados -#### GraphQL Supported Scalars +#### GraphQL admite Scalars -We support the following scalars in our GraphQL API: +Admitimos los siguientes scalars en nuestra API GraphQL: -| Type | Description | -| --- | --- | -| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | -| `ID` | Stored as a `string`. | -| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | -| `Boolean` | Scalar for `boolean` values. | -| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | -| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | -| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | +| Tipo | Descripción | +| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Bytes` | Byte array, representado como un string hexadecimal. Comúnmente utilizado para los hashes y addresses de Ethereum. | +| `ID` | Almacenado como un `string`. | +| `String` | Scalar para valores `string`. Los caracteres null no se admiten y se eliminan automáticamente. | +| `Boolean` | Scalar para valores `boolean`. | +| `Int` | The GraphQL spec define `Int` para tener un tamano de 32 bytes. | +| `BigInt` | Números enteros grandes. Usados para los tipos `uint32`, `int64`, `uint64`, ..., `uint256` de Ethereum. Nota: Todo debajo de `uint32`, como `int32`, `uint24` o `int8` es representado como `i32`. | +| `BigDecimal` | `BigDecimal` Decimales de alta precisión representados como un signo y un exponente. El rango de exponentes va de -6143 a +6144. Redondeado a 34 dígitos significativos. | #### Enums -You can also create enums within a schema. Enums have the following syntax: +También puedes crear enums dentro de un esquema. Los Enums tienen la siguiente sintaxis: ```graphql enum TokenStatus { @@ -240,19 +240,19 @@ enum TokenStatus { } ``` -Once the enum is defined in the schema, you can use the string representation of the enum value to set an enum field on an entity. For example, you can set the `tokenStatus` to `SecondOwner` by first defining your entity and subsequently setting the field with `entity.tokenStatus = "SecondOwner`. The example below demonstrates what the Token entity would look like with an enum field: +Una vez definido el enum en el esquema, puedes utilizar la representación del string del valor del enum para establecer un campo enum en una entidad. Por ejemplo, puedes establecer el `tokenStatus` a `SecondOwner` definiendo primero tu entidad y posteriormente estableciendo el campo con `entity.tokenStatus = "SecondOwner`. El ejemplo siguiente muestra el aspecto de la entidad Token con un campo enum: -More detail on writing enums can be found in the [GraphQL documentation](https://graphql.org/learn/schema/). +Puedes encontrar más detalles sobre la escritura de enums en la [GraphQL documentation](https://graphql.org/learn/schema/). -#### Entity Relationships +#### Relaciones entre Entidades -An entity may have a relationship to one or more other entities in your schema. These relationships may be traversed in your queries. Relationships in The Graph are unidirectional. It is possible to simulate bidirectional relationships by defining a unidirectional relationship on either "end" of the relationship. +Una entidad puede tener una relación con una o más entidades de tu esquema. Estas relaciones pueden ser recorridas en tus consultas. Las relaciones en The Graph son unidireccionales. Es posible simular relaciones bidireccionales definiendo una relación unidireccional en cada "extremo" de la relación. -Relationships are defined on entities just like any other field except that the type specified is that of another entity. +Las relaciones se definen en las entidades como cualquier otro campo, salvo que el tipo especificado es el de otra entidad. -#### One-To-One Relationships +#### Relaciones Uno a Uno -Define a `Transaction` entity type with an optional one-to-one relationship with a `TransactionReceipt` entity type: +Define un tipo de entidad `Transaction` con una relación opcional de uno a uno con un tipo de entidad `TransactionReceipt`: ```graphql type Transaction @entity { @@ -266,9 +266,9 @@ type TransactionReceipt @entity { } ``` -#### One-To-Many Relationships +#### Relaciones Uno-a-Muchos -Define a `TokenBalance` entity type with a required one-to-many relationship with a Token entity type: +Define un tipo de entidad `TokenBalance` con una relación requerida de uno a varios con un tipo de entidad Token: ```graphql type Token @entity { @@ -282,15 +282,15 @@ type TokenBalance @entity { } ``` -#### Reverse Lookups +#### Búsquedas Inversas -Reverse lookups can be defined on an entity through the `@derivedFrom` field. This creates a virtual field on the entity that may be queried but cannot be set manually through the mappings API. Rather, it is derived from the relationship defined on the other entity. For such relationships, it rarely makes sense to store both sides of the relationship, and both indexing and query performance will be better when only one side is stored and the other is derived. +Se pueden definir búsquedas inversas en una entidad a través del campo `@derivedFrom`. Esto crea un campo virtual en la entidad que puede ser consultado pero que no puede ser establecido manualmente a través de la API de mapeo. Más bien, se deriva de la relación definida en la otra entidad. Para este tipo de relaciones, rara vez tiene sentido almacenar ambos lados de la relación, y tanto la indexación como el rendimiento de la consulta serán mejores cuando sólo se almacene un lado y el otro se derive. -For one-to-many relationships, the relationship should always be stored on the 'one' side, and the 'many' side should always be derived. Storing the relationship this way, rather than storing an array of entities on the 'many' side, will result in dramatically better performance for both indexing and querying the subgraph. In general, storing arrays of entities should be avoided as much as is practical. +En el caso de las relaciones uno a muchos, la relación debe almacenarse siempre en el lado "uno", y el lado "muchos" debe derivarse siempre. Almacenar la relación de esta manera, en lugar de almacenar una array de entidades en el lado "muchos", resultará en un rendimiento dramáticamente mejor tanto para la indexación como para la consulta del subgrafo. En general, debe evitarse, en la medida de lo posible, el almacenamiento de arrays de entidades. -#### Example +#### Ejemplo -We can make the balances for a token accessible from the token by deriving a `tokenBalances` field: +Podemos hacer que los balances de un token sean accesibles desde el token derivando un campo `tokenBalances`: ```graphql type Token @entity { @@ -305,13 +305,13 @@ type TokenBalance @entity { } ``` -#### Many-To-Many Relationships +#### Relaciones de Muchos a Muchos -For many-to-many relationships, such as users that each may belong to any number of organizations, the most straightforward, but generally not the most performant, way to model the relationship is as an array in each of the two entities involved. If the relationship is symmetric, only one side of the relationship needs to be stored and the other side can be derived. +Para las relaciones de muchos a muchos, como los usuarios pueden pertenecer a cualquier número de organizaciones, la forma más directa, pero generalmente no la más eficaz, de modelar la relación es como un array en cada una de las dos entidades implicadas. Si la relación es simétrica, sólo es necesario almacenar un lado de la relación y el otro puede derivarse. -#### Example +#### Ejemplo -Define a reverse lookup from a `User` entity type to an `Organization` entity type. In the example below, this is achieved by looking up the `members` attribute from within the `Organization` entity. In queries, the `organizations` field on `User` will be resolved by finding all `Organization` entities that include the user's ID. +Define una búsqueda inversa desde un tipo de entidad `User` a un tipo de entidad `Organization`. En el ejemplo siguiente, esto se consigue buscando el atributo `members` desde la entidad `Organization`. En las consultas, el campo `organizations` en `User` se resolverá buscando todas las entidades de `Organization` que incluyan el ID del usuario. ```graphql type Organization @entity { @@ -327,7 +327,7 @@ type User @entity { } ``` -A more performant way to store this relationship is through a mapping table that has one entry for each `User` / `Organization` pair with a schema like +Una forma más eficaz de almacenar esta relación es a través de una tabla de asignación que tiene una entrada para cada par `User` / `Organization` con un esquema como ```graphql type Organization @entity { @@ -349,7 +349,7 @@ type UserOrganization @entity { } ``` -This approach requires that queries descend into one additional level to retrieve, for example, the organizations for users: +Este enfoque requiere que las consultas desciendan a un nivel adicional para recuperar, por ejemplo, las organizaciones para los usuarios: ```graphql query usersWithOrganizations { @@ -364,11 +364,11 @@ query usersWithOrganizations { } ``` -This more elaborate way of storing many-to-many relationships will result in less data stored for the subgraph, and therefore to a subgraph that is often dramatically faster to index and to query. +Esta forma más elaborada de almacenar las relaciones de muchos a muchos se traducirá en menos datos almacenados para el subgrafo y, por tanto, en un subgrafo que suele ser mucho más rápido de indexar y consultar. -#### Adding comments to the schema +#### Agregar comentarios al esquema -As per GraphQL spec, comments can be added above schema entity attributes using double quotations `""`. This is illustrated in the example below: +Según la especificación GraphQL, se pueden añadir comentarios por encima de los atributos de entidad del esquema utilizando comillas dobles `""`. Esto se ilustra en el siguiente ejemplo: ```graphql type MyFirstEntity @entity { @@ -378,13 +378,13 @@ type MyFirstEntity @entity { } ``` -## Defining Fulltext Search Fields +## Definición de Campos de Búsqueda de Texto Completo -Fulltext search queries filter and rank entities based on a text search input. Fulltext queries are able to return matches for similar words by processing the query text input into stems before comparing to the indexed text data. +Las consultas de búsqueda de texto completo filtran y clasifican las entidades basándose en una entrada de búsqueda de texto. Las consultas de texto completo pueden devolver coincidencias de palabras similares procesando el texto de la consulta en stems antes de compararlo con los datos del texto indexado. -A fulltext query definition includes the query name, the language dictionary used to process the text fields, the ranking algorithm used to order the results, and the fields included in the search. Each fulltext query may span multiple fields, but all included fields must be from a single entity type. +La definición de una consulta de texto completo incluye el nombre de la consulta, el diccionario lingüístico utilizado para procesar los campos de texto, el algoritmo de clasificación utilizado para ordenar los resultados y los campos incluidos en la búsqueda. Cada consulta de texto completo puede abarcar varios campos, pero todos los campos incluidos deben ser de un solo tipo de entidad. -To add a fulltext query, include a `_Schema_` type with a fulltext directive in the GraphQL schema. +Para agregar una consulta de texto completo, incluye un tipo `_Schema_` con una directiva de texto completo en el esquema GraphQL. ```graphql type _Schema_ @@ -407,7 +407,7 @@ type Band @entity { } ``` -The example `bandSearch` field can be used in queries to filter `Band` entities based on the text documents in the `name`, `description`, and `bio` fields. Jump to [GraphQL API - Queries](/developer/graphql-api#queries) for a description of the Fulltext search API and for more example usage. +El ejemplo campo `bandSearch` se puede utilizar en las consultas para filtrar las entidades `Band` con base en los documentos de texto en los campos `name`, `description`, y `bio`. Ve a [GraphQL API - Queries](/developer/graphql-api#queries) para ver una descripción de la API de búsqueda de texto completo y más ejemplos de uso. ```graphql query { @@ -420,49 +420,49 @@ query { } ``` -> **[Feature Management](#experimental-features):** From `specVersion` `0.0.4` and onwards, `fullTextSearch` must be declared under the `features` section in the subgraph manifest. +> **[Feature Management](#experimental-features):** Desde `specVersion` `0.0.4` y en adelante, `fullTextSearch` se debe declarar bajo la sección `features` en el manifiesto del subgrafo. -### Languages supported +### Idiomas admitidos -Choosing a different language will have a definitive, though sometimes subtle, effect on the fulltext search API. Fields covered by a fulltext query field are examined in the context of the chosen language, so the lexemes produced by analysis and search queries vary language to language. For example: when using the supported Turkish dictionary "token" is stemmed to "toke" while, of course, the English dictionary will stem it to "token". +La elección de un idioma diferente tendrá un efecto definitivo, aunque a veces sutil, en la API de búsqueda de texto completo. Los campos cubiertos por un campo de consulta de texto completo se examinan en el contexto de la lengua elegida, por lo que los lexemas producidos por las consultas de análisis y búsqueda varían de un idioma a otro. Por ejemplo: al utilizar el diccionario turco compatible, "token" se convierte en "toke", mientras que el diccionario inglés lo convierte en "token". -Supported language dictionaries: +Diccionarios de idiomas admitidos: -| Code | Dictionary | -| ------ | ---------- | -| simple | General | -| da | Danish | -| nl | Dutch | -| en | English | -| fi | Finnish | -| fr | French | -| de | German | -| hu | Hungarian | -| it | Italian | -| no | Norwegian | -| pt | Portugese | -| ro | Romanian | -| ru | Russian | -| es | Spanish | -| sv | Swedish | -| tr | Turkish | +| Código | Diccionario | +| ------ | ----------- | +| simple | General | +| da | Danés | +| nl | Holandés | +| en | Inglés | +| fi | Finlandés | +| fr | Francés | +| de | Alemán | +| hu | Húngaro | +| it | Italiano | +| no | Noruego | +| pt | Portugués | +| ro | Rumano | +| ru | Ruso | +| es | Español | +| sv | Sueco | +| tr | Turco | -### Ranking Algorithms +### Algoritmos de Clasificación -Supported algorithms for ordering results: +Algoritmos admitidos para ordenar los resultados: -| Algorithm | Description | -| ------------- | ----------------------------------------------------------------------- | -| rank | Use the match quality (0-1) of the fulltext query to order the results. | -| proximityRank | Similar to rank but also includes the proximity of the matches. | +| Algoritmos | Descripción | +| ------------------- | -------------------------------------------------------------------------------------------------- | +| rango | Usa la calidad de coincidencia (0-1) de la consulta de texto completo para ordenar los resultados. | +| rango de Proximidad | Similar al rango, pero también incluye la proximidad de los matches. | -## Writing Mappings +## Escribir Mapeos -The mappings transform the Ethereum data your mappings are sourcing into entities defined in your schema. Mappings are written in a subset of [TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) called [AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki) which can be compiled to WASM ([WebAssembly](https://webassembly.org/)). AssemblyScript is stricter than normal TypeScript, yet provides a familiar syntax. +Los mapeos transforman los datos de Ethereum de los que se abastecen tus mapeos en entidades definidas en tu esquema. Los mapeos se escriben en un subconjunto de [TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) llamado [AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki) que puede ser compilado a WASM ([WebAssembly](https://webassembly.org/)). AssemblyScript es más estricto que el TypeScript normal, pero proporciona una sintaxis familiar. -For each event handler that is defined in `subgraph.yaml` under `mapping.eventHandlers`, create an exported function of the same name. Each handler must accept a single parameter called `event` with a type corresponding to the name of the event which is being handled. +Para cada handler de eventos que se define en `subgraph.yaml` bajo `mapping.eventHandlers`, crea una función exportada del mismo nombre. Cada handler debe aceptar un único parámetro llamado `event` con un tipo correspondiente al nombre del evento que se está manejando. -In the example subgraph, `src/mapping.ts` contains handlers for the `NewGravatar` and `UpdatedGravatar` events: +En el subgrafo de ejemplo, `src/mapping.ts` contiene handlers para los eventos `NewGravatar` y `UpdatedGravatar`: ```javascript import { NewGravatar, UpdatedGravatar } from '../generated/Gravity/Gravity' @@ -489,31 +489,31 @@ export function handleUpdatedGravatar(event: UpdatedGravatar): void { } ``` -The first handler takes a `NewGravatar` event and creates a new `Gravatar` entity with `new Gravatar(event.params.id.toHex())`, populating the entity fields using the corresponding event parameters. This entity instance is represented by the variable `gravatar`, with an id value of `event.params.id.toHex()`. +El primer handler toma un evento `NewGravatar` y crea una nueva entidad `Gravatar` con `new Gravatar(event.params.id.toHex())`, poblando los campos de la entidad usando los parámetros correspondientes del evento. Esta instancia de entidad está representada por la variable `gravatar`, con un valor de id de `event.params.id.toHex()`. -The second handler tries to load the existing `Gravatar` from the Graph Node store. If it does not exist yet, it is created on demand. The entity is then updated to match the new event parameters, before it is saved back to the store using `gravatar.save()`. +El segundo handler intenta cargar el `Gravatar` existente desde el almacén de The Graph Node. Si aún no existe, se crea bajo demanda. A continuación, la entidad se actualiza para que coincida con los nuevos parámetros del evento, antes de volver a guardarla en el almacén mediante `gravatar.save()`. -### Recommended IDs for Creating New Entities +### ID Recomendados para la Creación de Nuevas Entidades -Every entity has to have an `id` that is unique among all entities of the same type. An entity's `id` value is set when the entity is created. Below are some recommended `id` values to consider when creating new entities. NOTE: The value of `id` must be a `string`. +Cada entidad tiene que tener un `id` que sea único entre todas las entidades del mismo tipo. El valor del `id` de una entidad se establece cuando se crea la entidad. A continuación se recomiendan algunos valores de `id` a tener en cuenta a la hora de crear nuevas entidades. NOTA: El valor del `id` debe ser un `string`. - `event.params.id.toHex()` - `event.transaction.from.toHex()` - `event.transaction.hash.toHex() + "-" + event.logIndex.toString()` -We provide the [Graph Typescript Library](https://github.com/graphprotocol/graph-ts) which contains utilies for interacting with the Graph Node store and conveniences for handling smart contract data and entities. You can use this library in your mappings by importing `@graphprotocol/graph-ts` in `mapping.ts`. +Proporcionamos la [Graph Typescript Library](https://github.com/graphprotocol/graph-ts) que contiene utilidades para interactuar con el almacén Graph Node y comodidades para manejar datos y entidades de contratos inteligentes. Puedes utilizar esta biblioteca en tus mapeos importando `@graphprotocol/graph-ts` in `mapping.ts`. -## Code Generation +## Generación de Código -In order to make working smart contracts, events and entities easy and type-safe, the Graph CLI can generate AssemblyScript types from the subgraph's GraphQL schema and the contract ABIs included in the data sources. +Para que trabajar con contratos inteligentes, eventos y entidades sea fácil y seguro desde el punto de vista de los tipos, Graph CLI puede generar tipos AssemblyScript a partir del esquema GraphQL del subgrafo y de las ABIs de los contratos incluidas en las fuentes de datos. -This is done with +Esto se hace con ```sh graph codegen [--output-dir ] [] ``` -but in most cases, subgraphs are already preconfigured via `package.json` to allow you to simply run one of the following to achieve the same: +pero en la mayoría de los casos, los subgrafos ya están preconfigurados a través de `package.json` para permitirte simplemente ejecutar uno de los siguientes para lograr lo mismo: ```sh # Yarn @@ -523,7 +523,7 @@ yarn codegen npm run codegen ``` -This will generate an AssemblyScript class for every smart contract in the ABI files mentioned in `subgraph.yaml`, allowing you to bind these contracts to specific addresses in the mappings and call read-only contract methods against the block being processed. It will also generate a class for every contract event to provide easy access to event parameters as well as the block and transaction the event originated from. All of these types are written to `//.ts`. In the example subgraph, this would be `generated/Gravity/Gravity.ts`, allowing mappings to import these types with +Esto generará una clase AssemblyScript para cada contrato inteligente en los archivos ABI mencionados en `subgraph.yaml`, permitiéndote vincular estos contratos a direcciones específicas en los mapeos y llamar a métodos de contrato de sólo lectura contra el bloque que se está procesando. También generará una clase para cada evento del contrato para facilitar el acceso a los parámetros del evento, así como el bloque y la transacción que originó el evento. Todos estos tipos se escriben en `//.ts`. En el subgrafo de ejemplo, esto sería `generated/Gravity/Gravity.ts`, permitiendo a los mapeos importar estos tipos con ```javascript import { @@ -535,23 +535,23 @@ import { } from '../generated/Gravity/Gravity' ``` -In addition to this, one class is generated for each entity type in the subgraph's GraphQL schema. These classes provide type-safe entity loading, read and write access to entity fields as well as a `save()` method to write entities to store. All entity classes are written to `/schema.ts`, allowing mappings to import them with +Además, se genera una clase para cada tipo de entidad en el esquema GraphQL del subgrafo. Estas clases proporcionan una carga de entidades segura, acceso de lectura y escritura a los campos de la entidad, así como un método `save()` para escribir entidades en el almacén. Todas las clases de entidades se escriben en `/schema.ts`, lo que permite que los mapeos los importen con ```javascript import { Gravatar } from '../generated/schema' ``` -> **Note:** The code generation must be performed again after every change to the GraphQL schema or the ABIs included in the manifest. It must also be performed at least once before building or deploying the subgraph. +> **Nota:** La generación de código debe realizarse de nuevo después de cada cambio en el esquema GraphQL o en las ABIs incluidas en el manifiesto. También debe realizarse al menos una vez antes de construir o desplegar el subgrafo. -Code generation does not check your mapping code in `src/mapping.ts`. If you want to check that before trying to deploy your subgraph to the Graph Explorer, you can run `yarn build` and fix any syntax errors that the TypeScript compiler might find. +La generación de código no comprueba tu código de mapeo en `src/mapping.ts`. Si quieres comprobarlo antes de intentar desplegar tu subgrafo en the Graph Explorer, puedes ejecutar `yarn build` y corregir cualquier error de sintaxis que el compilador de TypeScript pueda encontrar. -## Data Source Templates +## Plantillas de Fuentes de Datos -A common pattern in Ethereum smart contracts is the use of registry or factory contracts, where one contract creates, manages or references an arbitrary number of other contracts that each have their own state and events. The addresses of these sub-contracts may or may not be known upfront and many of these contracts may be created and/or added over time. This is why, in such cases, defining a single data source or a fixed number of data sources is impossible and a more dynamic approach is needed: _data source templates_. +Un patrón común en los contratos inteligentes de Ethereum es el uso de contratos de registro o fábrica, donde un contrato crea, gestiona o hace referencia a un número arbitrario de otros contratos que tienen cada uno su propio estado y eventos. Las direcciones de estos subcontratos pueden o no conocerse de antemano y muchos de estos contratos pueden crearse y/o añadirse con el tiempo. Por eso, en estos casos, es imposible definir una única fuente de datos o un número fijo de fuentes de datos y se necesita un enfoque más dinámico: _data source templates_. -### Data Source for the Main Contract +### Fuente de Datos para el Contrato Principal -First, you define a regular data source for the main contract. The snippet below shows a simplified example data source for the [Uniswap](https://uniswap.io) exchange factory contract. Note the `NewExchange(address,address)` event handler. This is emitted when a new exchange contract is created on chain by the factory contract. +En primer lugar, define una fuente de datos regular para el contrato principal. El siguiente fragmento muestra un ejemplo simplificado de fuente de datos para el contrato de fábrica de exchange [Uniswap](https://uniswap.io). Nota el handler `NewExchange(address,address)` del evento. Se emite cuando el contrato de fábrica crea un nuevo contrato de exchange en la cadena. ```yaml dataSources: @@ -576,9 +576,9 @@ dataSources: handler: handleNewExchange ``` -### Data Source Templates for Dynamically Created Contracts +### Plantillas de Fuentes de Datos para Contratos Creados Dinámicamente -Then, you add _data source templates_ to the manifest. These are identical to regular data sources, except that they lack a predefined contract address under `source`. Typically, you would define one template for each type of sub-contract managed or referenced by the parent contract. +A continuación, añade _plantillas de origen de datos_ al manifiesto. Son idénticas a las fuentes de datos normales, salvo que carecen de una dirección de contrato predefinida en `source`. Normalmente, defines un modelo para cada tipo de subcontrato gestionado o referenciado por el contrato principal. ```yaml dataSources: @@ -612,9 +612,9 @@ templates: handler: handleRemoveLiquidity ``` -### Instantiating a Data Source Template +### Instanciación de una Plantilla de Fuente de Datos -In the final step, you update your main contract mapping to create a dynamic data source instance from one of the templates. In this example, you would change the main contract mapping to import the `Exchange` template and call the `Exchange.create(address)` method on it to start indexing the new exchange contract. +En el último paso, actualiza la asignación del contrato principal para crear una instancia de fuente de datos dinámica a partir de una de las plantillas. En este ejemplo, cambiarías el mapeo del contrato principal para importar la plantilla `Exchange` y llamaría al método `Exchange.create(address)` en él para empezar a indexar el nuevo contrato de exchange. ```typescript import { Exchange } from '../generated/templates' @@ -626,13 +626,13 @@ export function handleNewExchange(event: NewExchange): void { } ``` -> **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks. -> -> If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created. +> **Nota:** Un nuevo origen de datos sólo procesará las llamadas y los eventos del bloque en el que fue creado y todos los bloques siguientes, pero no procesará los datos históricos, es decir, los datos que están contenidos en bloques anteriores. +> +> Si los bloques anteriores contienen datos relevantes para la nueva fuente de datos, lo mejor es indexar esos datos leyendo el estado actual del contrato y creando entidades que representen ese estado en el momento de crear la nueva fuente de datos. -### Data Source Context +### Contexto de la Fuente de Datos -Data source contexts allow passing extra configuration when instantiating a template. In our example, let's say exchanges are associated with a particular trading pair, which is included in the `NewExchange` event. That information can be passed into the instantiated data source, like so: +Los contextos de fuentes de datos permiten pasar una configuración extra al instanciar una plantilla. En nuestro ejemplo, digamos que los exchanges se asocian a un par de trading concreto, que se incluye en el evento `NewExchange`. Esa información se puede pasar a la fuente de datos instanciada, así: ```typescript import { Exchange } from '../generated/templates' @@ -644,7 +644,7 @@ export function handleNewExchange(event: NewExchange): void { } ``` -Inside a mapping of the `Exchange` template, the context can then be accessed: +Dentro de un mapeo de la plantilla `Exchange`, se puede acceder al contexto: ```typescript import { dataSource } from '@graphprotocol/graph-ts' @@ -653,11 +653,11 @@ let context = dataSource.context() let tradingPair = context.getString('tradingPair') ``` -There are setters and getters like `setString` and `getString` for all value types. +Hay setters y getters como `setString` and `getString` para todos los tipos de valores. -## Start Blocks +## Bloques de Inicio -The `startBlock` is an optional setting that allows you to define from which block in the chain the data source will start indexing. Setting the start block allows the data source to skip potentially millions of blocks that are irrelevant. Typically, a subgraph developer will set `startBlock` to the block in which the smart contract of the data source was created. +El `startBlock` es un ajuste opcional que permite definir a partir de qué bloque de la cadena comenzará a indexar la fuente de datos. Establecer el bloque inicial permite a la fuente de datos omitir potencialmente millones de bloques que son irrelevantes. Normalmente, un desarrollador de subgrafos establecerá `startBlock` al bloque en el que se creó el contrato inteligente de la fuente de datos. ```yaml dataSources: @@ -683,23 +683,23 @@ dataSources: handler: handleNewEvent ``` -> **Note:** The contract creation block can be quickly looked up on Etherscan: -> -> 1. Search for the contract by entering its address in the search bar. -> 2. Click on the creation transaction hash in the `Contract Creator` section. -> 3. Load the transaction details page where you'll find the start block for that contract. +> **Nota:** El bloque de creación del contrato se puede buscar rápidamente en Etherscan: +> +> 1. Busca el contrato introduciendo su dirección en la barra de búsqueda. +> 2. Haz clic en el hash de la transacción de creación en la sección `Contract Creator`. +> 3. Carga la página de detalles de la transacción, donde encontrarás el bloque inicial de ese contrato. -## Call Handlers +## Handlers de Llamadas -While events provide an effective way to collect relevant changes to the state of a contract, many contracts avoid generating logs to optimize gas costs. In these cases, a subgraph can subscribe to calls made to the data source contract. This is achieved by defining call handlers referencing the function signature and the mapping handler that will process calls to this function. To process these calls, the mapping handler will receive an `ethereum.Call` as an argument with the typed inputs to and outputs from the call. Calls made at any depth in a transaction's call chain will trigger the mapping, allowing activity with the data source contract through proxy contracts to be captured. +Aunque los eventos proporcionan una forma eficaz de recoger los cambios relevantes en el estado de un contrato, muchos contratos evitan generar registros para optimizar los costos de gas. En estos casos, un subgrafo puede suscribirse a las llamadas realizadas al contrato de la fuente de datos. Esto se consigue definiendo los handlers de llamadas que hacen referencia a la firma de la función y al handler de mapeo que procesará las llamadas a esta función. Para procesar estas llamadas, el manejador de mapeo recibirá un `ethereum.Call` como argumento con las entradas y salidas tipificadas de la llamada. Las llamadas realizadas en cualquier profundidad de la cadena de llamadas de una transacción activarán el mapeo, permitiendo capturar la actividad con el contrato de origen de datos a través de los contratos proxy. -Call handlers will only trigger in one of two cases: when the function specified is called by an account other than the contract itself or when it is marked as external in Solidity and called as part of another function in the same contract. +Los handlers de llamadas sólo se activarán en uno de estos dos casos: cuando la función especificada sea llamada por una cuenta distinta del propio contrato o cuando esté marcada como externa en Solidity y sea llamada como parte de otra función en el mismo contrato. -> **Note:** Call handlers are not supported on Rinkeby, Goerli or Ganache. Call handlers currently depend on the Parity tracing API and these networks do not support it. +> **Nota:**Los handlers de llamadas no son compatibles con Rinkeby, Goerli o Ganache. Los handlers de llamadas dependen actualmente de la API de rastreo de Parity y estas redes no la admiten. -### Defining a Call Handler +### Definición de un Handler de Llamadas -To define a call handler in your manifest simply add a `callHandlers` array under the data source you would like to subscribe to. +Para definir un handler de llamadas en su manifiesto simplemente añade una array `callHandlers` bajo la fuente de datos a la que deseas suscribirte. ```yaml dataSources: @@ -724,11 +724,11 @@ dataSources: handler: handleCreateGravatar ``` -The `function` is the normalized function signature to filter calls by. The `handler` property is the name of the function in your mapping you would like to execute when the target function is called in the data source contract. +La `función` es la firma de la función normalizada por la que se filtran las llamadas. La propiedad `handler` es el nombre de la función de tu mapeo que quieres ejecutar cuando se llame a la función de destino en el contrato de origen de datos. -### Mapping Function +### Función Mapeo -Each call handler takes a single parameter that has a type corresponding to the name of the called function. In the example subgraph above, the mapping contains a handler for when the `createGravatar` function is called and receives a `CreateGravatarCall` parameter as an argument: +Cada handler de llamadas toma un solo parámetro que tiene un tipo correspondiente al nombre de la función llamada. En el subgrafo de ejemplo anterior, el mapeo contiene un handler para cuando la función `createGravatar` es llamada y recibe un parámetro `CreateGravatarCall` como argumento: ```typescript import { CreateGravatarCall } from '../generated/Gravity/Gravity' @@ -743,22 +743,22 @@ export function handleCreateGravatar(call: CreateGravatarCall): void { } ``` -The `handleCreateGravatar` function takes a new `CreateGravatarCall` which is a subclass of `ethereum.Call`, provided by `@graphprotocol/graph-ts`, that includes the typed inputs and outputs of the call. The `CreateGravatarCall` type is generated for you when you run `graph codegen`. +La función `handleCreateGravatar` toma una nueva `CreateGravatarCall` que es una subclase de `ethereum.Call`, proporcionada por `@graphprotocol/graph-ts`, que incluye las entradas y salidas tipificadas de la llamada. El tipo `CreateGravatarCall` se genera por ti cuando ejecutas `graph codegen`. -## Block Handlers +## Handlers de Bloques -In addition to subscribing to contract events or function calls, a subgraph may want to update its data as new blocks are appended to the chain. To achieve this a subgraph can run a function after every block or after blocks that match a predefined filter. +Además de suscribirse a eventos del contracto o llamadas a funciones, un subgrafo puede querer actualizar sus datos a medida que se añaden nuevos bloques a la cadena. Para ello, un subgrafo puede ejecutar una función después de cada bloque o después de los bloques que coincidan con un filtro predefinido. -### Supported Filters +### Filtros Admitidos ```yaml filter: kind: call ``` -_The defined handler will be called once for every block which contains a call to the contract (data source) the handler is defined under._ +_El handler definido será llamado una vez por cada bloque que contenga una llamada al contrato (fuente de datos) bajo el cual está definido el handler._ -The absense of a filter for a block handler will ensure that the handler is called every block. A data source can only contain one block handler for each filter type. +La ausencia de un filtro para un handler de bloque asegurará que el handler sea llamado en cada bloque. Una fuente de datos sólo puede contener un handler de bloque para cada tipo de filtro. ```yaml dataSources: @@ -785,9 +785,9 @@ dataSources: kind: call ``` -### Mapping Function +### Función de Mapeo -The mapping function will receive an `ethereum.Block` as its only argument. Like mapping functions for events, this function can access existing subgraph entities in the store, call smart contracts and create or update entities. +La función de mapeo recibirá un `ethereum.Block` como único argumento. Al igual que las funciones de mapeo de eventos, esta función puede acceder a las entidades del subgrafo existentes en el almacén, llamar a los contratos inteligentes y crear o actualizar entidades. ```typescript import { ethereum } from '@graphprotocol/graph-ts' @@ -799,9 +799,9 @@ export function handleBlock(block: ethereum.Block): void { } ``` -## Anonymous Events +## Eventos Anónimos -If you need to process anonymous events in Solidity, that can be achieved by providing the topic 0 of the event, as in the example: +Si necesitas procesar eventos anónimos en Solidity, puedes hacerlo proporcionando el tema 0 del evento, como en el ejemplo: ```yaml eventHandlers: @@ -810,20 +810,20 @@ eventHandlers: handler: handleGive ``` -An event will only be triggered when both the signature and topic 0 match. By default, `topic0` is equal to the hash of the event signature. +Un evento sólo se activará cuando la firma y el tema 0 coincidan. Por defecto, `topic0` es igual al hash de la firma del evento. -## Experimental features +## Características experimentales -Starting from `specVersion` `0.0.4`, subgraph features must be explicitly declared in the `features` section at the top level of the manifest file, using their `camelCase` name, as listed in the table below: +Las características del subgrafo que parten de `specVersion` `0.0.4` deben declararse explícitamente en la sección `features` del nivel superior del archivo del manifiesto, utilizando su nombre `camelCase`, como se indica en la tabla siguiente: -| Feature | Name | +| Característica | Nombre | | --------------------------------------------------------- | ------------------------- | | [Non-fatal errors](#non-fatal-errors) | `nonFatalErrors` | | [Full-text Search](#defining-fulltext-search-fields) | `fullTextSearch` | | [Grafting](#grafting-onto-existing-subgraphs) | `grafting` | | [IPFS on Ethereum Contracts](#ipfs-on-ethereum-contracts) | `ipfsOnEthereumContracts` | -For instance, if a subgraph uses the **Full-Text Search** and the **Non-fatal Errors** features, the `features` field in the manifest should be: +Por ejemplo, si un subgrafo utiliza las características **Full-Text Search** y **Non-fatal Errors**, el campo `features` del manifiesto debería ser: ```yaml specVersion: 0.0.4 @@ -834,27 +834,27 @@ features: dataSources: ... ``` -Note that using a feature without declaring it will incur in a **validation error** during subgraph deployment, but no errors will occur if a feature is declared but not used. +Ten en cuenta que el uso de una característica sin declararla incurrirá en un **error de validación** durante el despliegue del subgrafo, pero no se producirá ningún error si se declara una característica pero no se utiliza. -### IPFS on Ethereum Contracts +### IPFS en Contratos de Ethereum -A common use case for combining IPFS with Ethereum is to store data on IPFS that would be too expensive to maintain on chain, and reference the IPFS hash in Ethereum contracts. +Un caso de uso común para combinar IPFS con Ethereum es almacenar datos en IPFS que serían demasiado costosos de mantener en la cadena, y hacer referencia al hash de IPFS en los contratos de Ethereum. -Given such IPFS hashes, subgraphs can read the corresponding files from IPFS using `ipfs.cat` and `ipfs.map`. To do this reliably, however, it is required that these files are pinned on the IPFS node that the Graph Node indexing the subgraph connects to. In the case of the [hosted service](https://thegraph.com/hosted-service), this is [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs/). +Dados estos hashes de IPFS, los subgrafos pueden leer los archivos correspondientes desde IPFS utilizando `ipfs.cat` y `ipfs.map`. Sin embargo, para hacer esto de forma fiable, es necesario que estos archivos estén anclados en el nodo IPFS al que se conecta the Graph Node que indexa el subgrafo. En el caso del [hosted service](https://thegraph.com/hosted-service), es [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs/). -> **Note:** The Graph Network does not yet support `ipfs.cat` and `ipfs.map`, and developers should not deploy subgraphs using that functionality to the network via the Studio. +> **Nota:** The Graph Network todavía no admite `ipfs.cat` y `ipfs.map`, y los desarrolladores no deben desplegar subgrafos que utilicen esa funcionalidad en la red a través de Studio. -In order to make this easy for subgraph developers, The Graph team wrote a tool for transfering files from one IPFS node to another, called [ipfs-sync](https://github.com/graphprotocol/ipfs-sync). +Para facilitar esto a los desarrolladores de subgrafos, el equipo de The Graph escribió una herramienta para transferir archivos de un nodo IPFS a otro, llamada [ipfs-sync](https://github.com/graphprotocol/ipfs-sync). -> **[Feature Management](#experimental-features):** `ipfsOnEthereumContracts` must be declared under `features` in the subgraph manifest. +> **[La Gestión de Funciones](#experimental-features):** `ipfsOnEthereumContracts` debe declararse en `funciones` en el manifiesto del subgrafo. -### Non-fatal errors +### Errores no fatales -Indexing errors on already synced subgraphs will, by default, cause the subgraph to fail and stop syncing. Subgraphs can alternatively be configured to continue syncing in the presence of errors, by ignoring the changes made by the handler which provoked the error. This gives subgraph authors time to correct their subgraphs while queries continue to be served against the latest block, though the results will possibly be inconsistent due to the bug that caused the error. Note that some errors are still always fatal, to be non-fatal the error must be known to be deterministic. +Los errores de indexación en subgrafos ya sincronizados harán que, por defecto, el subgrafo falle y deje de sincronizarse. Los subgrafos pueden ser configurados alternativamente para continuar la sincronización en presencia de errores, ignorando los cambios realizados por el handler que provocó el error. Esto da a los autores de subgrafos tiempo para corregir sus subgrafos mientras las consultas siguen siendo servidas contra el último bloque, aunque los resultados serán posiblemente inconsistentes debido al fallo que causó el error. Ten en cuenta que algunos errores siguen siendo siempre fatales, para que el error no sea fatal debe saberse que es determinista. -> **Note:** The Graph Network does not yet support non-fatal errors, and developers should not deploy subgraphs using that functionality to the network via the Studio. +> **Nota:** The Graph Network todavía no admite errores no fatales, y los desarrolladores no deben desplegar subgrafos que utilicen esa funcionalidad en la red a través de Studio. -Enabling non-fatal errors requires setting the following feature flag on the subgraph manifest: +La activación de los errores no fatales requiere el establecimiento de la siguiente bandera de características en el manifiesto del subgrafo: ```yaml specVersion: 0.0.4 @@ -864,7 +864,7 @@ features: ... ``` -The query must also opt-in to querying data with potential inconsistencies through the `subgraphError` argument. It is also recommended to query `_meta` to check if the subgraph has skipped over errors, as in the example: +La consulta también debe optar por consultar datos con posibles inconsistencias a través del argumento `subgraphError`. También se recomienda consultar `_meta` para comprobar si el subgrafo ha saltado los errores, como en el ejemplo: ```graphql foos(first: 100, subgraphError: allow) { @@ -876,7 +876,7 @@ _meta { } ``` -If the subgraph encounters an error that query will return both the data and a graphql error with the message `"indexing_error"`, as in this example response: +Si el subgrafo encuentra un error esa consulta devolverá tanto los datos como un error de graphql con el mensaje `"indexing_error"`, como en este ejemplo de respuesta: ```graphql "data": { @@ -896,13 +896,13 @@ If the subgraph encounters an error that query will return both the data and a g ] ``` -### Grafting onto Existing Subgraphs +### Grafting en Subgrafos Existentes -When a subgraph is first deployed, it starts indexing events at the genesis block of the corresponding chain (or at the `startBlock` defined with each data source) In some circumstances, it is beneficial to reuse the data from an existing subgraph and start indexing at a much later block. This mode of indexing is called _Grafting_. Grafting is, for example, useful during development to get past simple errors in the mappings quickly, or to temporarily get an existing subgraph working again after it has failed. +Cuando un subgrafo se despliega por primera vez, comienza a indexar eventos en el bloque génesis de la cadena correspondiente (o en el `startBlock` definido con cada fuente de datos) En algunas circunstancias, es beneficioso reutilizar los datos de un subgrafo existente y comenzar a indexar en un bloque mucho más tarde. Este modo de indexación se denomina _Grafting_. El grafting es, por ejemplo, útil durante el desarrollo para superar rápidamente errores simples en los mapeos, o para hacer funcionar temporalmente un subgrafo existente después de que haya fallado. -> **Note:** Grafting requires that the Indexer has indexed the base subgraph. It is not recommended on The Graph Network at this time, and developers should not deploy subgraphs using that functionality to the network via the Studio. +> **Nota:** El grafting requiere que el indexador haya indexado el subgrafo base. No se recomienda en The Graph Network en este momento, y los desarrolladores no deberían desplegar subgrafos que utilicen esa funcionalidad en la red a través de Studio. -A subgraph is grafted onto a base subgraph when the subgraph manifest in `subgraph.yaml` contains a `graft` block at the toplevel: +Un subgrafo se injerta en un subgrafo base cuando el manifiesto del subgrafo en `subgraph.yaml` contiene un bloque `graft` en el nivel superior: ```yaml description: ... @@ -911,18 +911,18 @@ graft: block: 7345624 # Block number ``` -When a subgraph whose manifest contains a `graft` block is deployed, Graph Node will copy the data of the `base` subgraph up to and including the given `block` and then continue indexing the new subgraph from that block on. The base subgraph must exist on the target Graph Node instance and must have indexed up to at least the given block. Because of this restriction, grafting should only be used during development or during an emergency to speed up producing an equivalent non-grafted subgraph. +Cuando se despliega un subgrafo cuyo manifiesto contiene un bloque `graft`, Graph Node copiará los datos del subgrafo `base` hasta e incluyendo el `block` dado y luego continuará indexando el nuevo subgrafo a partir de ese bloque. El subgrafo base debe existir en el target de Graph Node de destino y debe haber indexado hasta al menos el bloque dado. Debido a esta restricción, el grafting sólo debería utilizarse durante el desarrollo o durante una emergencia para acelerar la producción de un subgrafo equivalente no grafted. -Because grafting copies rather than indexes base data it is much quicker in getting the subgraph to the desired block than indexing from scratch, though the initial data copy can still take several hours for very large subgraphs. While the grafted subgraph is being initialized, the Graph Node will log information about the entity types that have already been copied. +Dado que el grafting copia en lugar de indexar los datos de base, es mucho más rápido llevar el subgrafo al bloque deseado que indexar desde cero, aunque la copia inicial de los datos puede tardar varias horas en el caso de subgrafos muy grandes. Mientras se inicializa el subgrafo grafteado, the Graph Node registrará información sobre los tipos de entidad que ya han sido copiados. -The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right but may deviate from the base subgraph's schema in the following ways: +El subgrafo grafteado puede utilizar un esquema GraphQL que no es idéntico al del subgrafo base, sino simplemente compatible con él. Tiene que ser un esquema de subgrafo válido por sí mismo, pero puede desviarse del esquema del subgrafo base de las siguientes maneras: -- It adds or removes entity types -- It removes attributes from entity types -- It adds nullable attributes to entity types -- It turns non-nullable attributes into nullable attributes -- It adds values to enums -- It adds or removes interfaces -- It changes for which entity types an interface is implemented +- Agrega o elimina tipos de entidades +- Elimina los atributos de los tipos de entidad +- Agrega atributos anulables a los tipos de entidad +- Convierte los atributos no anulables en atributos anulables +- Añade valores a los enums +- Agrega o elimina interfaces +- Cambia para qué tipos de entidades se implementa una interfaz -> **[Feature Management](#experimental-features):** `grafting` must be declared under `features` in the subgraph manifest. +> **[La gestión de características](#experimental-features):** `grafting` se declara en `features` en el manifiesto del subgrafo. diff --git a/pages/es/developer/define-subgraph-hosted.mdx b/pages/es/developer/define-subgraph-hosted.mdx index 92bf5bd8cd2f..64011dddac02 100644 --- a/pages/es/developer/define-subgraph-hosted.mdx +++ b/pages/es/developer/define-subgraph-hosted.mdx @@ -1,34 +1,34 @@ --- -title: Define a Subgraph +title: Definir un Subgrafo --- -A subgraph defines which data The Graph will index from Ethereum, and how it will store it. Once deployed, it will form a part of a global graph of blockchain data. +Un subgrafo define los datos que The Graph indexará de Ethereum, y cómo los almacenará. Una vez desplegado, formará parte de un gráfico global de datos de la blockchain. -![Define a Subgraph](/img/define-subgraph.png) +![Definir un Subgrafo](/img/define-subgraph.png) -The subgraph definition consists of a few files: +La definición del subgrafo consta de unos cuantos archivos: -- `subgraph.yaml`: a YAML file containing the subgraph manifest +- `subgraph.yaml`: un archivo YAML que contiene el manifiesto del subgrafo -- `schema.graphql`: a GraphQL schema that defines what data is stored for your subgraph, and how to query it via GraphQL +- `schema.graphql`: un esquema GraphQL que define qué datos se almacenan para su subgrafo, y cómo consultarlos a través de GraphQL -- `AssemblyScript Mappings`: [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) code that translates from the event data to the entities defined in your schema (e.g. `mapping.ts` in this tutorial) +- `AssemblyScript Mappings`: [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) codigo que traduce de los datos del evento a las entidades definidas en su esquema (por ejemplo `mapping.ts` en este tutorial) -Before you go into detail about the contents of the manifest file, you need to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) which you will need to build and deploy a subgraph. +Antes de entrar en detalles sobre el contenido del archivo de manifiesto, es necesario instalar el [Graph CLI](https://github.com/graphprotocol/graph-cli) que necesitarás para construir y desplegar un subgrafo. -## Install the Graph CLI +## Instalar The Graph CLI -The Graph CLI is written in JavaScript, and you will need to install either `yarn` or `npm` to use it; it is assumed that you have yarn in what follows. +The Graph CLI está escrito en JavaScript, y tendrás que instalar `yarn` o `npm` para utilizarlo; se supone que tienes yarn en lo que sigue. -Once you have `yarn`, install the Graph CLI by running +Una vez que tengas `yarn`, instala The Graph CLI ejecutando -**Install with yarn:** +**Instalar con yarn:** ```bash yarn global add @graphprotocol/graph-cli ``` -**Install with npm:** +**Instalar con npm:** ```bash npm install -g @graphprotocol/graph-cli diff --git a/pages/es/developer/deprecating-a-subgraph.mdx b/pages/es/developer/deprecating-a-subgraph.mdx index f8966e025c13..28448746b0a5 100644 --- a/pages/es/developer/deprecating-a-subgraph.mdx +++ b/pages/es/developer/deprecating-a-subgraph.mdx @@ -1,17 +1,17 @@ --- -title: Deprecating a Subgraph +title: Deprecar un Subgrafo --- -So you'd like to deprecate your subgraph on The Graph Explorer. You've come to the right place! Follow the steps below: +Así que te gustaría deprecar tu subgrafo en The Graph Explorer. Has venido al lugar adecuado! Sigue los siguientes pasos: -1. Visit the contract address [here](https://etherscan.io/address/0xadca0dd4729c8ba3acf3e99f3a9f471ef37b6825#writeProxyContract) -2. Call 'deprecateSubgraph' with your own address as the first parameter -3. In the 'subgraphNumber' field, list 0 if it's the first subgraph you're publishing, 1 if it's your second, 2 if it's your third, etc. -4. Inputs for #2 and #3 can be found in your `` which is composed of the `{graphAccount}-{subgraphNumber}`. For example, the [Sushi Subgraph's](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&version=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0-0&view=Overview) ID is `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0>`, which is a combination of `graphAccount` = `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0>` and `subgraphNumber` = `<0>` -5. Voila! Your subgraph will no longer show up on searches on The Graph Explorer. Please note the following: +1. Visita el address del contrato [aquí](https://etherscan.io/address/0xadca0dd4729c8ba3acf3e99f3a9f471ef37b6825#writeProxyContract) +2. Llama a 'deprecateSubgraph' con tu propia dirección como primer parámetro +3. En el campo 'subgraphNumber', anota 0 si es el primer subgrafo que publicas, 1 si es el segundo, 2 si es el tercero, etc. +4. Las entradas para #2 y #3 se pueden encontrar en tu `` que está compuesto por `{graphAccount}-{subgraphNumber}`. Por ejemplo, el [Subgrafo de Sushi](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&version=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0-0&view=Overview) ID is `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0>`, que es una combinación de `graphAccount` = `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0>` y `subgraphNumber` = `<0>` +5. Voila! Tu subgrafo ya no aparecerá en las búsquedas en The Graph Explorer. Ten en cuenta lo siguiente: -- Curators will not be able to signal on the subgraph anymore -- Curators that already signaled on the subgraph will be able to withdraw their signal at an average share price -- Deprecated subgraphs will be indicated with an error message. +- Los curadores ya no podrán señalar en el subgrafo +- Los curadores que ya hayan señalado en el subgrafo podrán retirar su señal a un precio promedio de la participación +- Los subgrafos deprecados se indicarán con un mensaje de error. -If you interacted with the now deprecated subgraph, you'll be able to find it in your user profile under the "Subgraphs", "Indexing", or "Curating" tab respectively. +Si interactuaste con el ahora subgrafo deprecado, podrás encontrarlo en tu perfil de usuario en la pestaña "Subgraphs", "Indexing" o "Curating" respectivamente. diff --git a/pages/es/developer/developer-faq.mdx b/pages/es/developer/developer-faq.mdx index 41449c60e5ab..ed6de912d75e 100644 --- a/pages/es/developer/developer-faq.mdx +++ b/pages/es/developer/developer-faq.mdx @@ -1,70 +1,70 @@ --- -title: Developer FAQs +title: Preguntas Frecuentes de los Desarrolladores --- -### 1. Can I delete my subgraph? +### 1. ¿Puedo eliminar mi subgrafo? -It is not possible to delete subgraphs once they are created. +No es posible eliminar los subgrafos una vez creados. -### 2. Can I change my subgraph name? +### 2. ¿Puedo cambiar el nombre de mi subgrafo? -No. Once a subgraph is created, the name cannot be changed. Make sure to think of this carefully before you create your subgraph so it is easily searchable and identifiable by other dapps. +No. Una vez creado un subgrafo, no se puede cambiar el nombre. Asegúrate de pensar en esto cuidadosamente antes de crear tu subgrafo para que sea fácilmente buscable e identificable por otras dapps. -### 3. Can I change the GitHub account associated with my subgraph? +### 3. ¿Puedo cambiar la cuenta de GitHub asociada a mi subgrafo? -No. Once a subgraph is created, the associated GitHub account cannot be changed. Make sure to think of this carefully before you create your subgraph. +No. Una vez creado un subgrafo, la cuenta de GitHub asociada no puede ser modificada. Asegúrate de pensarlo bien antes de crear tu subgrafo. -### 4. Am I still able to create a subgraph if my smart contracts don't have events? +### 4. ¿Puedo crear un subgrafo si mis contratos inteligentes no tienen eventos? -It is highly recommended that you structure your smart contracts to have events associated with data you are interested in querying. Event handlers in the subgraph are triggered by contract events, and are by far the fastest way to retrieve useful data. +Es muy recomendable que estructures tus contratos inteligentes para tener eventos asociados a los datos que te interesa consultar. Los handlers de eventos en el subgrafo son activados por los eventos de los contratos, y son, con mucho, la forma más rápida de recuperar datos útiles. -If the contracts you are working with do not contain events, your subgraph can use call and block handlers to trigger indexing. Although this is not recommended as performance will be significantly slower. +Si los contratos con los que trabajas no contienen eventos, tu subgrafo puede utilizar handlers de llamadas y bloques para activar la indexación. Aunque esto no se recomienda, ya que el rendimiento será significativamente más lento. -### 5. Is it possible to deploy one subgraph with the same name for multiple networks? +### 5. ¿Es posible desplegar un subgrafo con el mismo nombre para varias redes? -You will need separate names for multiple networks. While you can't have different subgraphs under the same name, there are convenient ways of having a single codebase for multiple networks. Find more on this in our documentation: [Redeploying a Subgraph](/hosted-service/deploy-subgraph-hosted#redeploying-a-subgraph) +Necesitarás nombres distintos para varias redes. Aunque no se pueden tener diferentes subgrafos bajo el mismo nombre, hay formas convenientes de tener una sola base de código para múltiples redes. Encontrará más información al respecto en nuestra documentación: [Redeploying a Subgraph](/hosted-service/deploy-subgraph-hosted#redeploying-a-subgraph) -### 6. How are templates different from data sources? +### 6. ¿En qué se diferencian las plantillas de las fuentes de datos? -Templates allow you to create data sources on the fly, while your subgraph is indexing. It might be the case that your contract will spawn new contracts as people interact with it, and since you know the shape of those contracts (ABI, events, etc) up front you can define how you want to index them in a template and when they are spawned your subgraph will create a dynamic data source by supplying the contract address. +Las plantillas permiten crear fuentes de datos sobre la marcha, mientras el subgrafo se indexa. Puede darse el caso de que tu contrato genere nuevos contratos a medida que la gente interactúe con él, y dado que conoces la forma de esos contratos (ABI, eventos, etc) por adelantado, puedes definir cómo quieres indexarlos en una plantilla y, cuando se generen, tu subgrafo creará una fuente de datos dinámica proporcionando la dirección del contrato. -Check out the "Instantiating a data source template" section on: [Data Source Templates](/developer/create-subgraph-hosted#data-source-templates). +Consulta la sección "Instalar un modelo de fuente de datos" en: [Data Source Templates](/developer/create-subgraph-hosted#data-source-templates). -### 7. How do I make sure I'm using the latest version of graph-node for my local deployments? +### 7. ¿Cómo puedo asegurarme de que estoy utilizando la última versión de graph-node para mis despliegues locales? -You can run the following command: +Puede ejecutar el siguiente comando: ```sh docker pull graphprotocol/graph-node:latest ``` -**NOTE:** docker / docker-compose will always use whatever graph-node version was pulled the first time you ran it, so it is important to do this to make sure you are up to date with the latest version of graph-node. +**NOTA:** docker / docker-compose siempre utilizará la versión de graph-node que se sacó la primera vez que se ejecutó, por lo que es importante hacer esto para asegurarse de que estás al día con la última versión de graph-node. -### 8. How do I call a contract function or access a public state variable from my subgraph mappings? +### 8. ¿Cómo puedo llamar a una función de contrato o acceder a una variable de estado pública desde mis mapeos de subgrafos? -Take a look at `Access to smart contract` state inside the section [AssemblyScript API](/developer/assemblyscript-api). +Echa un vistazo al estado `Access to smart contract` dentro de la sección [AssemblyScript API](/developer/assemblyscript-api). -### 9. Is it possible to set up a subgraph using `graph init` from `graph-cli` with two contracts? Or should I manually add another datasource in `subgraph.yaml` after running `graph init`? +### 9. ¿Es posible configurar un subgrafo usando `graph init` desde `graph-cli` con dos contratos? ¿O debo añadir manualmente otra fuente de datos en `subgraph.yaml` después de ejecutar `graph init`? -Unfortunately this is currently not possible. `graph init` is intended as a basic starting point, from which you can then add more data sources manually. +Lamentablemente, esto no es posible en la actualidad. `graph init` está pensado como un punto de partida básico, a partir del cual puedes añadir más fuentes de datos manualmente. -### 10. I want to contribute or add a GitHub issue, where can I find the open source repositories? +### 10. Quiero contribuir o agregar una cuestión en GitHub, ¿dónde puedo encontrar los repositorios de código abierto? - [graph-node](https://github.com/graphprotocol/graph-node) - [graph-cli](https://github.com/graphprotocol/graph-cli) - [graph-ts](https://github.com/graphprotocol/graph-ts) -### 11. What is the recommended way to build "autogenerated" ids for an entity when handling events? +### 11. ¿Cuál es la forma recomendada de construir ids "autogenerados" para una entidad cuando se manejan eventos? -If only one entity is created during the event and if there's nothing better available, then the transaction hash + log index would be unique. You can obfuscate these by converting that to Bytes and then piping it through `crypto.keccak256` but this won't make it more unique. +Si sólo se crea una entidad durante el evento y si no hay nada mejor disponible, entonces el hash de la transacción + el índice del registro serían únicos. Puedes ofuscar esto convirtiendo eso en Bytes y luego pasándolo por `crypto.keccak256` pero esto no lo hará más único. -### 12. When listening to multiple contracts, is it possible to select the contract order to listen to events? +### 12. Cuando se escuchan varios contratos, ¿es posible seleccionar el orden de los contratos para escuchar los eventos? -Within a subgraph, the events are always processed in the order they appear in the blocks, regardless of whether that is across multiple contracts or not. +Dentro de un subgrafo, los eventos se procesan siempre en el orden en que aparecen en los bloques, independientemente de que sea a través de múltiples contratos o no. -### 13. Is it possible to differentiate between networks (mainnet, Kovan, Ropsten, local) from within event handlers? +### 13. ¿Es posible diferenciar entre redes (mainnet, Kovan, Ropsten, local) desde los handlers de eventos? -Yes. You can do this by importing `graph-ts` as per the example below: +Sí. Puedes hacerlo importando `graph-ts` como en el ejemplo siguiente: ```javascript import { dataSource } from '@graphprotocol/graph-ts' @@ -73,39 +73,39 @@ dataSource.network() dataSource.address() ``` -### 14. Do you support block and call handlers on Rinkeby? +### 14. ¿Apoyan el bloqueo y los handlers de llamadas en Rinkeby? -On Rinkeby we support block handlers, but without `filter: call`. Call handlers are not supported for the time being. +En Rinkeby apoyamos los handlers de bloque, pero sin `filter: call`. Los handlers de llamadas no son compatibles por el momento. -### 15. Can I import ethers.js or other JS libraries into my subgraph mappings? +### 15. ¿Puedo importar ethers.js u otras bibliotecas JS en mis mapeos de subgrafos? -Not currently, as mappings are written in AssemblyScript. One possible alternative solution to this is to store raw data in entities and perform logic that requires JS libraries on the client. +Actualmente no, ya que los mapeos se escriben en AssemblyScript. Una posible solución alternativa a esto es almacenar los datos en bruto en entidades y realizar la lógica que requiere las bibliotecas JS en el cliente. -### 16. Is it possible to specifying what block to start indexing on? +### 16. ¿Es posible especificar en qué bloque se inicia la indexación? -Yes. `dataSources.source.startBlock` in the `subgraph.yaml` file specifies the number of the block that the data source starts indexing from. In most cases we suggest using the block in which the contract was created: Start blocks +Sí. `dataSources.source.startBlock` en el `subgraph.yaml` especifica el número del bloque a partir del cual la fuente de datos comienza a indexar. En la mayoría de los casos, sugerimos utilizar el bloque en el que se creó el contrato: Bloques de inicio -### 17. Are there some tips to increase performance of indexing? My subgraph is taking a very long time to sync. +### 17. ¿Hay algunos consejos para aumentar el rendimiento de la indexación? Mi subgrafo está tardando mucho en sincronizarse. -Yes, you should take a look at the optional start block feature to start indexing from the block that the contract was deployed: [Start blocks](/developer/create-subgraph-hosted#start-blocks) +Sí, deberías echar un vistazo a la función opcional de inicio de bloque para comenzar la indexación desde el bloque en el que se desplegó el contrato: [Start blocks](/developer/create-subgraph-hosted#start-blocks) -### 18. Is there a way to query the subgraph directly to determine what the latest block number it has indexed? +### 18. ¿Hay alguna forma de consultar directamente el subgrafo para determinar cuál es el último número de bloque que ha indexado? -Yes! Try the following command, substituting "organization/subgraphName" with the organization under it is published and the name of your subgraph: +¡Sí! Prueba el siguiente comando, sustituyendo "organization/subgraphName" por la organización bajo la que se publica y el nombre de tu subgrafo: ```sh curl -X POST -d '{ "query": "{indexingStatusForCurrentVersion(subgraphName: \"organization/subgraphName\") { chains { latestBlock { hash number }}}}"}' https://api.thegraph.com/index-node/graphql ``` -### 19. What networks are supported by The Graph? +### 19. ¿Qué redes son compatibles con The Graph? -The graph-node supports any EVM-compatible JSON RPC API chain. +The Graph Node admite cualquier cadena de API JSON RPC compatible con EVM. -The Graph Network supports subgraphs indexing mainnet Ethereum: +The Graph Network admite subgrafos que indexan la red principal de Ethereum: - `mainnet` -In the Hosted Service, the following networks are supported: +En el Servicio Alojado, se admiten las siguientes redes: - Ethereum mainnet - Kovan @@ -133,40 +133,40 @@ In the Hosted Service, the following networks are supported: - Optimism - Optimism Testnet (on Kovan) -There is work in progress towards integrating other blockchains, you can read more in our repo: [RFC-0003: Multi-Blockchain Support](https://github.com/graphprotocol/rfcs/pull/8/files). +Se está trabajando en la integración de otras blockchains, puedes leer más en nuestro repo: [RFC-0003: Multi-Blockchain Support](https://github.com/graphprotocol/rfcs/pull/8/files). -### 20. Is it possible to duplicate a subgraph to another account or endpoint without redeploying? +### 20. ¿Es posible duplicar un subgrupo en otra cuenta o endpoint sin volver a desplegarlo? -You have to redeploy the subgraph, but if the subgraph ID (IPFS hash) doesn't change, it won't have to sync from the beginning. +Tienes que volver a desplegar el subgrafo, pero si el ID del subgrafo (hash IPFS) no cambia, no tendrá que sincronizarse desde el principio. -### 21. Is this possible to use Apollo Federation on top of graph-node? +### 21. ¿Es posible utilizar Apollo Federation sobre graph-node? -Federation is not supported yet, although we do want to support it in the future. At the moment, something you can do is use schema stitching, either on the client or via a proxy service. +Federation aún no es compatible, aunque queremos apoyarla en el futuro. Por el momento, algo que se puede hacer es utilizar el stitching de esquemas, ya sea en el cliente o a través de un servicio proxy. -### 22. Is there a limit to how many objects The Graph can return per query? +### 22. ¿Existe un límite en el número de objetos que The Graph puede devolver por consulta? -By default query responses are limited to 100 items per collection. If you want to receive more, you can go up to 1000 items per collection and beyond that you can paginate with: +Por defecto, las respuestas a las consultas están limitadas a 100 elementos por colección. Si quieres recibir más, puedes llegar hasta 1000 artículos por colección y más allá puedes paginar con: ```graphql someCollection(first: 1000, skip: ) { ... } ``` -### 23. If my dapp frontend uses The Graph for querying, do I need to write my query key into the frontend directly? What if we pay query fees for users – will malicious users cause our query fees to be very high? +### 23. Si mi dapp frontend utiliza The Graph para la consulta, ¿tengo que escribir mi clave de consulta en el frontend directamente? Si pagamos tasas de consulta a los usuarios, ¿los usuarios malintencionados harán que nuestras tasas de consulta sean muy altas? -Currently, the recommended approach for a dapp is to add the key to the frontend and expose it to end users. That said, you can limit that key to a host name, like _yourdapp.io_ and subgraph. The gateway is currently being run by Edge & Node. Part of the responsibility of a gateway is to monitor for abusive behavior and block traffic from malicious clients. +Actualmente, el enfoque recomendado para una dapp es añadir la clave al frontend y exponerla a los usuarios finales. Dicho esto, puedes limitar esa clave a un nombre de host, como _yourdapp.io_ y subgrafo. El gateway está siendo gestionado actualmente por Edge & Node. Parte de la responsabilidad de un gateway es vigilar los comportamientos abusivos y bloquear el tráfico de los clientes maliciosos. -### 24. Where do I go to find my current subgraph on the Hosted Service? +### 24. ¿Dónde puedo encontrar mi subgrafo actual en el Servicio Alojado? -Head over to the Hosted Service in order to find subgraphs that you or others deployed to the Hosted Service. You can find it [here.](https://thegraph.com/hosted-service) +Dirígete al Servicio Alojado para encontrar los subgrafos que tú u otros desplegaron en el Servicio Alojado. Puedes encontrarlo [aquí.](https://thegraph.com/hosted-service) -### 25. Will the Hosted Service start charging query fees? +### 25. ¿Comenzará el Servicio Alojado a cobrar tasas de consulta? -The Graph will never charge for the Hosted Service. The Graph is a decentralized protocol, and charging for a centralized service is not aligned with The Graph’s values. The Hosted Service was always a temporary step to help get to the decentralized network. Developers will have a sufficient amount of time to migrate to the decentralized network as they are comfortable. +The Graph nunca cobrará por el Servicio Alojado. The Graph es un protocolo descentralizado, y cobrar por un servicio centralizado no está alineado con los valores de The Graph. El Servicio Alojado siempre fue un paso temporal para ayudar a llegar a la red descentralizada. Los desarrolladores dispondrán de tiempo suficiente para migrar a la red descentralizada a medida que se sientan cómodos. -### 26. When will the Hosted Service be shut down? +### 26. ¿Cuándo se cerrará el Servicio Alojado? -If and when there are plans to do this, the community will be notified well ahead of time with considerations made for any subgraphs built on the Hosted Service. +Si y cuando se planee hacer esto, se notificará a la comunidad con suficiente antelación y se tendrán en cuenta los subgrafos construidos en el Servicio Alojado. -### 27. How do I upgrade a subgraph on mainnet? +### 27. ¿Cómo puedo actualizar un subgrafo en mainnet? -If you’re a subgraph developer, you can upgrade a new version of your subgraph to the Studio using the CLI. It’ll be private at that point but if you’re happy with it, you can publish to the decentralized Graph Explorer. This will create a new version of your subgraph that Curators can start signaling on. +Si eres un desarrollador de subgrafos, puedes actualizar una nueva versión de tus subgrafos a Studio utilizando la CLI. En ese momento será privado, pero si estás contento con él, puedes publicarlo en the Graph Explorer descentralizado. Esto creará una nueva versión de tu subgrafo que los Curadoress pueden empezar a señalar. diff --git a/pages/es/developer/distributed-systems.mdx b/pages/es/developer/distributed-systems.mdx index 894fcbe2e18b..bfbc733c4107 100644 --- a/pages/es/developer/distributed-systems.mdx +++ b/pages/es/developer/distributed-systems.mdx @@ -1,37 +1,37 @@ --- -title: Distributed Systems +title: Sistemas Distribuidos --- -The Graph is a protocol implemented as a distributed system. +The Graph es un protocolo implementado como un sistema distribuido. -Connections fail. Requests arrive out of order. Different computers with out-of-sync clocks and states process related requests. Servers restart. Re-orgs happen between requests. These problems are inherent to all distributed systems but are exacerbated in systems operating at a global scale. +Las conexiones fallan. Las solicitudes llegan fuera de orden. Diferentes computadoras con relojes y estados desincronizados procesan solicitudes relacionadas. Los servidores se reinician. Las reorganizaciones se producen entre las solicitudes. Estos problemas son inherentes a todos los sistemas distribuidos, pero se agravan en los sistemas que funcionan a escala mundial. -Consider this example of what may occur if a client polls an Indexer for the latest data during a re-org. +Considera este ejemplo de lo que puede ocurrir si un cliente pregunta a un Indexador por los últimos datos durante una reorganización. -1. Indexer ingests block 8 -2. Request served to the client for block 8 -3. Indexer ingests block 9 -4. Indexer ingests block 10A -5. Request served to the client for block 10A -6. Indexer detects reorg to 10B and rolls back 10A -7. Request served to the client for block 9 -8. Indexer ingests block 10B -9. Indexer ingests block 11 -10. Request served to the client for block 11 +1. El indexador ingiere el bloque 8 +2. Solicitud servida al cliente para el bloque 8 +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 +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 -From the point of view of the Indexer, things are progressing forward logically. Time is moving forward, though we did have to roll back an uncle block and play the block under consensus forward on top of it. Along the way, the Indexer serves requests using the latest state it knows about at that time. +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. -From the point of view of the client, however, things appear chaotic. The client observes that the responses were for blocks 8, 10, 9, and 11 in that order. We call this the "block wobble" problem. When a client experiences block wobble, data may appear to contradict itself over time. The situation worsens when we consider that Indexers do not all ingest the latest blocks simultaneously, and your requests may be routed to multiple Indexers. +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. -It is the responsibility of the client and server to work together to provide consistent data to the user. Different approaches must be used depending on the desired consistency as there is no one right program for every problem. +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. -Reasoning through the implications of distributed systems is hard, but the fix may not be! We've established APIs and patterns to help you navigate some common use-cases. The following examples illustrate those patterns but still elide details required by production code (like error handling and cancellation) to not obfuscate the main ideas. +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. -## Polling for updated data +## Sondeo para obtener datos actualizados -The Graph provides the `block: { number_gte: $minBlock }` API, which ensures that the response is for a single block equal or higher to `$minBlock`. If the request is made to a `graph-node` instance and the min block is not yet synced, `graph-node` will return an error. If `graph-node` has synced min block, it will run the response for the latest block. If the request is made to an Edge & Node Gateway, the Gateway will filter out any Indexers that have not yet synced min block and make the request for the latest block the Indexer has synced. +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. -We can use `number_gte` to ensure that time never travels backward when polling for data in a loop. Here is an example: +Podemos utilizar `number_gte` para asegurarnos de que el tiempo nunca viaja hacia atrás cuando se realizan sondeos de datos en un loop. Aquí hay un ejemplo: ```javascript /// Updates the protocol.paused variable to the latest @@ -73,11 +73,11 @@ async function updateProtocolPaused() { } ``` -## Fetching a set of related items +## Obtención de un conjunto de elementos relacionados -Another use-case is retrieving a large set or, more generally, retrieving related items across multiple requests. Unlike the polling case (where the desired consistency was to move forward in time), the desired consistency is for a single point in time. +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. -Here we will use the `block: { hash: $blockHash }` argument to pin all of our results to the same block. +Aquí utilizaremos el argumento `block: { hash: $blockHash }` para anclar todos nuestros resultados al mismo bloque. ```javascript /// Gets a list of domain names from a single block using pagination @@ -129,4 +129,4 @@ async function getDomainNames() { } ``` -Note that in case of a re-org, the client will need to retry from the first request to update the block hash to a non-uncle block. +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. diff --git a/pages/es/developer/graphql-api.mdx b/pages/es/developer/graphql-api.mdx index 65928d8734e0..4513e9f5c724 100644 --- a/pages/es/developer/graphql-api.mdx +++ b/pages/es/developer/graphql-api.mdx @@ -1,16 +1,16 @@ --- -title: GraphQL API +title: API GraphQL --- -This guide explains the GraphQL Query API that is used for the Graph Protocol. +Esta guía explica la API de consulta GraphQL que se utiliza para the Graph Protocol. -## Queries +## Consultas -In your subgraph schema you define types called `Entities`. For each `Entity` type, an `entity` and `entities` field will be generated on the top-level `Query` type. Note that `query` does not need to be included at the top of the `graphql` query when using The Graph. +En tu esquema de subgrafos defines tipos llamados `Entities`. Por cada tipo de `Entity`, se generará un campo `entity` y `entities` en el nivel superior del tipo `Query`. Ten en cuenta que no es necesario incluir `query` en la parte superior de la consulta `graphql` cuando se utiliza The Graph. -#### Examples +#### Ejemplos -Query for a single `Token` entity defined in your schema: +Consulta de una única entidad `Token` definida en tu esquema: ```graphql { @@ -21,9 +21,9 @@ Query for a single `Token` entity defined in your schema: } ``` -**Note:** When querying for a single entity, the `id` field is required and it must be a string. +**Nota:** Cuando se consulta una sola entidad, el campo `id` es obligatorio y debe ser un string. -Query all `Token` entities: +Consulta todas las entidades `Token`: ```graphql { @@ -34,11 +34,11 @@ Query all `Token` entities: } ``` -### Sorting +### Clasificación -When querying a collection, the `orderBy` parameter may be used to sort by a specific attribute. Additionally, the `orderDirection` can be used to specify the sort direction, `asc` for ascending or `desc` for descending. +Al consultar una colección, el parámetro `orderBy` puede utilizarse para ordenar por un atributo específico. Además, el `orderDirection` se puede utilizar para especificar la dirección de ordenación, `asc` para ascendente o `desc` para descendente. -#### Example +#### Ejemplo ```graphql { @@ -49,17 +49,17 @@ When querying a collection, the `orderBy` parameter may be used to sort by a spe } ``` -### Pagination +### Paginación -When querying a collection, the `first` parameter can be used to paginate from the beginning of the collection. It is worth noting that the default sort order is by ID in ascending alphanumeric order, not by creation time. +Al consultar una colección, el parámetro `first` puede utilizarse para paginar desde el principio de la colección. Cabe destacar que el orden por defecto es por ID en orden alfanumérico ascendente, no por tiempo de creación. -Further, the `skip` parameter can be used to skip entities and paginate. e.g. `first:100` shows the first 100 entities and `first:100, skip:100` shows the next 100 entities. +Además, el parámetro `skip` puede utilizarse para saltar entidades y paginar. por ejemplo, `first:100` muestra las primeras 100 entidades y `first:100, skip:100` muestra las siguientes 100 entidades. -Queries should avoid using very large `skip` values since they generally perform poorly. For retrieving a large number of items, it is much better to page through entities based on an attribute as shown in the last example. +Las consultas deben evitar el uso de valores de `skip` muy grandes, ya que suelen tener un rendimiento deficiente. Para recuperar un gran número de elementos, es mucho mejor para paginar recorrer las entidades basándose en un atributo, como se muestra en el último ejemplo. -#### Example +#### Ejemplo -Query the first 10 tokens: +Consulta los primeros 10 tokens: ```graphql { @@ -70,11 +70,11 @@ Query the first 10 tokens: } ``` -To query for groups of entities in the middle of a collection, the `skip` parameter may be used in conjunction with the `first` parameter to skip a specified number of entities starting at the beginning of the collection. +Para consultar grupos de entidades en medio de una colección, el parámetro `skip` puede utilizarse junto con el parámetro `first` para omitir un número determinado de entidades empezando por el principio de la colección. -#### Example +#### Ejemplo -Query 10 `Token` entities, offset by 10 places from the beginning of the collection: +Consulta 10 entidades `Token`, desplazadas 10 lugares desde el principio de la colección: ```graphql { @@ -85,9 +85,9 @@ Query 10 `Token` entities, offset by 10 places from the beginning of the collect } ``` -#### Example +#### Ejemplo -If a client needs to retrieve a large number of entities, it is much more performant to base queries on an attribute and filter by that attribute. For example, a client would retrieve a large number of tokens using this query: +Si un cliente necesita recuperar un gran número de entidades, es mucho más eficaz basar las consultas en un atributo y filtrar por ese atributo. Por ejemplo, un cliente podría recuperar un gran número de tokens utilizando esta consulta: ```graphql { @@ -100,15 +100,15 @@ If a client needs to retrieve a large number of entities, it is much more perfor } ``` -The first time, it would send the query with `lastID = ""`, and for subsequent requests would set `lastID` to the `id` attribute of the last entity in the previous request. This approach will perform significantly better than using increasing `skip` values. +La primera vez, enviaría la consulta con `lastID = ""`, y para las siguientes peticiones pondría `lastID` al atributo `id` de la última entidad de la petición anterior. Este enfoque tendrá un rendimiento significativamente mejor que el uso de valores crecientes de `skip`. -### Filtering +### Filtro -You can use the `where` parameter in your queries to filter for different properties. You can filter on mulltiple values within the `where` parameter. +Puedes utilizar el parámetro `where` en tus consultas para filtrar por diferentes propiedades. Puedes filtrar por múltiples valores dentro del parámetro `where`. -#### Example +#### Ejemplo -Query challenges with `failed` outcome: +Desafíos de consulta con resultado `failed`: ```graphql { @@ -122,9 +122,9 @@ Query challenges with `failed` outcome: } ``` -You can use suffixes like `_gt`, `_lte` for value comparison: +Puede utilizar sufijos como `_gt`, `_lte` para la comparación de valores: -#### Example +#### Ejemplo ```graphql { @@ -136,7 +136,7 @@ You can use suffixes like `_gt`, `_lte` for value comparison: } ``` -Full list of parameter suffixes: +Lista completa de sufijos de parámetros: ```graphql _not @@ -154,17 +154,17 @@ _not_starts_with _not_ends_with ``` -Please note that some suffixes are only supported for specific types. For example, `Boolean` only supports `_not`, `_in`, and `_not_in`. +Ten en cuenta que algunos sufijos sólo son compatibles con determinados tipos. Por ejemplo, `Boolean` solo admite `_not`, `_in`, y `_not_in`. -### Time-travel queries +### Consultas sobre Time-travel -You can query the state of your entities not just for the latest block, which is the by default, but also for an arbitrary block in the past. The block at which a query should happen can be specified either by its block number or its block hash by including a `block` argument in the toplevel fields of queries. +Puedes consultar el estado de tus entidades no sólo para el último bloque, que es el predeterminado, sino también para un bloque arbitrario en el pasado. El bloque en el que debe producirse una consulta puede especificarse por su número de bloque o su hash de bloque incluyendo un argumento `block` en los campos de nivel superior de las consultas. -The result of such a query will not change over time, i.e., querying at a certain past block will return the same result no matter when it is executed, with the exception that if you query at a block very close to the head of the Ethereum chain, the result might change if that block turns out to not be on the main chain and the chain gets reorganized. Once a block can be considered final, the result of the query will not change. +El resultado de una consulta de este tipo no cambiará con el tiempo, es decir, la consulta en un determinado bloque pasado devolverá el mismo resultado sin importar cuándo se ejecute, con la excepción de que si se consulta en un bloque muy cercano al encabezado de la cadena de Ethereum, el resultado podría cambiar si ese bloque resulta no estar en la cadena principal y la cadena se reorganiza. Una vez que un bloque puede considerarse definitivo, el resultado de la consulta no cambiará. -Note that the current implementation is still subject to certain limitations that might violate these gurantees. The implementation can not always tell that a given block hash is not on the main chain at all, or that the result of a query by block hash for a block that can not be considered final yet might be influenced by a block reorganization running concurrently with the query. They do not affect the results of queries by block hash when the block is final and known to be on the main chain. [This issue](https://github.com/graphprotocol/graph-node/issues/1405) explains what these limitations are in detail. +Ten en cuenta que la implementación está sujeta a ciertas limitaciones que podrían violar estas garantías. La implementación no siempre puede decir que un hash de bloque dado no está en la cadena principal en absoluto, o que el resultado de una consulta por hash de bloque para un bloque que no puede considerarse final todavía podría estar influenciado por una reorganización de bloque que se ejecuta simultáneamente con la consulta. No afectan a los resultados de las consultas por el hash del bloque cuando éste es definitivo y se sabe que está en la cadena principal. [ Esta cuestión](https://github.com/graphprotocol/graph-node/issues/1405) explica con detalle cuáles son estas limitaciones. -#### Example +#### Ejemplo ```graphql { @@ -178,9 +178,9 @@ Note that the current implementation is still subject to certain limitations tha } ``` -This query will return `Challenge` entities, and their associated `Application` entities, as they existed directly after processing block number 8,000,000. +Esta consulta devolverá las entidades `Challenge`, y sus entidades asociadas `Application`, tal y como existían directamente después de procesar el bloque número 8.000.000. -#### Example +#### Ejemplo ```graphql { @@ -194,26 +194,26 @@ This query will return `Challenge` entities, and their associated `Application` } ``` -This query will return `Challenge` entities, and their associated `Application` entities, as they existed directly after processing the block with the given hash. +Esta consulta devolverá las entidades `Challenge`, y sus entidades asociadas `Application`, tal y como existían directamente después de procesar el bloque con el hash dado. -### Fulltext Search Queries +### Consultas de Búsqueda de Texto Completo -Fulltext search query fields provide an expressive text search API that can be added to the subgraph schema and customized. Refer to [Defining Fulltext Search Fields](/developer/create-subgraph-hosted#defining-fulltext-search-fields) to add fulltext search to your subgraph. +Los campos de consulta de búsqueda de texto completo proporcionan una API de búsqueda de texto expresiva que puede añadirse al esquema de subgrafos y personalizarse. Consulta [Definiendo los campos de búsqueda de texto completo](/developer/create-subgraph-hosted#defining-fulltext-search-fields) para añadir la búsqueda de texto completo a tu subgrafo. -Fulltext search queries have one required field, `text`, for supplying search terms. Several special fulltext operators are available to be used in this `text` search field. +Las consultas de búsqueda de texto completo tienen un campo obligatorio, `text`, para suministrar los términos de búsqueda. Hay varios operadores especiales de texto completo que se pueden utilizar en este campo de búsqueda de `text`. -Fulltext search operators: +Operadores de búsqueda de texto completo: -| Symbol | Operator | Description | -| --- | --- | --- | -| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | -| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | -| `<->` | `Follow by` | Specify the distance between two words. | -| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | +| Símbolo | Operador | Descripción | +| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `&` | `And` | Para combinar varios términos de búsqueda en un filtro para entidades que incluyen todos los términos proporcionados | +| | | `Or` | Las consultas con varios términos de búsqueda separados por o el operador devolverá todas las entidades que coincidan con cualquiera de los términos proporcionados | +| `<->` | `Follow by` | Especifica la distancia entre dos palabras. | +| `:*` | `Prefix` | Utilice el término de búsqueda del prefijo para encontrar palabras cuyo prefijo coincida (se requieren 2 caracteres.) | -#### Examples +#### Ejemplos -Using the `or` operator, this query will filter to blog entities with variations of either "anarchism" or "crumpet" in their fulltext fields. +Utilizando el operador `or`, esta consulta filtrará las entidades del blog que tengan variaciones de "anarchism" o de "crumpet" en sus campos de texto completo. ```graphql { @@ -226,7 +226,7 @@ Using the `or` operator, this query will filter to blog entities with variations } ``` -The `follow by` operator specifies a words a specific distance apart in the fulltext documents. The following query will return all blogs with variations of "decentralize" followed by "philosophy" +El operador `follow by` especifica unas palabras a una distancia determinada en los documentos de texto completo. La siguiente consulta devolverá todos los blogs con variaciones de "decentralize" seguidas de "philosophy" ```graphql { @@ -239,7 +239,7 @@ The `follow by` operator specifies a words a specific distance apart in the full } ``` -Combine fulltext operators to make more complex filters. With a pretext search operator combined with a follow by this example query will match all blog entities with words that start with "lou" followed by "music". +Combina los operadores de texto completo para crear filtros más complejos. Con un operador de búsqueda de pretexto combinado con un follow by esta consulta de ejemplo coincidirá con todas las entidades del blog con palabras que empiecen por "lou" seguidas de "music". ```graphql { @@ -252,16 +252,16 @@ Combine fulltext operators to make more complex filters. With a pretext search o } ``` -## Schema +## Esquema -The schema of your data source--that is, the entity types, values, and relationships that are available to query--are defined through the [GraphQL Interface Definition Langauge (IDL)](https://facebook.github.io/graphql/draft/#sec-Type-System). +El esquema de tu fuente de datos, es decir, los tipos de entidad, los valores y las relaciones que están disponibles para la consulta, se definen a través del [GraphQL Interface Definition Language (IDL)](https://facebook.github.io/graphql/draft/#sec-Type-System). -GraphQL schemas generally define root types for `queries`, `subscriptions` and `mutations`. The Graph only supports `queries`. The root `Query` type for your subgraph is automatically generated from the GraphQL schema that's included in your subgraph manifest. +Los esquemas de GraphQL suelen definir tipos raíz para `queries`, `subscriptions` y `mutations`. The Graph solo admite `queries`. El tipo de `Query` raíz de tu subgrafo se genera automáticamente a partir del esquema GraphQL que se incluye en el manifiesto de tu subgrafo. -> **Note:** Our API does not expose mutations because developers are expected to issue transactions directly against the underlying blockchain from their applications. +> **Nota:** Nuestra API no expone mutaciones porque se espera que los desarrolladores emitan transacciones directamente contra la blockchain subyacente desde sus aplicaciones. -### Entities +### Entidades -All GraphQL types with `@entity` directives in your schema will be treated as entities and must have an `ID` field. +Todos los tipos GraphQL con directivas `@entity` en tu esquema serán tratados como entidades y deben tener un campo `ID`. -> **Note:** Currently, all types in your schema must have an `@entity` directive. In the future, we will treat types without an `@entity` directive as value objects, but this is not yet supported. +> **Nota:** Actualmente, todos los tipos de tu esquema deben tener una directiva `@entity`. En el futuro, trataremos los tipos sin una directiva `@entity` como objetos de valor, pero esto todavía no está soportado. diff --git a/pages/es/developer/matchstick.mdx b/pages/es/developer/matchstick.mdx index 3cf1ec761bb9..2cd0e327579d 100644 --- a/pages/es/developer/matchstick.mdx +++ b/pages/es/developer/matchstick.mdx @@ -1,16 +1,16 @@ --- -title: Unit Testing Framework +title: Marco de Unit Testing --- -Matchstick is a unit testing framework, developed by [LimeChain](https://limechain.tech/), that enables subgraph developers to test their mapping logic in a sandboxed environment and deploy their subgraphs with confidence! +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! -Follow the [Matchstick installation guide](https://github.com/LimeChain/matchstick/blob/main/README.md#quick-start-) to install. Now, you can move on to writing your first unit test. +Sigue la [Matchstick installation guide](https://github.com/LimeChain/matchstick/blob/main/README.md#quick-start-) para instalar. Ahora, puede pasar a escribir tu primera unit test. -## Write a Unit Test +## Escribe una Unit Test -Let's see how a simple unit test would look like, using the Gravatar [Example Subgraph](https://github.com/graphprotocol/example-subgraph). +Veamos cómo sería una unit test sencilla, utilizando el Gravatar [Example Subgraph](https://github.com/graphprotocol/example-subgraph). -Assuming we have the following handler function (along with two helper functions to make our life easier): +Suponiendo que tenemos la siguiente función handler (junto con dos funciones de ayuda para facilitarnos la vida): ```javascript export function handleNewGravatar(event: NewGravatar): void { @@ -61,7 +61,7 @@ export function createNewGravatarEvent( } ``` -We first have to create a test file in our project. We have chosen the name `gravity.test.ts`. In the newly created file we need to define a function named `runTests()`. It is important that the function has that exact name. This is an example of how our tests might look like: +Primero tenemos que crear un archivo de prueba en nuestro proyecto. Hemos elegido el nombre `gravity.test.ts`. En el archivo recién creado tenemos que definir una función llamada `runTests()`. Es importante que la función tenga ese nombre exacto. Este es un ejemplo de cómo podrían ser nuestras pruebas: ```typescript import { clearStore, test, assert } from 'matchstick-as/assembly/index' @@ -95,27 +95,27 @@ export function runTests(): void { } ``` -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: +¡Es mucho para desempacar! En primer lugar, una cosa importante a notar es que estamos importando cosas de `matchstick-as`, nuestra biblioteca de ayuda de AssemblyScript (distribuida como un módulo npm). Puedes encontrar el repositorio [aquí](https://github.com/LimeChain/matchstick-as). `matchstick-as` nos proporciona útiles métodos de prueba y también define la función `test()` que utilizaremos para construir nuestros bloques de prueba. El resto es bastante sencillo: esto es lo que ocurre: -- We're setting up our initial state and adding one custom Gravatar entity; -- We define two `NewGravatar` event objects along with their data, using the `createNewGravatarEvent()` function; -- We're calling out handler methods for those events - `handleNewGravatars()` and passing in the list of our custom events; -- We assert the state of the store. How does that work? - We're passing a unique combination of Entity type and id. Then we check a specific field on that Entity and assert that it has the value we expect it to have. We're doing this both for the initial Gravatar Entity we added to the store, as well as the two Gravatar entities that gets added when the handler function is called; -- And lastly - we're cleaning the store using `clearStore()` so that our next test can start with a fresh and empty store object. We can define as many test blocks as we want. +- 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; +- 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. -There we go - we've created our first test! 👏 +Ya está: ¡hemos creado nuestra primera prueba! 👏 -❗ **IMPORTANT:** _In order for the tests to work, we need to export the `runTests()` function in our mappings file. It won't be used there, but the export statement has to be there so that it can get picked up by Rust later when running the tests._ +❗ **IMPORTANTE:** _ Para que las pruebas funcionen, necesitamos exportar la función `runTests()` en nuestro archivo de mapeo. No se utilizará allí, pero la declaración de exportación tiene que estar allí para que pueda ser recogida por Rust más tarde al ejecutar las pruebas._ -You can export the tests wrapper function in your mappings file like this: +Puedes exportar la función wrapper de las pruebas en tu archivo de mapeo de la siguiente manera: ``` export { runTests } from "../tests/gravity.test.ts"; ``` -❗ **IMPORTANT:** _Currently there's an issue with using Matchstick when deploying your subgraph. Please only use Matchstick for local testing, and remove/comment out this line (`export { runTests } from "../tests/gravity.test.ts"`) once you're done. We expect to resolve this issue shortly, sorry for the inconvenience!_ +❗ **IMPORTANTE:** _Actualmente hay un problema con el uso de Matchstick cuando se despliega tu subgrafo. Por favor, sólo usa Matchstick para pruebas locales, y elimina/comenta esta línea (`export { runTests } de "../tests/gravity.test.ts"`) una vez que hayas terminado. Esperamos resolver este problema en breve, ¡disculpa las molestias!_ -_If you don't remove that line, you will get the following error message when attempting to deploy your subgraph:_ +_Si no eliminas esa línea, obtendrás el siguiente mensaje de error al intentar desplegar tu subgrafo:_ ``` /... @@ -123,28 +123,28 @@ Mapping terminated before handling trigger: oneshot canceled .../ ``` -Now in order to run our tests you simply need to run the following in your subgraph root folder: +Ahora, para ejecutar nuestras pruebas, sólo tienes que ejecutar lo siguiente en la carpeta raíz de tu subgrafo: `graph test 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 superadas!"](/img/matchstick-tests-passed.png) -## Common test scenarios +## Escenarios de prueba comunes -### Hydrating the store with a certain state +### Hidratar 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 hidratar 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 +### Llamada 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 a la tienda: ```typescript import { store } from 'matchstick-as/assembly/store' @@ -156,9 +156,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' @@ -180,9 +180,9 @@ export function handleNewGravatars(events: NewGravatar[]): void { } ``` -### Mocking contract calls +### Simular llamadas de contratos -Users can mock contract calls: +Los usuarios pueden simular las llamadas de los contratos: ```typescript import { addMetadata, assert, createMockedFunction, clearStore, test } from 'matchstick-as/assembly/index' @@ -202,9 +202,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 ha demostrado, para simular (mock) una llamada a un contrato y endurecer un valor de retorno, el usuario debe proporcionar una dirección de contrato, el nombre de la función, la firma de la función, una array de argumentos y, por supuesto, el valor de retorno. -Users can also mock function reverts: +Los usuarios también pueden simular las reversiones de funciones: ```typescript let contractAddress = Address.fromString('0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7') @@ -213,9 +213,9 @@ createMockedFunction(contractAddress, 'getGravatar', 'getGravatar(address):(stri .reverts() ``` -### Asserting the state of the store +### Afirmar el estado del almacén -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 hacer una aserción al estado final (o intermedio) del almacén a través de entidades de aserción. Para ello, el usuario tiene que suministrar un tipo de Entidad, el ID específico de una Entidad, el nombre de un campo en esa Entidad y el valor esperado del campo. Aquí hay un ejemplo rápido: ```typescript import { assert } from 'matchstick-as/assembly/index' @@ -227,11 +227,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. +Al ejecutar la función assert.fieldEquals() se comprobará la igualdad del campo dado con el valor esperado dado. La prueba fallará y se emitirá un mensaje de error si los valores son **NO** iguales. En caso contrario, la prueba pasará con éxito. -### Interacting with Event metadata +### Interacción con los metadatos de los 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 utilizar los metadatos de la transacción por defecto, que podrían ser devueltos como un ethereum.Event utilizando la función `newMockEvent()`. El siguiente ejemplo muestra cómo se puede leer/escribir en esos campos del objeto Evento: ```typescript // Read @@ -242,26 +242,26 @@ let UPDATED_ADDRESS = '0xB16081F360e3847006dB660bae1c6d1b2e17eC2A' newGravatarEvent.address = Address.fromString(UPDATED_ADDRESS) ``` -### Asserting variable equality +### Afirmar la igualdad de las 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 es **no** en el almacén -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 almacén. La función toma un tipo de entidad y un id. Si la entidad está de hecho en el almacén, la prueba fallará con un mensaje de error relevante. Aquí hay un ejemplo rápido de cómo utilizar esta funcionalidad: ```typescript assert.notInStore('Gravatar', '23') ``` -### Test run time duration in the log output +### Duración del tiempo de ejecución de la prueba en la salida del registro -The log output includes the test run duration. Here's an example: +La salida del registro incluye la duración de la prueba. Aquí hay un ejemplo: `Jul 09 14:54:42.420 INFO Program execution time: 10.06022ms` -## Feedback +## Comentarios -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 tienes alguna pregunta, comentario, petición de características o simplemente quieres ponerte en contacto, el mejor lugar sería The Graph Discord, donde tenemos un canal dedicado a Matchstick, llamado 🔥| unit-testing. diff --git a/pages/es/developer/publish-subgraph.mdx b/pages/es/developer/publish-subgraph.mdx index 2f35f5eb1bae..2d0a971c4286 100644 --- a/pages/es/developer/publish-subgraph.mdx +++ b/pages/es/developer/publish-subgraph.mdx @@ -1,27 +1,27 @@ --- -title: Publish a Subgraph to the Decentralized Network +title: Publicar un Subgrafo en la Red Descentralizada --- -Once your subgraph has been [deployed to the Subgraph Studio](/studio/deploy-subgraph-studio), you have tested it out, and are ready to put it into production, you can then publish it to the decentralized network. +Una vez que tu subgrafo ha sido [desplegado en el Subgraph Studio](/studio/deploy-subgraph-studio), lo has probado y estás listo para ponerlo en producción, puedes publicarlo en la red descentralizada. -Publishing a Subgraph to the decentralized network makes it available for [curators](/curating) to begin curating on it, and [indexers](/indexing) to begin indexing it. +La publicación de un Subgrafo en la red descentralizada hace que esté disponible para que los [curadores](/curating) comiencen a curar en él, y para que los [indexadores](/indexing) comiencen a indexarlo. -For a walkthrough of how to publish a subgraph to the decentralized network, see [this video](https://youtu.be/HfDgC2oNnwo?t=580). +Para ver un tutorial sobre cómo publicar un subgrafo en la red descentralizada, consulta [este video](https://youtu.be/HfDgC2oNnwo?t=580). -### Networks +### Redes -The decentralized network currently supports both Rinkeby and Ethereum Mainnet. +La red descentralizada admite actualmente tanto Rinkeby como Ethereum Mainnet. -### Publishing a subgraph +### Publicar un subgrafo -Subgraphs can be published to the decentralized network directly from the Subgraph Studio dashboard by clicking on the **Publish** button. Once a subgraph is published, it will be available to view in the [Graph Explorer](https://thegraph.com/explorer/). +Los subgrafos se pueden publicar en la red descentralizada directamente desde el panel de control de Subgraph Studio haciendo clic en el botón **Publish**. Una vez publicado un subgrafo, estará disponible para su visualización en The [Graph Explorer](https://thegraph.com/explorer/). -- Subgraphs published to Rinkeby can index and query data from either the Rinkeby network or Ethereum Mainnet. +- Los subgrafos publicados en Rinkeby pueden indexar y consultar datos de la red Rinkeby o de la red principal de Ethereum. -- Subgraphs published to Ethereum Mainnet can only index and query data from Ethereum Mainnet, meaning that you cannot publish subgraphs to the main decentralized network that index and query testnet data. +- Los subgrafos publicados en la red principal (mainnet) de Ethereum sólo pueden indexar y consultar datos de la red principal de Ethereum, lo que significa que no se pueden publicar subgrafos en la red descentralizada principal que indexen y consulten datos de la red de prueba (testnet). -- When publishing a new version for an existing subgraph the same rules apply as above. +- Cuando se publica una nueva versión para un subgrafo existente se aplican las mismas reglas que las anteriores. -### Updating metadata for a published subgraph +### Actualización de los metadatos de un subgrafo publicado -Once your subgraph has been published to the decentralized network, you can modify the metadata at any time by making the update in the Subgraph Studio dashboard of the subgraph. After saving the changes and publishing your updates to the network, they will be reflected in the Graph Explorer. This won’t create a new version, as your deployment hasn’t changed. +Una vez que tu subgrafo ha sido publicado en la red descentralizada, puedes modificar los metadatos en cualquier momento haciendo la actualización en el panel de control de Subgraph Studio del subgrafo. Luego de guardar los cambios y publicar tus actualizaciones en la red, éstas se reflejarán en The Graph Explorer. Esto no creará una nueva versión, ya que tu despliegue no ha cambiado. diff --git a/pages/es/developer/query-the-graph.mdx b/pages/es/developer/query-the-graph.mdx index ae480b1e6883..f21700f082b8 100644 --- a/pages/es/developer/query-the-graph.mdx +++ b/pages/es/developer/query-the-graph.mdx @@ -1,14 +1,14 @@ --- -title: Query The Graph +title: Consultar The Graph --- -With the subgraph deployed, visit the [Graph Explorer](https://thegraph.com/explorer) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. +Con el subgrafo desplegado, visita el [Graph Explorer](https://thegraph.com/explorer) para abrir una [interfaz GraphQL](https://github.com/graphql/graphiql) en la que podrás explorar la API GraphQL desplegada para el subgrafo emitiendo consultas y viendo el esquema. -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +A continuación se proporciona un ejemplo, pero por favor, consulta la [Query API](/developer/graphql-api) para obtener una referencia completa sobre cómo consultar las entidades del subgrafo. -#### Example +#### Ejemplo -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +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`: ```graphql { @@ -19,14 +19,14 @@ This query lists all the counters our mapping has created. Since we only create } ``` -## Using The Graph Explorer +## Uso de The Graph Explorer -Each subgraph published to the decentralized Graph Explorer has a unique query URL that you can find by navigating to the subgraph details page and clicking on the "Query" button on the top right corner. This will open a side pane that will give you the unique query URL of the subgraph as well as some instructions about how to query it. +Cada subgrafo publicado en The Graph Explorer descentralizado tiene una URL de consulta única que puedes encontrar navegando a la página de detalles del subgrafo y haciendo clic en el botón "Query (Consulta)" en la esquina superior derecha. Esto abrirá un panel lateral que te dará la URL de consulta única del subgrafo, así como algunas instrucciones sobre cómo consultarlo. -![Query Subgraph Pane](/img/query-subgraph-pane.png) +![Panel de Consulta de Subgrafos](/img/query-subgraph-pane.png) -As you can notice, this query URL must use a unique API key. You can create and manage your API keys in the [Subgraph Studio](https://thegraph.com/studio) in the "API Keys" section. Learn more about how to use Subgraph Studio [here](/studio/subgraph-studio). +Como puede observar, esta URL de consulta debe utilizar una clave de API única. Puedes crear y gestionar tus claves API en el [Subgraph Studio](https://thegraph.com/studio) en la sección "API Keys (Claves API)". Aprende a utilizar Subgraph Studio [aquí](/studio/subgraph-studio). -Querying subgraphs using your API keys will generate query fees that will be paid in GRT. You can learn more about billing [here](/studio/billing). +La consulta de subgrafos utilizando tus claves API generará tasas de consulta que se pagarán en GRT. Puedes obtener más información sobre la facturación [aquí](/studio/billing). -You can also use the GraphQL playground in the "Playground" tab to query a subgraph within The Graph Explorer. +También puedes utilizar el playground GraphQL en la pestaña "Playground" para consultar un subgrafo dentro de The Graph Explorer. diff --git a/pages/es/developer/querying-from-your-app.mdx b/pages/es/developer/querying-from-your-app.mdx index c09c44efee72..fb8c7895afaa 100644 --- a/pages/es/developer/querying-from-your-app.mdx +++ b/pages/es/developer/querying-from-your-app.mdx @@ -1,10 +1,10 @@ --- -title: Querying from an Application +title: Consultar desde una Aplicacion --- -Once a subgraph is deployed to the Subgraph Studio or to the Graph Explorer, you will be given the endpoint for your GraphQL API that should look something like this: +Una vez que un subgrafo es desplegado en Subgraph Studio o en The Graph Explorer, se te dará el endpoint para tu API GraphQL que debería ser algo así: -**Subgraph Studio (testing endpoint)** +**Subgraph Studio (endpoint de prueba)** ```sh Queries (HTTP) @@ -18,23 +18,23 @@ Queries (HTTP) https://gateway.thegraph.com/api//subgraphs/id/ ``` -Using the GraphQL endpoint, you can use various GraphQL Client libraries to query the subgraph and populate your app with the data indexed by the subgraph. +Usando el endpoint de GraphQL, puedes usar varias librerías de Clientes de GraphQL para consultar el subgrafo y rellenar tu aplicación con los datos indexados por el subgrafo. -Here are a couple of the more popular GraphQL clients in the ecosystem and how to use them: +A continuación se presentan un par de clientes GraphQL más populares en el ecosistema y cómo utilizarlos: -### Apollo client +### Cliente Apollo -[Apollo client](https://www.apollographql.com/docs/) supports web projects including frameworks like React and Vue, as well as mobile clients like iOS, Android, and React Native. +[Apollo client](https://www.apollographql.com/docs/) admite proyectos web que incluyen frameworks como React y Vue, así como clientes móviles como iOS, Android y React Native. -Let's look at how fetch data from a subgraph with Apollo client in a web project. +Veamos cómo obtener datos de un subgrafo con el cliente Apollo en un proyecto web. -First, install `@apollo/client` and `graphql`: +Primero, instala `@apollo/client` y `graphql`: ```sh npm install @apollo/client graphql ``` -Then you can query the API with the following code: +A continuación, puedes consultar la API con el siguiente código: ```javascript import { ApolloClient, InMemoryCache, gql } from '@apollo/client' @@ -67,7 +67,7 @@ client }) ``` -To use variables, you can pass in a `variables` argument to the query: +Para utilizar variables, puedes pasar un argumento `variables` a la consulta: ```javascript const tokensQuery = ` @@ -100,17 +100,17 @@ client ### URQL -Another option is [URQL](https://formidable.com/open-source/urql/), a somewhat lighter weight GraphQL client library. +Otra opción es [URQL](https://formidable.com/open-source/urql/), una libreria cliente de GraphQL algo más ligera. -Let's look at how fetch data from a subgraph with URQL in a web project. +Veamos cómo obtener datos de un subgrafo con URQL en un proyecto web. -First, install `urql` and `graphql`: +Primero, instala `urql` and `graphql`: ```sh npm install urql graphql ``` -Then you can query the API with the following code: +A continuación, puedes consultar la API con el siguiente código: ```javascript import { createClient } from 'urql' diff --git a/pages/es/developer/quick-start.mdx b/pages/es/developer/quick-start.mdx index 6893d424ddc2..a75c04fadbd1 100644 --- a/pages/es/developer/quick-start.mdx +++ b/pages/es/developer/quick-start.mdx @@ -1,17 +1,17 @@ --- -title: Quick Start +title: Comienzo Rapido --- -This guide will quickly take you through how to initialize, create, and deploy your subgraph on: +Esta guía te llevará rápidamente a través de cómo inicializar, crear y desplegar tu subgrafo en: -- **Subgraph Studio** - used only for subgraphs that index **Ethereum mainnet** -- **Hosted Service** - used for subgraphs that index **other networks** outside of Ethereum mainnnet (e.g. Binance, Matic, etc) +- **Subgraph Studio** - usado solo para subgrafos que indexan en **Ethereum mainnet** +- **Hosted Service** - usado para subgrafos que indexan **otras redes** fuera de Ethereum mainnet (e.g. Binance, Matic, etc) ## Subgraph Studio -### 1. Install the Graph CLI +### 1. Instala The Graph CLI -The Graph CLI is written in JavaScript and you will need to have either `npm` or `yarn` installed to use it. +The Graph CLI esta escrito en JavaScript y necesitaras tener `npm` o `yarn` instalado para usarlo. ```sh # NPM @@ -21,51 +21,51 @@ $ npm install -g @graphprotocol/graph-cli $ yarn global add @graphprotocol/graph-cli ``` -### 2. Initialize your Subgraph +### 2. Inicializa tu Subgrafo -- Initialize your subgraph from an existing contract. +- Inicializa tu subgrafo a partir de un contrato existente. ```sh graph init --studio ``` -- Your subgraph slug is an identifier for your subgraph. The CLI tool will walk you through the steps for creating a subgraph, such as contract address, network, etc as you can see in the screenshot below. +- El slug de tu subgrafo es un identificador para tu subgrafo. La herramienta CLI te guiará a través de los pasos para crear un subgrafo, como la address del contrato, la red, etc., como puedes ver en la captura de pantalla siguiente. -![Subgraph command](/img/Subgraph-Slug.png) +![Comando de Subgrafo](/img/Subgraph-Slug.png) -### 3. Write your Subgraph +### 3. Escribe tu Subgrafo -The previous commands creates a scaffold subgraph that you can use as a starting point for building your subgraph. When making changes to the subgraph, you will mainly work with three files: +Los comandos anteriores crean un subgrafo de andamio que puedes utilizar como punto de partida para construir tu subgrafo. Al realizar cambios en el subgrafo, trabajarás principalmente con tres archivos: -- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraphs will index. -- Schema (schema.graphql) - The GraphQL schema defines what data you wish to retreive from the subgraph. -- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema. +- Manifest (subgraph.yaml) - El manifiesto define qué fuentes de datos indexarán tus subgrafos. +- 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. -For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). +Para más información sobre cómo escribir tu subgrafo, mira [Create a Subgraph](/developer/create-subgraph-hosted). -### 4. Deploy to the Subgraph Studio +### 4. Despliega en Subgraph Studio -- Go to the Subgraph Studio [https://thegraph.com/studio/](https://thegraph.com/studio/) and connect your wallet. -- Click "Create" and enter the subgraph slug you used in step 2. -- Run these commands in the subgraph folder +- Ve a Subgraph Studio [https://thegraph.com/studio/](https://thegraph.com/studio/) y conecta tu wallet. +- Haz clic en "Crear" e introduce el subgrafo que utilizaste en el paso 2. +- Ejecuta estos comandos en la carpeta subgrafo ```sh $ graph codegen $ graph build ``` -- Authenticate and deploy your subgraph. The deploy key can be found on the Subgraph page in Subgraph Studio. +- Autentica y despliega tu subgrafo. La clave para desplegar se puede encontrar en la página de Subgraph en Subgraph Studio. ```sh $ graph auth --studio $ graph deploy --studio ``` -- You will be asked for a version label. It's strongly recommended to use the following conventions for naming your versions. Example: `0.0.1`, `v1`, `version1` +- Se te pedirá una etiqueta de versión. Se recomienda encarecidamente utilizar las siguientes convenciones para nombrar tus versiones. Ejemplo: `0.0.1`, `v1`, `version1` -### 5. Check your logs +### 5. Comprueba tus registros -The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: +Los registros deberían indicarte si hay algún error. Si tu subgrafo está fallando, puedes consultar la fortaleza del subgrafo utilizando la función [GraphiQL Playground](https://graphiql-online.com/). Usa [este endpoint](https://api.thegraph.com/index-node/graphql). Ten en cuenta que puedes aprovechar la consulta de abajo e introducir tu ID de despliegue para tu subgrafo. En este caso, `Qm...` es el ID de despliegue (que puede ser obtenido en la pagina de the Subgraph debado de **Details**). La siguiente consulta te dirá cuándo falla un subgrafo para que puedas depurar en consecuencia: ```sh { @@ -109,15 +109,15 @@ The logs should tell you if there are any errors. If your subgraph is failing, y } ``` -### 6. Query your Subgraph +### 6. Consulta tu Subgrafo -You can now query your subgraph by following [these instructions](/developer/query-the-graph). You can query from your dapp if you don't have your API key via the free, rate limited temporary query URL that can be used for development and staging. You can read the additional instructions for how to query a subgraph from a frontend application [here](/developer/querying-from-your-app). +Ahora puedes consultar tu subgrafo siguiendo [estas instrucciones](/developer/query-the-graph). Puedes consultar desde tu dapp si no tienes tu clave de API a través de la URL de consulta temporal, libre y de tarifa limitada, que puede utilizarse para el desarrollo y la puesta en marcha. Puedes leer las instrucciones adicionales sobre cómo consultar un subgrafo desde una aplicación frontend [aquí](/developer/querying-from-your-app). -## Hosted Service +## Servicio Alojado -### 1. Install the Graph CLI +### 1. Instala The Graph CLI -"The Graph CLI is an npm package and you will need `npm` or `yarn` installed to use it. +"The Graph CLI es un paquete npm y necesitarás `npm` o `yarn` instalado para usarlo. ```sh # NPM @@ -127,39 +127,39 @@ $ npm install -g @graphprotocol/graph-cli $ yarn global add @graphprotocol/graph-cli ``` -### 2. Initialize your Subgraph +### 2. Inicializa tu Subgrafo -- Initialize your subgraph from an existing contract. +- Inicializa tu subgrafo a partir de un contrato existente. ```sh $ graph init --product hosted-service --from-contract
``` -- You will be asked for a subgraph name. The format is `/`. Ex: `graphprotocol/examplesubgraph` +- Se te pedirá un nombre de subgrafo. El formato es `/`. Ex: `graphprotocol/examplesubgraph` -- If you'd like to initialize from an example, run the command below: +- Si quieres inicializar desde un ejemplo, ejecuta el siguiente comando: ```sh $ graph init --product hosted-service --from-example ``` -- In the case of the example, the subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. +- En el caso del ejemplo, el subgrafo se basa en el contrato Gravity de Dani Grant que gestiona los avatares de los usuarios y emite `NewGravatar` o `UpdateGravatar` cada vez que se crean o actualizan los avatares. -### 3. Write your Subgraph +### 3. Escribe tu Subgrafo -The previous command will have created a scaffold from where you can build your subgraph. When making changes to the subgraph, you will mainly work with three files: +El comando anterior habrá creado un andamio a partir del cual puedes construir tu subgrafo. Al realizar cambios en el subgrafo, trabajarás principalmente con tres archivos: -- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraph will index -- Schema (schema.graphql) - The GraphQL schema define what data you wish to retrieve from the subgraph -- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema +- Manifest (subgraph.yaml) - El manifiesto define qué fuentes de datos indexará tu subgrafo +- 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 -For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). +Para más información sobre cómo escribir tu subgrafo, mira [Create a Subgraph](/developer/create-subgraph-hosted). -### 4. Deploy your Subgraph +### 4. Despliega tu Subgrafo -- Sign into the [Hosted Service](https://thegraph.com/hosted-service/) using your github account -- Click Add Subgraph and fill out the required information. Use the same subgraph name as in step 2. -- Run codegen in the subgraph folder +- Firma en el [Hosted Service](https://thegraph.com/hosted-service/) usando tu cuenta github +- Haz clic en Add Subgraph y rellena la información requerida. Utiliza el mismo nombre de subgrafo que en el paso 2. +- Ejecuta codegen en la carpeta del subgrafo ```sh # NPM @@ -169,16 +169,16 @@ $ npm run codegen $ yarn codegen ``` -- Add your Access token and deploy your subgraph. The access token is found on your dashboard in the Hosted Service. +- Agrega tu token de acceso y despliega tu subgrafo. El token de acceso se encuentra en tu panel de control en el Servicio Alojado (Hosted Service). ```sh $ graph auth --product hosted-service $ graph deploy --product hosted-service / ``` -### 5. Check your logs +### 5. Comprueba tus registros -The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: +Los registros deberían indicarte si hay algún error. Si tu subgrafo está fallando, puedes consultar la fortaleza del subgrafo utilizando la función [GraphiQL Playground](https://graphiql-online.com/). Usa [este endpoint](https://api.thegraph.com/index-node/graphql). Ten en cuenta que puedes aprovechar la consulta de abajo e introducir tu ID de despliegue para tu subgrafo. En este caso, `Qm...` es el ID de despliegue (que puede ser obtenido en la pagina de the Subgraph debado de **Details**). La siguiente consulta te dirá cuándo falla un subgrafo para que puedas depurar en consecuencia: ```sh { @@ -222,6 +222,6 @@ The logs should tell you if there are any errors. If your subgraph is failing, y } ``` -### 6. Query your Subgraph +### 6. Consulta tu Subgrafo -Follow [these instructions](/hosted-service/query-hosted-service) to query your subgraph on the Hosted Service. +Sigue [estas instrucciones](/hosted-service/query-hosted-service) para consultar tu subgrafo en el Servicio Alojado (Hosted Service). diff --git a/pages/es/explorer.mdx b/pages/es/explorer.mdx index 72bd427987c2..6ede1f9592e3 100644 --- a/pages/es/explorer.mdx +++ b/pages/es/explorer.mdx @@ -11,7 +11,7 @@ Bienvenido al explorador de The Graph, o como nos gusta llamarlo, tu portal desc title="Reproductor de video de YouTube" frameBorder="0" allowFullScreen - > +> ## Subgrafos @@ -178,7 +178,7 @@ Las métricas de Delegador que verás aquí en esta pestaña incluyen: En la segunda mitad de la página, tienes la tabla de delegaciones. Aquí puedes ver los Indexadores a los que delegaste, así como sus detalles (como recortes de recompensas, tiempo de enfriamiento, etc.). -With the buttons on the right side of the table, you can manage your delegation - delegate more, undelegate, or withdraw your delegation after the thawing period. +Con los botones en el lado derecho de la tabla, puede administrar su delegación: delegar más, quitar su delegación o retirar su delegación después del período de descongelación. Con los botones situados al lado derecho de la tabla, puedes administrar tu delegación: delegar más, anular la delegación actual o retirar tu delegación después del período de descongelación. diff --git a/pages/es/hosted-service/deploy-subgraph-hosted.mdx b/pages/es/hosted-service/deploy-subgraph-hosted.mdx index bdc532e205e4..5b5c2dacade7 100644 --- a/pages/es/hosted-service/deploy-subgraph-hosted.mdx +++ b/pages/es/hosted-service/deploy-subgraph-hosted.mdx @@ -1,56 +1,56 @@ --- -title: Deploy a Subgraph to the Hosted Service +title: Despliega un Subgrafo en el Servicio Alojado --- -If you have not checked out already, check out how to write the files that make up a [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) and how to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) to generate code for your subgraph. Now, it's time to deploy your subgraph to the Hosted Service, also known as the Hosted Service. +Si aún no lo has comprobado, revisa cómo escribir los archivos que componen un [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) y cómo instalar el [Graph CLI](https://github.com/graphprotocol/graph-cli) para generar el código para tu subgrafo. Ahora, es el momento de desplegar tu subgrafo en el Servicio Alojado, también conocido como Hosted Service. -## Create a Hosted Service account +## Crear una cuenta en el Servicio Alojado -Before using the Hosted Service, create an account in our Hosted Service. You will need a [Github](https://github.com/) account for that; if you don't have one, you need to create that first. Then, navigate to the [Hosted Service](https://thegraph.com/hosted-service/), click on the _'Sign up with Github'_ button and complete Github's authorization flow. +Antes de utilizar el Servicio Alojado, crea una cuenta en nuestro Servicio Alojado. Para ello necesitarás una cuenta [Github](https://github.com/); si no tienes una, debes crearla primero. A continuación, navega hasta el [Hosted Service](https://thegraph.com/hosted-service/), haz clic en el botón _'Sign up with Github'_ y completa el flujo de autorización de Github. -## Store the Access Token +## Guardar el Token de Acceso -After creating an account, navigate to your [dashboard](https://thegraph.com/hosted-service/dashboard). Copy the access token displayed on the dashboard and run `graph auth --product hosted-service `. This will store the access token on your computer. You only need to do this once, or if you ever regenerate the access token. +Luego de crear la cuenta, navega a tu [dashboard](https://thegraph.com/hosted-service/dashboard). Copia el token de acceso que aparece en el dashboard y ejecuta `graph auth --product hosted-service `. Esto almacenará el token de acceso en tu computadora. Sólo tienes que hacerlo una vez, o si alguna vez regeneras el token de acceso. -## Create a Subgraph on the Hosted Service +## Crear un Subgrafo en el Servicio Alojado -Before deploying the subgraph, you need to create it in The Graph Explorer. Go to the [dashboard](https://thegraph.com/hosted-service/dashboard) and click on the _'Add Subgraph'_ button and fill in the information below as appropriate: +Antes de desplegar el subgrafo, es necesario crearlo en The Graph Explorer. Ve a [dashboard](https://thegraph.com/hosted-service/dashboard) y haz clic en el botón _'Add Subgraph'_ y completa la información siguiente según corresponda: -**Image** - Select an image to be used as a preview image and thumbnail for the subgraph. +**Image** - Selecciona una imagen que se utilizará como imagen de vista previa y miniatura para el subgrafo. -**Subgraph Name** - Together with the account name that the subgraph is created under, this will also define the `account-name/subgraph-name`-style name used for deployments and GraphQL endpoints. _This field cannot be changed later._ +**Subgraph Name** -Junto con el nombre de la cuenta con la que se crea el subgrafo, esto también definirá el nombre de estilo `account-name/subgraph-name` utilizado para los despliegues y los endpoints de GraphQL. _Este campo no puede ser cambiado posteriormente._ -**Account** - The account that the subgraph is created under. This can be the account of an individual or organization. _Subgraphs cannot be moved between accounts later._ +**Account** - La cuenta con la que se crea el subgrafo. Puede ser la cuenta de un individuo o de una organización. _Los Subgrafos no pueden ser movidos entre cuentas posteriormente._ -**Subtitle** - Text that will appear in subgraph cards. +**Subtitle** - Texto que aparecerá en las tarjetas del subgrafo. -**Description** - Description of the subgraph, visible on the subgraph details page. +**Description** - Descripción del subgrafo, visible en la página de detalles del subgrafo. -**GitHub URL** - Link to the subgraph repository on GitHub. +**GitHub URL** Enlace al repositorio de subgrafos en GitHub. -**Hide** - Switching this on hides the subgraph in the Graph Explorer. +**Hide** - Al activar esta opción se oculta el subgrafo en the Graph Explorer. -After saving the new subgraph, you are shown a screen with help on how to install the Graph CLI, how to generate the scaffolding for a new subgraph, and how to deploy your subgraph. The first two steps were covered in the [Define a Subgraph section](/developer/define-subgraph-hosted). +Después de guardar el nuevo subgrafo, se te muestra una pantalla con ayuda sobre cómo instalar the Graph CLI, cómo generar el andamiaje para un nuevo subgrafo, y cómo desplegar tu subgrafo. Los dos primeros pasos se trataron en la sección [Definir un Subgrafo](/developer/define-subgraph-hosted). -## Deploy a Subgraph on the Hosted Service +## Desplegar un Subgrupo en el Servicio Alojado -Deploying your subgraph will upload the subgraph files that you've built with `yarn build` to IPFS and tell the Graph Explorer to start indexing your subgraph using these files. +El despliegue de tu subgrafo subirá los archivos del subgrafo que has construido con `yarn build` a IPFS y le dirá a Graph Explorer que empiece a indexar tu subgrafo usando estos archivos. -You deploy the subgraph by running `yarn deploy` +El subgrafo lo despliegas ejecutando `yarn deploy` -After deploying the subgraph, the Graph Explorer will switch to showing the synchronization status of your subgraph. Depending on the amount of data and the number of events that need to be extracted from historical Ethereum blocks, starting with the genesis block, syncing can take from a few minutes to several hours. The subgraph status switches to `Synced` once the Graph Node has extracted all data from historical blocks. The Graph Node will continue inspecting Ethereum blocks for your subgraph as these blocks are mined. +Después de desplegar el subgrafo, The Graph Explorer pasará a mostrar el estado de sincronización de tu subgrafo. Dependiendo de la cantidad de datos y del número de eventos que haya que extraer de los bloques históricos de Ethereum, empezando por el bloque génesis, la sincronización puede tardar desde unos minutos hasta varias horas. El estado del subgrafo cambia a `Synced` una vez que the Graph Node ha extraído todos los datos de los bloques históricos. The Graph Node continuará inspeccionando los bloques de Ethereum para tu subgrafo a medida que estos bloques sean minados. -## Redeploying a Subgraph +## Re-Desplegar un Subgrafo -When making changes to your subgraph definition, for example to fix a problem in the entity mappings, run the `yarn deploy` command above again to deploy the updated version of your subgraph. Any update of a subgraph requires that Graph Node reindexes your entire subgraph, again starting with the genesis block. +Cuando hagas cambios en la definición de tu subgrafo, por ejemplo para arreglar un problema en los mapeos de entidades, ejecuta de nuevo el comando `yarn deploy` anterior para desplegar la versión actualizada de tu subgrafo. Cualquier actualización de un subgrafo requiere que Graph Node reindexe todo tu subgrafo, de nuevo empezando por el bloque génesis. -If your previously deployed subgraph is still in status `Syncing`, it will be immediately replaced with the newly deployed version. If the previously deployed subgraph is already fully synced, Graph Node will mark the newly deployed version as the `Pending Version`, sync it in the background, and only replace the currently deployed version with the new one once syncing the new version has finished. This ensures that you have a subgraph to work with while the new version is syncing. +Si tu subgrafo previamente desplegado está todavía en estado `Syncing`, será inmediatamente reemplazado por la nueva versión desplegada. Si el subgrafo previamente desplegado ya está completamente sincronizado, Graph Node marcará la nueva versión desplegada como `Pending Version`, la sincronizará en segundo plano, y sólo reemplazará la versión actualmente desplegada por la nueva una vez que la sincronización de la nueva versión haya terminado. Esto asegura que tienes un subgrafo con el que trabajar mientras la nueva versión se sincroniza. -### Deploying the subgraph to multiple Ethereum networks +### Desplegar el subgrafo en múltiples redes Ethereum -In some cases, you will want to deploy the same subgraph to multiple Ethereum networks without duplicating all of its code. The main challenge that comes with this is that the contract addresses on these networks are different. One solution that allows to parameterize aspects like contract addresses is to generate parts of it using a templating system like [Mustache](https://mustache.github.io/) or [Handlebars](https://handlebarsjs.com/). +En algunos casos, querrás desplegar el mismo subgrafo en múltiples redes Ethereum sin duplicar todo su código. El principal desafío que supone esto es que las direcciones de los contratos en estas redes son diferentes. Una solución que permite parametrizar aspectos como las direcciones de los contratos es generar partes de los mismos mediante un sistema de plantillas como [Mustache](https://mustache.github.io/) o [Handlebars](https://handlebarsjs.com/). -To illustrate this approach, let's assume a subgraph should be deployed to mainnet and Ropsten using different contract addresses. You could then define two config files providing the addresses for each network: +Para ilustrar este enfoque, supongamos que un subgrafo debe desplegarse en mainnet y Ropsten utilizando diferentes direcciones de contrato. Entonces podrías definir dos archivos de configuración que proporcionen las direcciones para cada red: ```json { @@ -59,7 +59,7 @@ To illustrate this approach, let's assume a subgraph should be deployed to mainn } ``` -and +y ```json { @@ -68,7 +68,7 @@ and } ``` -Along with that, you would substitute the network name and addresses in the manifest with variable placeholders `{{network}}` and `{{address}}` and rename the manifest to e.g. `subgraph.template.yaml`: +Junto con eso, sustituirías el nombre de la red y las direcciones en el manifiesto con un marcador de posición variable `{{network}}` y `{{address}}` y renombra el manifiesto a e.g. `subgraph.template.yaml`: ```yaml # ... @@ -85,7 +85,7 @@ dataSources: kind: ethereum/events ``` -In order generate a manifest to either network, you could add two additional commands to `package.json` along with a dependency on `mustache`: +Para generar un manifiesto a cualquiera de las dos redes, podrías añadir dos comandos adicionales a `package.json` junto con una dependencia en `mustache`: ```json { @@ -102,7 +102,7 @@ In order generate a manifest to either network, you could add two additional com } ``` -To deploy this subgraph for mainnet or Ropsten you would now simply run one of the two following commands: +Para desplegar este subgrafo para mainnet o Ropsten, sólo tienes que ejecutar uno de los dos comandos siguientes: ```sh # Mainnet: @@ -112,15 +112,15 @@ yarn prepare:mainnet && yarn deploy yarn prepare:ropsten && yarn deploy ``` -A working example of this can be found [here](https://github.com/graphprotocol/example-subgraph/tree/371232cf68e6d814facf5e5413ad0fef65144759). +Un ejemplo práctico de esto se puede encontrar [aquí](https://github.com/graphprotocol/example-subgraph/tree/371232cf68e6d814facf5e5413ad0fef65144759). -**Note:** This approach can also be applied more complex situations, where it is necessary to substitute more than contract addresses and network names or where generating mappings or ABIs from templates as well. +**Nota:** Este enfoque también puede aplicarse a situaciones más complejas, en las que es necesario sustituir más que las direcciones de los contratos y los nombres de las redes o en las que también se generan mapeos o ABIs a partir de plantillas. -## Checking subgraph health +## Comprobar de la fortaleza del subgrafo -If a subgraph syncs successfully, that is a good sign that it will continue to run well forever. However, new triggers on the chain might cause your subgraph to hit an untested error condition or it may start to fall behind due to performance issues or issues with the node operators. +Si un subgrafo se sincroniza con éxito, es una buena señal de que seguirá funcionando bien para siempre. Sin embargo, los nuevos disparadores en la cadena pueden hacer que tu subgrafo se encuentre con una condición de error no probada o puede empezar a retrasarse debido a problemas de rendimiento o problemas con los operadores de nodos. -Graph Node exposes a graphql endpoint which you can query to check the status of your subgraph. On the Hosted Service, it is available at `https://api.thegraph.com/index-node/graphql`. On a local node it is available on port `8030/graphql` by default. The full schema for this endpoint can be found [here](https://github.com/graphprotocol/graph-node/blob/master/server/index-node/src/schema.graphql). Here is an example query that checks the status of the current version of a subgraph: +Graph Node expone un endpoint graphql que puedes consultar para comprobar el estado de tu subgrafo. En el Servicio Alojado, está disponible en `https://api.thegraph.com/index-node/graphql`. En el nodo local está disponible por default en el puerto `8030/graphql`. El esquema completo para este endpoint se puede encontrar [aquí](https://github.com/graphprotocol/graph-node/blob/master/server/index-node/src/schema.graphql). A continuación se muestra un ejemplo de consulta que comprueba el estado de la versión actual de un subgrafo: ```graphql { @@ -147,14 +147,14 @@ Graph Node exposes a graphql endpoint which you can query to check the status of } ``` -This will give you the `chainHeadBlock` which you can compare with the `latestBlock` on your subgraph to check if it is running behind. `synced` informs if the subgraph has ever caught up to the chain. `health` can currently take the values of `healthy` if no errors ocurred, or `failed` if there was an error which halted the progress of the subgraph. In this case you can check the `fatalError` field for details on this error. +Esto te dará el `chainHeadBlock` que puedes comparar con el `latestBlock` de tu subgrafo para comprobar si se está retrasando. `synced` informa si el subgrafo ha alcanzado la cadena. `health` actualmente puede tomar los valores de `healthy` si no hubo errores, o `failed` si hubo un error que detuvo el progreso del subgrafo. En este caso puedes consultar el campo `fatalError` para conocer los detalles de este error. -## Subgraph archive policy +## Política de archivos de subgrafos -The Hosted Service is a free Graph Node indexer. Developers can deploy subgraphs indexing a range of networks, which will be indexed, and made available to query via graphQL. +El Servicio Alojado es un indexador gratuito de Graph Node. Los desarrolladores pueden desplegar subgrafos que indexen una serie de redes, que serán indexadas y estarán disponibles para su consulta a través de graphQL. -To improve the performance of the service for active subgraphs, the Hosted Service will archive subgraphs which are inactive. +Para mejorar el rendimiento del servicio para los subgrafos activos, el Servicio Alojado archivará los subgrafos que estén inactivos. -**A subgraph is defined as "inactive" if it was deployed to the Hosted Service more than 45 days ago, and if it has received 0 queries in the last 30 days.** +**Un subgrafo se define como "inactivo" si se desplegó en el Servicio Alojado hace más de 45 días, y si ha recibido 0 consultas en los últimos 30 días.** -Developers will be notified by email if one of their subgraphs has been marked as inactive 7 days before it is removed. If they wish to "activate" their subgraph, they can do so by making a query in their subgraph's Hosted Service graphQL playground. Developers can always redeploy an archived subgraph if it is required again. +Los desarrolladores serán notificados por correo electrónico si uno de sus subgrafos ha sido marcado como inactivo 7 días antes de su eliminación. Si desean "activar" su subgrafo, pueden hacerlo realizando una consulta en el playground graphQL de su subgrafo. Los desarrolladores siempre pueden volver a desplegar un subgrafo archivado si lo necesitan de nuevo. diff --git a/pages/es/hosted-service/migrating-subgraph.mdx b/pages/es/hosted-service/migrating-subgraph.mdx index d515d7b7a5b5..eda54d1931ed 100644 --- a/pages/es/hosted-service/migrating-subgraph.mdx +++ b/pages/es/hosted-service/migrating-subgraph.mdx @@ -142,7 +142,7 @@ If you're still confused, fear not! Check out the following resources or watch o title="Reproductor de video de YouTube" frameBorder="0" allowFullScreen - > +> - [The Graph Network Contracts](https://github.com/graphprotocol/contracts) diff --git a/pages/es/hosted-service/query-hosted-service.mdx b/pages/es/hosted-service/query-hosted-service.mdx index 731e3a3120b2..cdb6bf9f8135 100644 --- a/pages/es/hosted-service/query-hosted-service.mdx +++ b/pages/es/hosted-service/query-hosted-service.mdx @@ -1,14 +1,14 @@ --- -title: Query the Hosted Service +title: Consultas en el Sistema Alojado --- -With the subgraph deployed, visit the [Hosted Service](https://thegraph.com/hosted-service/) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. +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. -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +A continuación se proporciona un ejemplo, pero por favor, consulta la [Query API](/developer/graphql-api) para obtener una referencia completa sobre cómo consultar las entidades del subgrafo. -#### Example +#### Ejemplo -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +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`: ```graphql { @@ -19,10 +19,10 @@ This query lists all the counters our mapping has created. Since we only create } ``` -## Using The Hosted Service +## Utilización del Servicio Alojado -The Graph Explorer and its GraphQL playground is a useful way to explore and query deployed subgraphs on the Hosted Service. +The Graph Explorer y su playground GraphQL es una forma útil de explorar y consultar los subgrafos desplegados en el Servicio Alojado. -Some of the main features are detailed below: +A continuación se detallan algunas de las principales características: -![Explorer Playground](/img/explorer-playground.png) +![Explora el Playground](/img/explorer-playground.png) diff --git a/pages/es/hosted-service/what-is-hosted-service.mdx b/pages/es/hosted-service/what-is-hosted-service.mdx index 7f604c8dc31a..03b41d6578b5 100644 --- a/pages/es/hosted-service/what-is-hosted-service.mdx +++ b/pages/es/hosted-service/what-is-hosted-service.mdx @@ -1,20 +1,20 @@ --- -title: What is the Hosted Service? +title: '¿Qué es el Servicio Alojado?' --- -This section will walk you through deploying a subgraph to the Hosted Service, otherwise known as the [Hosted Service.](https://thegraph.com/hosted-service/) As a reminder, the Hosted Service will not be shut down soon. We will gradually sunset the Hosted Service once we reach feature parity with the decentralized network. Your subgraphs deployed on the Hosted Service are still available [here.](https://thegraph.com/hosted-service/) +Esta sección te guiará a través del despliegue de un subgrafo en el Servicio Alojado, también conocido como [Servicio Alojado.](https://thegraph.com/hosted-service/) Como recordatorio, el Servicio Alojado no se cerrará pronto. El Servicio Alojado desaparecerá gradualmente cuando alcancemos la paridad de características con la red descentralizada. Tus subgrafos desplegados en el Servicio Alojado siguen disponibles [aquí.](https://thegraph.com/hosted-service/) -If you don't have an account on the Hosted Service, you can signup with your Github account. Once you authenticate, you can start creating subgraphs through the UI and deploying them from your terminal. Graph Node supports a number of Ethereum testnets (Rinkeby, Ropsten, Kovan) in addition to mainnet. +Si no tienes una cuenta en el Servicio Alojado, puedes registrarte con tu cuenta de Github. Una vez que te autentiques, puedes empezar a crear subgrafos a través de la interfaz de usuario y desplegarlos desde tu terminal. Graph Node admite varias redes de prueba de Ethereum (Rinkeby, Ropsten, Kovan) además de la red principal. -## Create a Subgraph +## Crear un Subgrafo -First follow the instructions [here](/developer/define-subgraph-hosted) to install the Graph CLI. Create a subgraph by passing in `graph init --product hosted service` +Primero sigue las instrucciones [aquí](/developer/define-subgraph-hosted) para instalar the Graph CLI. Crea un subgrafo pasando `graph init --product hosted service` -### From an Existing Contract +### De un Contrato Existente -If you already have a smart contract deployed to Ethereum mainnet or one of the testnets, bootstrapping a new subgraph from this contract can be a good way to get started on the Hosted Service. +Si ya tienes un contrato inteligente desplegado en la red principal de Ethereum o en una de las redes de prueba, el arranque de un nuevo subgrafo a partir de este contrato puede ser una buena manera de empezar a utilizar el Servicio Alojado. -You can use this command to create a subgraph that indexes all events from an existing contract. This will attempt to fetch the contract ABI from [Etherscan](https://etherscan.io/). +Puedes utilizar este comando para crear un subgrafo que indexe todos los eventos de un contrato existente. Esto intentará obtener el contrato ABI de [Etherscan](https://etherscan.io/). ```sh graph init \ @@ -23,28 +23,28 @@ graph init \ / [] ``` -Additionally, you can use the following optional arguments. If the ABI cannot be fetched from Etherscan, it falls back to requesting a local file path. If any optional arguments are missing from the command, it takes you through an interactive form. +Además, puedes utilizar los siguientes argumentos opcionales. Si la ABI no puede ser obtenida de Etherscan, vuelve a solicitar una ruta de archivo local. Si falta algún argumento opcional en el comando, éste te lleva a través de un formulario interactivo. ```sh --network \ --abi \ ``` -The `` in this case is your github user or organization name, `` is the name for your subgraph, and `` is the optional name of the directory where graph init will put the example subgraph manifest. The `` is the address of your existing contract. `` is the name of the Ethereum network that the contract lives on. `` is a local path to a contract ABI file. **Both --network and --abi are optional.** +El ``en este caso es tu nombre de usuario u organización de github, `` es el nombre para tu subgrafo, y `` es el nombre opcional del directorio donde graph init pondrá el manifiesto del subgrafo de ejemplo. El `` es la dirección de tu contrato existente. `` es el nombre de la red Ethereum en la que está activo el contrato. `` es una ruta local a un archivo ABI del contrato. **Tanto --network como --abi son opcionales** -### From an Example Subgraph +### De un Subgrafo de Ejemplo -The second mode `graph init` supports is creating a new project from an example subgraph. The following command does this: +El segundo modo que admite `graph init` es la creación de un nuevo proyecto a partir de un subgrafo de ejemplo. El siguiente comando lo hace: ``` graph init --from-example --product hosted-service / [] ``` -The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. Continue on to the [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) to better understand which events from your smart contracts to pay attention to, mappings, and more. +El subgrafo de ejemplo se basa en el contrato Gravity de Dani Grant que gestiona los avatares de los usuarios y emite `NewGravatar` o `UpdateGravatar` cada vez que se crean o actualizan los avatares. El subgrafo maneja estos eventos escribiendo entidades `Gravatar` en el almacén de the Graph Node y asegurándose de que éstas se actualicen según los eventos. Continúa con el [manifiesto del subgrafo](/developer/create-subgraph-hosted#the-subgraph-manifest) para entender mejor a qué eventos de tus contratos inteligentes hay que prestar atención, los mapeos y mucho más. -## Supported Networks on the Hosted Service +## Redes Admitidas en el Servicio Alojado -Please note that the following networks are supported on the Hosted Service. Networks outside of Ethereum mainnet ('mainnet') are not currently supported on [The Graph Explorer.](https://thegraph.com/explorer) +Ten en cuenta que las siguientes redes son admitidas en el Servicio Alojado. Las redes fuera de la red principal de Ethereum ('mainnet') no son actualmente admitidas en [The Graph Explorer.](https://thegraph.com/explorer) - `mainnet` - `kovan` diff --git a/pages/es/indexing.mdx b/pages/es/indexing.mdx index 241841b2e01a..460c64005f05 100644 --- a/pages/es/indexing.mdx +++ b/pages/es/indexing.mdx @@ -60,18 +60,18 @@ query indexerAllocations { } ``` -Use Etherscan to call `getRewards()`: +Utiliza Etherscan para solicitar el `getRewards()`: -- Navega a [la interfase de Etherscan para ver el Rewards contract](https://etherscan.io/address/0x9Ac758AB77733b4150A901ebd659cbF8cB93ED66#readProxyContract) +- Navega a través de [la interfaz de Etherscan para ver el contrato de recompensas](https://etherscan.io/address/0x9Ac758AB77733b4150A901ebd659cbF8cB93ED66#readProxyContract) * Para llamar `getRewards()`: - - Expande el **10. getRewards** dropdown. + - Eleva el **10. getRewards** dropdown. - Introduce el **allocationID** en la entrada. - - Presiona el **Query** boton. + - Presiona el botón de **Query**. ### ¿Qué son las disputas y dónde puedo verlas? -Las consultas y asignaciones del Indexador se pueden disputar en The Graph durante el período de disputa. El período de disputa varía según el tipo de disputa. Las consultas / atestaciones tienen una ventana de disputa de 7 ciclos, mientras que las asignaciones tienen 56 ciclos. Una vez transcurridos estos períodos, no se pueden abrir disputas contra asignaciones o consultas. Cuando se abre una disputa, los Fishermen requieren un depósito de un mínimo de 10,000 GRT, que permanecerá bloqueado hasta que finalice la disputa y se haya dado una resolución. Los Fishermen (o pescadores) son todos los participantes de la red que abren disputas. +Las consultas y asignaciones del Indexador se pueden disputar en The Graph durante el período de disputa. El período de disputa varía según el tipo de disputa. Las consultas tienen una ventana de disputa de 7 ciclos, mientras que las asignaciones tienen 56 ciclos. Una vez transcurridos estos períodos, no se pueden abrir disputas contra asignaciones o consultas. Cuando se abre una disputa, los Fishermen requieren un depósito mínimo de 10,000 GRT, que permanecerá bloqueado hasta que finalice la disputa y se haya dado una resolución. Los Fishermen (o pescadores) son todos los participantes de la red que abren disputas. Las disputas se pueden ver en la interfaz de usuario, en la página de perfil de un Indexador, en la pestaña `Disputas`. @@ -79,7 +79,7 @@ Las disputas se pueden ver en la interfaz de usuario, en la página de perfil de - Si la disputa se resuelve como empate, se devolverá el depósito de los Fishermen y no se recortará al indexador en disputa. - Si la disputa es aceptada, los GRT depositados por los Fishermen será devuelto, el Indexador en disputa será recortado y los Fishermen ganarán el 50% de los GRT recortados. -Disputes can be viewed in the UI in an Indexer's profile page under the `Disputes` tab. +Las disputas se podran visualizar en la interfaz correspondiente al perfil del indexador en la pestaña de `disputas`. ### ¿Qué son los reembolsos de tarifas de consulta y cuándo se distribuyen? @@ -114,12 +114,12 @@ Los indexadores pueden diferenciarse aplicando técnicas avanzadas para tomar de - **Medio**: Indexador de producción que admite 100 subgrafos y 200-500 solicitudes por segundo. - **Grande**: Preparado para indexar todos los subgrafos utilizados actualmente y atender solicitudes para el tráfico relacionado. -| Configuración | (CPUs) | (memoria en GB) | (disco en TB) | (CPUs) | (memoria en GB) | -| ------------- | :----: | :-------------: | :-----------: | :----: | :-------------: | -| Pequeño | 4 | 8 | 1 | 4 | 16 | -| Estándar | 8 | 30 | 1 | 12 | 48 | -| Medio | 16 | 64 | 2 | 32 | 64 | -| Grande | 72 | 468 | 3,5 | 48 | 184 | +| Configuración | Postgres
(CPUs) | Postgres
(memory in GBs) | Postgres
(disk in TBs) | VMs
(CPUs) | VMs
(memory in GBs) | +| ------------- |:--------------------------:|:-----------------------------------:|:---------------------------------:|:---------------------:|:------------------------------:| +| Pequeño | 4 | 8 | 1 | 4 | 16 | +| Estándar | 8 | 30 | 1 | 12 | 48 | +| Medio | 16 | 64 | 2 | 32 | 64 | +| Grande | 72 | 468 | 3,5 | 48 | 184 | ### ¿Cuáles son algunas de las precauciones de seguridad básicas que debe tomar un indexador? @@ -131,13 +131,13 @@ Los indexadores pueden diferenciarse aplicando técnicas avanzadas para tomar de En el centro de la infraestructura de un indexador está el Graph Node que monitorea Ethereum, extrae y carga datos según una definición de subgrafo y lo sirve como una [GraphQL API](/about/introduction#how-the-graph-works). El Graph Node debe estar conectado a los puntos finales del nodo Ethereum EVM y al nodo IPFS para obtener datos; una base de datos PostgreSQL para su tienda; y componentes del indexador que facilitan sus interacciones con la red. -- **Base de datos PostgreSQLPostgreSQL**: El almacén principal para Graph Node, aquí es donde se almacenan los datos del subgrafo. El servicio y el agente del indexador también utilizan la base de datos para almacenar datos del canal de estado, modelos de costos y reglas de indexación. +- **Base de datos PostgreSQL**: El almacén principal para Graph Node, aquí es donde se almacenan los datos del subgrafo. El servicio y el agente del indexador también utilizan la base de datos para almacenar datos del canal de estado, modelos de costos y reglas de indexación. -- **Punto final de Ethereum**: Un punto final que expone una API Ethereum JSON-RPC. Esto puede tomar la forma de un solo cliente Ethereum o podría ser una configuración más compleja que equilibre la carga en varios. Es importante tener en cuenta que ciertos subgrafos requerirán capacidades particulares del cliente Ethereum, como el modo de archivo y la API de seguimiento. +- **Endpoint de Ethereum**: Un punto final que expone una API Ethereum JSON-RPC. Esto puede tomar la forma de un solo cliente Ethereum o podría ser una configuración más compleja que equilibre la carga en varios. Es importante tener en cuenta que ciertos subgrafos requerirán capacidades particulares del cliente Ethereum, como el modo de archivo y la API de seguimiento. -- ** Nodo IPFS (versión inferior a 5)**: Los metadatos de implementación de Subgrafo se almacenan en la red IPFS. El Graph Node accede principalmente al nodo IPFS durante la implementación del subgrafo para obtener el manifiesto del subgrafo y todos los archivos vinculados. Los indexadores de la red no necesitan alojar su propio nodo IPFS, un nodo IPFS para la red está alojado en https://ipfs.network.thegraph.com. +- ***Nodo IPFS (versión inferior a 5)**: Los metadatos de implementación de Subgrafo se almacenan en la red IPFS. El Graph Node accede principalmente al nodo IPFS durante la implementación del subgrafo para obtener el manifiesto del subgrafo y todos los archivos vinculados. Los indexadores de la red no necesitan alojar su propio nodo IPFS, un nodo IPFS para la red está alojado en https://ipfs.network.thegraph.com. -- ** Servicio de indexador**: Gestiona todas las comunicaciones externas necesarias con la red. Comparte modelos de costos y estados de indexación, transfiere solicitudes de consulta desde la puerta de acceso (gateway) a Graph Node y administra los pagos de consultas a través de canales de estado con la puerta de acceso. +- **Servicio de indexador**: Gestiona todas las comunicaciones externas necesarias con la red. Comparte modelos de costos y estados de indexación, transfiere solicitudes de consulta desde la puerta de acceso (gateway) a Graph Node y administra los pagos de consultas a través de canales de estado con la puerta de acceso. - **Agente indexador**: Facilita las interacciones de los indexadores en cadena, incluido el registro en la red, la gestión de implementaciones de subgrafos en sus Graph Node y la gestión de asignaciones. Servidor de métricas de Prometheus: los componentes Graph Node y el Indexer registran sus métricas en el servidor de métricas. @@ -149,24 +149,24 @@ Nota: Para admitir el escalado ágil, se recomienda que las inquietudes de consu #### Graph Node -| Puerto | Objeto | Rutas | Argumento CLI | Variable de Entorno | -| --- | --- | --- | --- | --- | -| 8000 | Servidor HTTP GraphQL
(para consultas de subgrafos) | /subgraphs/id/...

/subgraphs/name/.../... | --http-port | - | -| 8001 | GraphQL WS
(para suscripciones a subgrafos) | /subgraphs/id/...

/subgraphs/name/.../... | --ws-port | - | -| 8020 | JSON-RPC
(para administrar implementaciones) | / | --admin-port | - | -| 8030 | API de estado de indexación de subgrafos | /graphql | --index-node-port | - | -| 8040 | Métricas de Prometheus | /metrics | --metrics-port | - | +| Puerto | Objeto | Rutas | Argumento CLI | Variable de Entorno | +| ------ | ---------------------------------------------------------------- | ---------------------------------------------------- | ----------------- | ------------------- | +| 8000 | Servidor HTTP GraphQL
(para consultas de subgrafos) | /subgraphs/id/...
/subgraphs/name/.../... | --http-port | - | +| 8001 | GraphQL WS
(para suscripciones a subgrafos) | /subgraphs/id/...
/subgraphs/name/.../... | --ws-port | - | +| 8020 | JSON-RPC
(para administrar implementaciones) | / | --admin-port | - | +| 8030 | API de estado de indexación de subgrafos | /graphql | --index-node-port | - | +| 8040 | Métricas de Prometheus | /metrics | --metrics-port | - | #### Servicio de Indexador -| Puerto | Objeto | Rutas | Argumento CLI | Variable de Entorno | -| --- | --- | --- | --- | --- | -| 7600 | Servidor HTTP GraphQL
(para consultas de subgrafo pagadas) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | -| 7300 | Métricas de Prometheus | /metrics | --metrics-port | - | +| Puerto | Objeto | Rutas | Argumento CLI | Variable de Entorno | +| ------ | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | -------------- | ---------------------- | +| 7600 | Servidor HTTP GraphQL
(para consultas de subgrafo pagadas) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | +| 7300 | Métricas de Prometheus | /metrics | --metrics-port | - | #### Agente Indexador -| Puerto | Objeto | Rutas | Argumento CLI | Variable de
Entorno | +| Puerto | Objeto | Rutas | Argumento CLI | Variable de
Entorno | | ------ | ----------------------------- | ----- | ------------------------- | --------------------------------------- | | 8000 | API de gestión de indexadores | / | --indexer-management-port | `INDEXER_AGENT_INDEXER_MANAGEMENT_PORT` | @@ -243,7 +243,8 @@ gcloud compute addresses create google-managed-services-default \ --purpose=VPC_PEERING \ --network default \ --global \ - --description 'IP Range for peer networks.' gcloud services vpc-peerings connect \ + --description 'IP Range for peer networks.' +gcloud services vpc-peerings connect \ --network=default \ --ranges=google-managed-services-default ``` @@ -290,7 +291,7 @@ kubectl config use-context $(kubectl config get-contexts --output='name' - Lee todos los archivos en `$dir` y ajusta cualquier valor como se indica en los comentarios. -Deploy all resources with `kubectl apply -k $dir`. +Despliega todas las fuentes usando `kubectl apply -k $dir`. ### Graph Node @@ -306,7 +307,7 @@ Deploy all resources with `kubectl apply -k $dir`. - **IPFS** -- ** Requisitos adicionales para usuarios de Ubuntu**: Para ejecutar un nodo Graph en Ubuntu, es posible que se necesiten algunos paquetes adicionales. +- **Requisitos adicionales para usuarios de Ubuntu**: Para ejecutar un nodo Graph en Ubuntu, es posible que se necesiten algunos paquetes adicionales. ```sh sudo apt-get install -y clang libpg-dev libssl-dev pkg-config @@ -372,9 +373,9 @@ Para participar con éxito en la red se requiere una supervisión e interacción #### Comenzar -El agente indexador y el servicio indexador deben ubicarse junto con su infraestructura Graph Node. Hay muchas formas de configurar entornos de ejecución virtual para tus componentes de indexador; aquí explicaremos cómo ejecutarlos en baremetal utilizando paquetes o fuente NPM, o mediante kubernetes y docker en Google Cloud Kubernetes Engine. Si estos ejemplos de configuración no se traducen bien en tu infraestructura, es probable que haya una guía de la comunidad de referencia, ¡ven a saludar en [Discord](https://thegraph.com/discord)! Recuerda [stake en el protocolo](/indexing#stake-in-the-protocol) antes de iniciar tus componentes de indexador! Remember to [stake in the protocol](/indexing#stake-in-the-protocol) before starting up your indexer components! +El agente indexador y el servicio indexador deben ubicarse junto con su infraestructura Graph Node. Hay muchas formas de configurar entornos de ejecución virtual para tus componentes de indexador; aquí explicaremos cómo ejecutarlos en baremetal utilizando paquetes o fuente NPM, o mediante kubernetes y docker en Google Cloud Kubernetes Engine. Si estos ejemplos de configuración no se traducen bien en tu infraestructura, es probable que haya una guía de la comunidad de referencia, ¡ven a saludar en [Discord](https://thegraph.com/discord)! Recuerda [stake en el protocolo](/indexing#stake-in-the-protocol) antes de iniciar tus componentes de indexador! ¡Recuerda hacer [staking en el protocolo](/indexing#stake-in-the-protocol) antes de establecer tus componentes como indexer! -#### De paquetes de NPM +#### Paquetes de NPM ```sh npm install -g @graphprotocol/indexer-service @@ -397,7 +398,7 @@ graph indexer connect http://localhost:18000/ graph indexer ... ``` -#### De Origen +#### Fuente ```sh # From Repo root directory @@ -405,7 +406,7 @@ yarn # Indexer Service cd packages/indexer-service -./bin/graph-indexer-service start... +./bin/graph-indexer-service start ... # Indexer agent cd packages/indexer-agent @@ -514,7 +515,7 @@ graph-indexer-service start \ #### Indexer CLI -The Indexer CLI is a plugin for [`@graphprotocol/graph-cli`](https://www.npmjs.com/package/@graphprotocol/graph-cli) accessible in the terminal at `graph indexer`. +Indexer CLI es un complemento para [`@graphprotocol/graph-cli`](https://www.npmjs.com/package/@graphprotocol/graph-cli) accesible en la terminal de `graph indexer`. ```sh graph indexer connect http://localhost:18000 @@ -523,7 +524,7 @@ graph indexer status #### Gestión del indexador mediante Indexer CLI -El agente indexador necesita información de un indexador para interactuar de forma autónoma con la red en nombre del indexador. El mecanismo para definir el comportamiento del agente indexador son las **reglas de indexación**. Con las **reglas de indexación**, un indexador puede aplicar su estrategia específica para seleccionar subgrafos para indexar y atender consultas. Las reglas se administran a través de una API GraphQL proporcionada por el agente y conocida como API de administración de indexadores (Indexer Management API). La herramienta sugerida para interactuar con la ** API de Administración del Indexador** es la ** Indexer CLI**, una extensión de **Graph CLI**. +El agente indexador necesita información de un indexador para interactuar de forma autónoma con la red en nombre del indexador. El mecanismo para definir el comportamiento del agente indexador son las **reglas de indexación**. Con las **reglas de indexación**, un indexador puede aplicar su estrategia específica para seleccionar subgrafos para indexar y atender consultas. Las reglas se administran a través de una API GraphQL proporcionada por el agente y conocida como API de administración de indexadores (Indexer Management API). La herramienta sugerida para interactuar con la **API de Administración del Indexador** es la **Indexer CLI**, una extensión de **Graph CLI**. #### Uso @@ -531,7 +532,7 @@ La **CLI del Indexador** se conecta al agente del indexador, normalmente a trav - `graph indexer connect ` - Conéctate a la API de administración del indexador. Normalmente, la conexión al servidor se abre mediante el reenvío de puertos, por lo que la CLI se puede operar fácilmente de forma remota. (Ejemplo: `kubectl port-forward pod/ 8000:8000`) -- `graph indexer rules get [options] ...]` - Obtén una o más reglas de indexación usando `all` como `& lt;deployment-id>` para obtener todas las reglas, o `global` para obtener los valores globales predeterminados. Se puede usar un argumento adicional `--merged` para especificar que las reglas específicas de implementación se fusionan con la regla global. Así es como se aplican en el agente indexador. +- `graph indexer rules get [options] ...]` - Obtén una o más reglas de indexación usando `all` `` para obtener todas las reglas, o `global` para obtener los valores globales predeterminados. Se puede usar un argumento adicional `--merged` para especificar que las reglas específicas de implementación se fusionan con la regla global. Así es como se aplican en el agente indexador. - `graph indexer rules set [options] ...` - Establece una o más reglas de indexación. @@ -547,7 +548,7 @@ Todos los comandos que muestran reglas en la salida pueden elegir entre los form Las reglas de indexación se pueden aplicar como valores predeterminados globales o para implementaciones de subgrafos específicos usando sus ID. Los campos `deployment` y `decisionBasis` son obligatorios, mientras que todos los demás campos son opcionales. Cuando una regla de indexación tiene `rules` como `decisionBasis`, el agente indexador comparará los valores de umbral no nulos en esa regla con los valores obtenidos de la red para la implementación correspondiente. Si la implementación del subgrafo tiene valores por encima (o por debajo) de cualquiera de los umbrales, se elegirá para la indexación. -Por ejemplo, si la regla global tiene un `minStake` de ** 5 ** (GRT), cualquier implementación de subgrafo que tenga más de 5 (GRT) de participación (stake) asignado a él será indexado. Las reglas de umbral incluyen `maxAllocationPercentage`, `minSignal`, `maxSignal`, `minStake` y `minAverageQueryFees`. +Por ejemplo, si la regla global tiene un `minStake` de **5** (GRT), cualquier implementación de subgrafo que tenga más de 5 (GRT) de participación (stake) asignado a él será indexado. Las reglas de umbral incluyen `maxAllocationPercentage`, `minSignal`, `maxSignal`, `minStake` y `minAverageQueryFees`. Modelo de Datos: @@ -658,9 +659,9 @@ setDelegationParameters(950000, 600000, 500) ### La vida de una asignación -After being created by an indexer a healthy allocation goes through four states. +Después de ser creada por un indexador, una asignación saludable pasa por cuatro fases. -- **Activo**: Una vez que se crea una asignación en la cadena (\[allocateFrom()\](https://github.com/graphprotocol/contracts/blob/master/contracts/staking/Staking.sol # L873)) se considera ** activo **. Una parte de la participación propia y/o delegada del indexador se asigna a una implementación de subgrafo, lo que le permite reclamar recompensas de indexación y atender consultas para esa implementación de subgrafo. El agente indexador gestiona la creación de asignaciones basadas en las reglas del indexador. +- **Activo**: Una vez que se crea una asignación en la cadena (\[allocateFrom()\](https://github.com/graphprotocol/contracts/blob/master/contracts/staking/Staking.sol # L873)) se considera **activo**. Una parte de la participación propia y/o delegada del indexador se asigna a una implementación de subgrafo, lo que le permite reclamar recompensas de indexación y atender consultas para esa implementación de subgrafo. El agente indexador gestiona la creación de asignaciones basadas en las reglas del indexador. - **Cerrado**: Un indexador puede cerrar una asignación una vez que haya pasado 1 ciclo ([closeAllocation()](https://github.com/graphprotocol/contracts/blob/master/contracts/staking/Staking.sol#L873)) o su agente indexador cerrará automáticamente la asignación después de **maxAllocationEpochs** (actualmente 28 días). Cuando una asignación se cierra con una prueba válida de indexación (POI), sus recompensas de indexación se distribuyen al indexador y sus delegadores (consulta "¿Cómo se distribuyen las recompensas?" A continuación para obtener más información). diff --git a/pages/es/studio/billing.mdx b/pages/es/studio/billing.mdx index fec638ae5c9f..9a9d4593cced 100644 --- a/pages/es/studio/billing.mdx +++ b/pages/es/studio/billing.mdx @@ -46,7 +46,7 @@ For a quick demo of how billing works on the Subgraph Studio, check out the vide title="Reproductor de video de YouTube" frameBorder="0" allowFullScreen - > +> ### Multisig Users diff --git a/pages/es/studio/deploy-subgraph-studio.mdx b/pages/es/studio/deploy-subgraph-studio.mdx index 2155d8fe8976..72ca3decc35b 100644 --- a/pages/es/studio/deploy-subgraph-studio.mdx +++ b/pages/es/studio/deploy-subgraph-studio.mdx @@ -1,5 +1,5 @@ --- -title: Deploy a Subgraph to the Subgraph Studio +title: Despliegue de un subgrafo en Subgraph Studio --- Deploying a Subgraph to the Subgraph Studio is quite simple. This will take you through the steps to: @@ -13,13 +13,13 @@ Deploying a Subgraph to the Subgraph Studio is quite simple. This will take you We are using the same CLI to deploy subgraphs to our [hosted service](https://thegraph.com/hosted-service/) and to the [Subgraph Studio](https://thegraph.com/studio/). Here are the commands to install graph-cli. This can be done using npm or yarn. -**Install with yarn:** +**Instalar con yarn:** ```bash yarn global add @graphprotocol/graph-cli ``` -**Install with npm:** +**Instalar con npm:** ```bash npm install -g @graphprotocol/graph-cli @@ -29,7 +29,7 @@ npm install -g @graphprotocol/graph-cli Before deploying your actual subgraph you need to create a subgraph in [Subgraph Studio](https://thegraph.com/studio/). We recommend you read our [Studio documentation](/studio/subgraph-studio) to learn more about this. -## Initialize your Subgraph +## Inicializa tu Subgrafo Once your subgraph has been created in Subgraph Studio you can initialize the subgraph code using this command: diff --git a/pages/es/studio/multisig.mdx b/pages/es/studio/multisig.mdx index 164835bdb8a4..7b0f55c22ffb 100644 --- a/pages/es/studio/multisig.mdx +++ b/pages/es/studio/multisig.mdx @@ -4,7 +4,7 @@ title: Using a Multisig Wallet Subgraph Studio currently doesn't support signing with multisig wallets. Until then, you can follow this guide on how to publish your subgraph by invoking the [GNS contract](https://github.com/graphprotocol/contracts/blob/dev/contracts/discovery/GNS.sol) functions. -### Create a Subgraph +### Crear un Subgrafo Similary to using a regular wallet, you can create a subgraph by connecting your non-multisig wallet in Subgraph Studio. Once you connect the wallet, simply create a new subgraph. Make sure you fill out all the details, such as subgraph name, description, image, website, and source code url if applicable. diff --git a/pages/es/studio/studio-faq.mdx b/pages/es/studio/studio-faq.mdx index 4db4d7ccddaa..8ed8de7d106c 100644 --- a/pages/es/studio/studio-faq.mdx +++ b/pages/es/studio/studio-faq.mdx @@ -1,21 +1,21 @@ --- -title: Subgraph Studio FAQs +title: Preguntas Frecuentes sobre Subgraph Studio --- -### 1. How do I create an API Key? +### 1. ¿Cómo puedo crear una clave API? -In the Subgraph Studio, you can create API Keys as needed and add security settings to each of them. +En Subgraph Studio, puedes crear las claves de la API que necesites y añadir configuraciones de seguridad a cada una de ellas. -### 2. Can I create multiple API Keys? +### 2. ¿Puedo crear varias claves API? -A: Yes! You can create multiple API Keys to use in different projects. Check out the link [here](https://thegraph.com/studio/apikeys/). +R: ¡Sí! Puedes crear varias claves API para utilizarlas en diferentes proyectos. Consulta el enlace [aquí](https://thegraph.com/studio/apikeys/). -### 3. How do I restrict a domain for an API Key? +### 3. ¿Cómo puedo restringir un dominio para una clave API? -After creating an API Key, in the Security section you can define the domains that can query a specific API Key. +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. -### 4. How do I find query URLs for subgraphs if I’m not the developer of the subgraph I want to use? +### 4. ¿Cómo puedo encontrar las URL de consulta de los subgrafos si no soy el desarrollador del subgrafo que quiero utilizar? -You can find the query URL of each subgraph in the Subgraph Details section of The Graph Explorer. When you click on the “Query” button, you will be directed to a pane wherein you can view the query URL of the subgraph you’re interested in. You can then replace the `` placeholder with the API key you wish to leverage in the Subgraph Studio. +Puedes encontrar la URL de consulta de cada subgrafo en la sección Detalles del Subgrafo de the Graph Explorer. Al hacer clic en el botón "Query", se te dirigirá a un panel en el que podrás ver la URL de consulta del subgrafo te interesa. A continuación, puedes sustituir el marcador de posición `` por la clave de la API que deseas aprovechar en el Subgraph Studio. -Remember that you can create an API key and query any subgraph published to the network, even if you build a subgraph yourself. These queries via the new API key, are paid queries as any other on the network. +Recuerda que puedes crear una clave API y consultar cualquier subgrafo publicado en la red, incluso si tú mismo construyes un subgrafo. Estas consultas a través de la nueva clave API, son consultas pagas como cualquier otra en la red. diff --git a/pages/es/studio/subgraph-studio.mdx b/pages/es/studio/subgraph-studio.mdx index 36118547baee..28cfadea4edc 100644 --- a/pages/es/studio/subgraph-studio.mdx +++ b/pages/es/studio/subgraph-studio.mdx @@ -36,7 +36,7 @@ The best part! When you first create a subgraph, you’ll be directed to fill ou - Your Subgraph Name - Image -- Description +- Descripción - Categories - Website @@ -73,7 +73,7 @@ You’ve made it this far - congrats! Publishing your subgraph means that an IPF title="Reproductor de video de YouTube" frameBorder="0" allowFullScreen - > +> Remember, while you’re going through your publishing flow, you’ll be able to push to either mainnet or Rinkeby, the testnet we support. If you’re a first time subgraph developer, we highly suggest you start with publishing to Rinkeby, which is free to do. This will allow you to see how the subgraph will work in The Graph Explorer and will allow you to test curation elements. diff --git a/pages/ja/about/introduction.mdx b/pages/ja/about/introduction.mdx index 5f840c040400..2e8e73072b4b 100644 --- a/pages/ja/about/introduction.mdx +++ b/pages/ja/about/introduction.mdx @@ -1,47 +1,47 @@ --- -title: Introduction +title: イントロダクション --- -This page will explain what The Graph is and how you can get started. +このページでは、「The Graph」とは何か、どのようにして始めるのかを説明します。 -## What The Graph Is +## The Graph とは -The Graph is a decentralized protocol for indexing and querying data from blockchains, starting with Ethereum. It makes it possible to query data that is difficult to query directly. +The Graph は、Ethereum をはじめとするブロックチェーンのデータをインデックス化してクエリするための分散型プロトコルです。 これにより、直接クエリすることが困難のデータのクエリが容易に可能になります。 -Projects with complex smart contracts like [Uniswap](https://uniswap.org/) and NFTs initiatives like [Bored Ape Yacht Club](https://boredapeyachtclub.com/) store data on the Ethereum blockchain, making it really difficult to read anything other than basic data directly from the blockchain. +[Uniswap](https://uniswap.org/)のような複雑なスマートコントラクトを持つプロジェクトや、[Bored Ape Yacht Club](https://boredapeyachtclub.com/) のような NFT の取り組みでは、Ethereum のブロックチェーンにデータを保存しているため、基本的なデータ以外をブロックチェーンから直接読み取ることは実に困難です。 -In the case of Bored Ape Yacht Club, we can perform basic read operations on [the contract](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) like getting the owner of a certain Ape, getting the content URI of an Ape based on their ID, or the total supply, as these read operations are programmed directly into the smart contract, but more advanced real-world queries and operations like aggregation, search, relationships, and non-trivial filtering are not possible. For example, if we wanted to query for apes that are owned by a certain address, and filter by one of its characteristics, we would not be able to get that information by interacting directly with the contract itself. +Bored Ape Yacht Club の場合、ある Ape の所有者を取得したり、ID に基づいて Ape のコンテンツ URI を取得したり、総供給量を取得したりといった基本的な読み取り操作は、 [スマートコントラクト](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) に直接プログラムされているので実行できますが、集約、検索、連携、フィルタリングなど、より高度な実世界のクエリや操作はできません。 例えば、あるアドレスが所有している NFT をクエリし、その特徴の 1 つでフィルタリングしたいと思っても、コントラクト自体と直接やりとりしてその情報を得ることはできません。 -To get this data, you would have to process every single [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) event ever emitted, read the metadata from IPFS using the Token ID and IPFS hash, and then aggregate it. Even for these types of relatively simple questions, it would take **hours or even days** for a decentralized application (dapp) running in a browser to get an answer. +このデータを得るためには、これまでに発行されたすべての [`転送`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) イベントを処理し、トークン ID と IPFS ハッシュを使って IPFS からメタデータを読み取り、それを集約する必要があります。 このような比較的簡単な質問であっても、ブラウザ上で動作する分散型アプリケーション(dapp)が回答を得るには**数時間から数日**かかるでしょう。 -You could also build out your own server, process the transactions there, save them to a database, and build an API endpoint on top of it all in order to query the data. However, this option is resource intensive, needs maintenance, presents a single point of failure, and breaks important security properties required for decentralization. +また、独自のサーバーを構築し、そこでトランザクションを処理してデータベースに保存し、その上にデータを照会するための API エンドポイントを構築することもできます。 しかし、この方法はリソースを必要とし、メンテナンスが必要で、単一障害点となり、分散化に必要な重要なセキュリティ特性を壊してしまいます。 -**Indexing blockchain data is really, really hard.** +**ブロックチェーンデータのインデックス作成は非常に困難です。** -Blockchain properties like finality, chain reorganizations, or uncled blocks complicate this process further, and make it not just time consuming but conceptually hard to retrieve correct query results from blockchain data. +フィナリティ、チェーンの再編成、アンクルドブロックなどのブロックチェーンの特性は、このプロセスをさらに複雑にし、ブロックチェーンデータから正しいクエリ結果を取り出すことは、時間がかかるだけでなく、概念的にも困難です。 -The Graph solves this with a decentralized protocol that indexes and enables the performant and efficient querying of blockchain data. These APIs (indexed "subgraphs") can then be queried with a standard GraphQL API. Today, there is a hosted service as well as a decentralized protocol with the same capabilities. Both are backed by the open source implementation of [Graph Node](https://github.com/graphprotocol/graph-node). +The Graph は、ブロックチェーンデータにインデックスを付けて、パフォーマンスの高い効率的なクエリを可能にする分散型プロトコルでこれを解決します。 そして、これらの API(インデックス化された「サブグラフ」)は、標準的な GraphQL API でクエリを行うことができます。 現在、同じ機能を持つホスト型のサービスと、分散型のプロトコルがあります。 どちらも、オープンソースで実装されている [Graph Node](https://github.com/graphprotocol/graph-node).によって支えられています。 -## How The Graph Works +## The Graph の仕組み -The Graph learns what and how to index Ethereum data based on subgraph descriptions, known as the subgraph manifest. The subgraph description defines the smart contracts of interest for a subgraph, the events in those contracts to pay attention to, and how to map event data to data that The Graph will store in its database. +The Graph は、サブグラフマニフェストと呼ばれるサブグラフ記述に基づいて、Ethereum のデータに何をどのようにインデックスするかを学習します。 サブグラフマニフェストは、そのサブグラフで注目すべきスマートコントラクト、注目すべきコントラクト内のイベント、イベントデータと The Graph がデータベースに格納するデータとのマッピング方法などを定義します。 -Once you have written a `subgraph manifest`, you use the Graph CLI to store the definition in IPFS and tell the indexer to start indexing data for that subgraph. +`サブグラフのマニフェスト`を書いたら、グラフの CLI を使ってその定義を IPFS に保存し、インデクサーにそのサブグラフのデータのインデックス作成を開始するように指示します。 -This diagram gives more detail about the flow of data once a subgraph manifest has been deployed, dealing with Ethereum transactions: +この図では、サブグラフ・マニフェストがデプロイされた後のデータの流れについて、Ethereum のトランザクションを扱って詳しく説明しています。 ![](/img/graph-dataflow.png) -The flow follows these steps: +フローは以下のステップに従います。 -1. A decentralized application adds data to Ethereum through a transaction on a smart contract. -2. The smart contract emits one or more events while processing the transaction. -3. Graph Node continually scans Ethereum for new blocks and the data for your subgraph they may contain. -4. Graph Node finds Ethereum events for your subgraph in these blocks and runs the mapping handlers you provided. The mapping is a WASM module that creates or updates the data entities that Graph Node stores in response to Ethereum events. -5. The decentralized application queries the Graph Node for data indexed from the blockchain, using the node's [GraphQL endpoint](https://graphql.org/learn/). The Graph Node in turn translates the GraphQL queries into queries for its underlying data store in order to fetch this data, making use of the store's indexing capabilities. The decentralized application displays this data in a rich UI for end-users, which they use to issue new transactions on Ethereum. The cycle repeats. +1. 分散型アプリケーションは、スマートコントラクトのトランザクションを介して Ethereum にデータを追加します。 +2. スマートコントラクトは、トランザクションの処理中に 1 つまたは複数のイベントを発行します。 +3. Graph Node は、Ethereum の新しいブロックと、それに含まれる自分のサブグラフのデータを継続的にスキャンします。 +4. Graph Node は、これらのブロックの中からあなたのサブグラフの Ethereum イベントを見つけ出し、あなたが提供したマッピングハンドラーを実行します。 マッピングとは、イーサリアムのイベントに対応して Graph Node が保存するデータエンティティを作成または更新する WASM モジュールのことです。 +5. 分散型アプリケーションは、ノードの[GraphQL エンドポイント](https://graphql.org/learn/).を使って、ブロックチェーンからインデックスされたデータを Graph Node にクエリします。 Graph Node は、GraphQL のクエリを、基盤となるデータストアに対するクエリに変換し、ストアのインデックス機能を利用してデータを取得します。 分散型アプリケーションは、このデータをエンドユーザー向けのリッチな UI に表示し、エンドユーザーはこれを使って Ethereum 上で新しいトランザクションを発行します。 このサイクルが繰り返されます。 -## Next Steps +## 次のステップ -In the following sections we will go into more detail on how to define subgraphs, how to deploy them, and how to query data from the indexes that Graph Node builds. +次のセクションでは、サブグラフを定義する方法、サブグラフをデプロイする方法、Graph Node が構築したインデックスからデータをクエリする方法について、さらに詳しく説明します。 -Before you start writing your own subgraph, you might want to have a look at the Graph Explorer and explore some of the subgraphs that have already been deployed. The page for each subgraph contains a playground that lets you query that subgraph's data with GraphQL. +独自のサブグラフを書き始める前に、グラフエクスプローラを見て、既にデプロイされているサブグラフをいくつか見てみるといいでしょう。 各サブグラフのページには、そのサブグラフのデータを GraphQL でクエリするためのプレイグラウンドが用意されています。 diff --git a/pages/ja/about/network.mdx b/pages/ja/about/network.mdx index b19f08d12bc7..83f01727e162 100644 --- a/pages/ja/about/network.mdx +++ b/pages/ja/about/network.mdx @@ -1,15 +1,15 @@ --- -title: Network Overview +title: ネットワークの概要 --- -The Graph Network is a decentralized indexing protocol for organizing blockchain data. Applications use GraphQL to query open APIs called subgraphs, to retrieve data that is indexed on the network. With The Graph, developers can build serverless applications that run entirely on public infrastructure. +グラフネットワークは、ブロックチェーンデータを整理するための分散型インデックスプロトコルです。 アプリケーションはGraphQLを使ってサブグラフと呼ばれるオープンなAPIにクエリし、ネットワーク上にインデックスされているデータを取得します。 The Graphを使うことで、開発者は公共のインフラ上で実行されるサーバーレスアプリケーションを構築することができます。 > GRT Token Address: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) -## Overview +## 概要 -The Graph Network consists of Indexers, Curators and Delegators that provide services to the network, and serve data to Web3 applications. Consumers use the applications and consume the data. +グラフネットワークは、インデクサー、キュレーター、デリゲーターにより構成され、ネットワークにサービスを提供し、Web3アプリケーションにデータを提供します。 消費者は、アプリケーションを利用し、データを消費します。 -![Token Economics](/img/Network-roles@2x.png) +![トークンエコノミクス](/img/Network-roles@2x.png) -To ensure economic security of The Graph Network and the integrity of data being queried, participants stake and use Graph Tokens (GRT). GRT is a work token that is an ERC-20 on the Ethereum blockchain, used to allocate resources in the network. Active Indexers, Curators and Delegators can provide services and earn income from the network, proportional to the amount of work they perform and their GRT stake. +グラフネットワークの経済的な安全性と、クエリデータの完全性を確保するために、参加者はグラフトークン(GRT)をステークします。 GRTは、Ethereumブロックチェーン上でERC-20となっているワークトークンで、ネットワーク内のリソースを割り当てるために使用されます。 アクティブなインデクサー、キュレーター、デリゲーターはサービスを提供し、その作業量とGRTのステークに比例して、ネットワークから収入を得ることができます。 diff --git a/pages/ja/curating.mdx b/pages/ja/curating.mdx index 6b795800339d..d4e44811fbcf 100644 --- a/pages/ja/curating.mdx +++ b/pages/ja/curating.mdx @@ -63,8 +63,8 @@ The Graph の場合は、 [Bancor が実装しているボンディングカー 2. キュレーション料 - キュレーターがサブグラフ上で GRT をシグナルすると、1%のキュレーション税が発生します。 この手数料はバーンされ、残りはボンディングカーブのリザーブサプライに預けられます。 3. キュレーターが GRT を引き出すためにシェアをバーンすると、残りのシェアの GRT 評価額が下がります。 場合によっては、キュレーターが自分のシェアを一度にバーンすることを決めることがあるので注意が必要です。 このような状況は、dapp 開発者がサブグラフのバージョン管理や改良、クエリをやめた場合や、サブグラフが故障した場合によく見られます。 その結果、残ったキュレーターは当初の GRT の何分の一かしか引き出せないかもしれません。 リスクプロファイルの低いネットワークロールについては、\[Delegators\](https://thegraph.com/docs/delegating)を参照してください。 4. サブグラフはバグで失敗することがあります。 失敗したサブグラフは、クエリフィーが発生しません。 結果的に、開発者がバグを修正して新しいバージョンを展開するまで待たなければならなくなります。 - - サブグラフの最新バージョンに加入している場合、シェアはその新バージョンに自動移行します。 This will incur a 0.5% curation tax. - - 特定のサブグラフのバージョンでシグナリングしていて、それが失敗した場合は、手動でキュレーションシャイアをバーンする必要があります。 キュレーション・カーブに最初に預けた金額よりも多く、または少なく GRT を受け取る可能性があることに注意してください。 これはキュレーターとしてのリスクです。 You can then signal on the new subgraph version, thus incurring a 1% curation tax. + - サブグラフの最新バージョンに加入している場合、シェアはその新バージョンに自動移行します。 これには0.5%のキュレーション税がかかります。 + - 特定のサブグラフのバージョンでシグナリングしていて、それが失敗した場合は、手動でキュレーションシャイアをバーンする必要があります。 キュレーション・カーブに最初に預けた金額よりも多く、または少なく GRT を受け取る可能性があることに注意してください。 これはキュレーターとしてのリスクです。 そして、新しいサブグラフのバージョンにシグナルを送ることができ、1%のキュレーション税が発生します。 ## キューレーション FAQ @@ -81,7 +81,7 @@ The Graph の場合は、 [Bancor が実装しているボンディングカー ### 3. サブグラフのアップグレードにかかるコストは? -Migrating your curation shares to a new subgraph version incurs a curation tax of 1%. Curators can choose to subscribe to the newest version of a subgraph. When curator shares get auto-migrated to a new version, Curators will also pay half curation tax, ie. 0.5%, because upgrading subgraphs is an on-chain action which costs gas. +キュレーション株式を新しいサブグラフのバージョンに移行すると、1%のキュレーション税が発生します。 キュレーターは、サブグラフの最新バージョンへの登録を選択することができます。 キュレーターのシェアが新しいバージョンに自動移行されると、キュレーターはキュレーション税の半分、つまり0.5%を支払うことになります。これは、サブグラフのアップグレードがガスを消費するオンチェーンアクションであるためです。 ### 4. どのくらいの頻度でサブグラフをアップグレードできますか? @@ -91,7 +91,7 @@ Migrating your curation shares to a new subgraph version incurs a curation tax o キュレーションシェアは、他の ERC20 トークンのように「買う」ことも「売る」こともできません。 キュレーションシェアは、特定のサブグラフのボンディングカーブに沿って、ミント(作成)またはバーン(破棄)することしかできません。 新しいシグナルをミントするのに必要な GRT の量と、既存のシグナルをバーンしたときに受け取る GRT の量は、そのボンディングカーブによって決まります。 キュレーターとしては、GRT を引き出すためにキュレーションシェアをバーンすると、最初に預けた GRT よりも多くの GRT を手にすることもあれば、少なくなることもあることを把握しておく必要があります。 -Still confused? その他の不明点に関しては、 以下のキュレーションビデオガイドをご覧ください: +まだ不明点がありますか? その他の不明点に関しては、 以下のキュレーションビデオガイドをご覧ください:
+>
diff --git a/pages/ja/delegating.mdx b/pages/ja/delegating.mdx index a9facfe51595..06c1297a5a4a 100644 --- a/pages/ja/delegating.mdx +++ b/pages/ja/delegating.mdx @@ -2,11 +2,11 @@ title: デリゲーティング --- -Delegators cannot be slashed for bad behavior, but there is a deposit tax on Delegators to disincentivize poor decision making that could harm the integrity of the network. +デリゲーターは悪意の行動をしてもスラッシュされないが、デリゲーターにはデポジット税が課せられ、ネットワークの整合性を損なう可能性のある悪い意思決定を抑止します。 ## デリゲーターガイド -This guide will explain how to be an effective delegator in the Graph Network. Delegators share earnings of the protocol alongside all indexers on their delegated stake. A Delegator must use their best judgement to choose Indexers based on multiple factors. Please note this guide will not go over steps such as setting up Metamask properly, as that information is widely available on the internet. There are three sections in this guide: +このガイドでは、グラフネットワークで効果的なデリゲーターになるための方法を説明します。 デリゲーターは、デリゲートされたステークのすべてのインデクサーとともにプロトコルの収益を共有します。 デリゲーターは、複数の要素を考慮した上で、最善の判断でインデクサーを選ばなければなりません。 このガイドでは、メタマスクの適切な設定方法などについては説明しません。このガイドには3つのセクションがあります。 There are three sections in this guide: - グラフネットワークでトークンをデリゲートすることのリスク - デリゲーターとしての期待リターンの計算方法 @@ -39,8 +39,8 @@ This guide will explain how to be an effective delegator in the Graph Network. D インデキシング報酬カット - インデキシング報酬カットは、インデクサーが自分のために保持する報酬の部分です。 つまり、これが 100%に設定されていると、デリゲーターであるあなたは 0 のインデキシング報酬を得ることになります。 UI に 80%と表示されている場合は、デリゲーターとして 20%を受け取ることになります。 重要な注意点として、ネットワークの初期段階では、インデキシング報酬が報酬の大半を占めます。
- トップのインデクサーは、デリゲーターに90%の報酬を与えています。 The middle one is giving delegators 20%. The bottom - one is giving delegators ~83%.* + トップのインデクサーは、デリゲーターに90%の報酬を与えています。 The + middle one is giving delegators 20%. The bottom one is giving delegators ~83%.*
- クエリーフィーカット - これはインデキシングリワードカットと全く同じ働きをします。 しかし、これは特に、インデクサーが収集したクエリフィーに対するリターンを対象としています。 ネットワークの初期段階では、クエリフィーからのリターンは、インデキシング報酬に比べて非常に小さいことに注意する必要があります。 ネットワーク内のクエリフィーがいつから大きくなり始めるのかを判断するために、ネットワークに注意を払うことをお勧めします。 @@ -68,7 +68,7 @@ This guide will explain how to be an effective delegator in the Graph Network. D したがって、デリゲーターは計算して、デリゲーターに 20%を提供しているインデクサーの方が、より良いリターンを提供していると判断することができます。 -A delegator can therefore do the math to determine that the Indexer offering 20% to delegators, is offering a better return. +そのため、デリゲーターは、デリゲーターに20%を提供しているインデクサーの方が、より良いリターンを提供していると判断して計算することができます。 ### デリゲーション能力を考慮する @@ -89,5 +89,5 @@ A delegator can therefore do the math to determine that the Indexer offering 20% title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> diff --git a/pages/ja/developer/assemblyscript-api.mdx b/pages/ja/developer/assemblyscript-api.mdx index 2b6aa855c4a3..0069310090ce 100644 --- a/pages/ja/developer/assemblyscript-api.mdx +++ b/pages/ja/developer/assemblyscript-api.mdx @@ -2,75 +2,75 @@ title: AssemblyScript API --- -> Note: if you created a subgraph prior to `graph-cli`/`graph-ts` version `0.22.0`, you're using an older version of AssemblyScript, we recommend taking a look at the [`Migration Guide`](/developer/assemblyscript-migration-guide) +> Note: `graph-cli`/`graph-ts` version `0.22.0`より前にサブグラフを作成した場合、古いバージョンの AssemblyScript を使用しているので、[`Migration Guide`](/developer/assemblyscript-migration-guide)を参照することをお勧めします。 -This page documents what built-in APIs can be used when writing subgraph mappings. Two kinds of APIs are available out of the box: +このページでは、サブグラフのマッピングを記述する際に、どのような組み込み API を使用できるかを説明します。 すぐに使える API は 2 種類あります: -- the [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) and -- code generated from subgraph files by `graph codegen`. +- [Graph TypeScript ライブラリ](https://github.com/graphprotocol/graph-ts) (`graph-ts`)と +- `graph codegen`によってサブグラフファイルから生成されたコードです。 -It is also possible to add other libraries as dependencies, as long as they are compatible with [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Since this is the language mappings are written in, the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) is a good source for language and standard library features. +また、[AssemblyScript](https://github.com/AssemblyScript/assemblyscript)との互換性があれば、他のライブラリを依存関係に追加することも可能です。 マッピングはこの言語で書かれているので、言語や標準ライブラリの機能については、 [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki)が参考になります。 -## Installation +## インストール -Subgraphs created with [`graph init`](/developer/create-subgraph-hosted) come with preconfigured dependencies. All that is required to install these dependencies is to run one of the following commands: +[`graph init`](/developer/create-subgraph-hosted)で作成されたサブグラフには、あらかじめ設定された依存関係があります。 これらの依存関係をインストールするために必要なのは、以下のコマンドのいずれかを実行することです: ```sh yarn install # Yarn -npm install # NPM +npm install # NPM ``` -If the subgraph was created from scratch, one of the following two commands will install the Graph TypeScript library as a dependency: +サブグラフが最初から作成されている場合は、次の 2 つのコマンドのいずれかを実行すると、Graph TypeScript ライブラリが依存関係としてインストールされます: ```sh -yarn add --dev @graphprotocol/graph-ts # Yarn -npm install --save-dev @graphprotocol/graph-ts # NPM +yarn add --dev @graphprotocol/graph-ts # Yarn +npm install -save-dev @graphprotocol/graph-ts # NPM ``` -## API Reference +## API リファレンス -The `@graphprotocol/graph-ts` library provides the following APIs: +`@graphprotocol/graph-ts`ライブラリは、以下の API を提供しています: -- An `ethereum` API for working with Ethereum smart contracts, events, blocks, transactions, and Ethereum values. -- A `store` API to load and save entities from and to the Graph Node store. -- A `log` API to log messages to the Graph Node output and the Graph Explorer. -- An `ipfs` API to load files from IPFS. -- A `json` API to parse JSON data. -- A `crypto` API to use cryptographic functions. -- Low-level primitives to translate between different type systems such as Ethereum, JSON, GraphQL and AssemblyScript. +- Ethereum スマートコントラクト、イベント、ブロック、トランザクション、Ethereum の値を扱うための`ethereum`API +- エンティティをグラフノードのストアからロードしたり、ストアに保存したりする`store`API +- Graph Node の出力や Graph Explorer にメッセージを記録するための`log`API です +- IPFS からファイルをロードする`ipfs`API +- JSON データを解析するための`json`API +- 暗号機能を使用するための`crypto`API +- Ethereum、JSON、GraphQL、AssemblyScript など、異なるタイプのシステム間で変換するための低レベルプリミティブ -### Versions +### バージョン -The `apiVersion` in the subgraph manifest specifies the mapping API version which is run by Graph Node for a given subgraph. The current mapping API version is 0.0.6. +サブグラフマニフェストの`apiVersion` は、指定されたサブグラフに対してグラフノードが実行するマッピング API のバージョンを指定します。 現在のマッピング API のバージョンは 0.0.6 です。 -| Version | Release notes | +| バージョン | リリースノート | | :-: | --- | -| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | -| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | -| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | -| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | -| 0.0.2 | Added `input` field to the Ethereum Transaction object | +| 0.0.6 | Ethereum Transaction オブジェクトに`nonce`フィールドを追加 イーサリアムブロックオブジェクトに
Added `baseFeePerGas`を追加 | +| 0.0.5 | AssemblyScript がバージョン 0.19.10 にアップグレード(変更点がありますので[`Migration Guide`](/developer/assemblyscript-migration-guide))をご覧ください)。
`ethereum.transaction.gasUsed`の名前が`ethereum.transaction.gasLimit`に変更 | +| 0.0.4 | Ethereum SmartContractCall オブジェクトに`functionSignature`フィールドを追加 | +| 0.0.3 | Ethereum Call オブジェクトに`from`フィールドを追加
`etherem.call.address`の名前を `ethereum.call.to`に変更 | +| 0.0.2 | Ethereum Transaction オブジェクトに `input`フィールドを追加 | -### Built-in Types +### 組み込み型 -Documentation on the base types built into AssemblyScript can be found in the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types). +AssemblyScript に組み込まれている基本型のドキュメントは[AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types)にあります。 -The following additional types are provided by `@graphprotocol/graph-ts`. +以下の追加型は`@graphprotocol/graph-ts`で提供されています。 -#### ByteArray +#### バイト配列 ```typescript -import { ByteArray } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から{ ByteArray } をインポートします。 ``` -`ByteArray` represents an array of `u8`. +`ByteArray`は、`u8`の配列を表します。 -_Construction_ +_構造_ - `fromI32(x: i32): ByteArray` - Decomposes `x` into bytes. - `fromHexString(hex: string): ByteArray` - Input length must be even. Prefixing with `0x` is optional. -_Type conversions_ +_型変換_ - `toHexString(): string` - Converts to a hex string prefixed with `0x`. - `toString(): string` - Interprets the bytes as a UTF-8 string. @@ -78,66 +78,66 @@ _Type conversions_ - `toU32(): u32` - Interprets the bytes as a little-endian `u32`. Throws in case of overflow. - `toI32(): i32` - Interprets the byte array as a little-endian `i32`. Throws in case of overflow. -_Operators_ +_オペレーター_ - `equals(y: ByteArray): bool` – can be written as `x == y`. #### BigDecimal ```typescript -import { BigDecimal } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から { BigDecimal } をインポートします。 ``` -`BigDecimal` is used to represent arbitrary precision decimals. +`BigDecimal`は、任意の精度の小数を表現するために使用されます。 -_Construction_ +_構造_ - `constructor(bigInt: BigInt)` – creates a `BigDecimal` from an `BigInt`. - `static fromString(s: string): BigDecimal` – parses from a decimal string. -_Type conversions_ +_型変換_ - `toString(): string` – prints to a decimal string. -_Math_ - -- `plus(y: BigDecimal): BigDecimal` – can be written as `x + y`. -- `minus(y: BigDecimal): BigDecimal` – can be written as `x - y`. -- `times(y: BigDecimal): BigDecimal` – can be written as `x * y`. -- `div(y: BigDecimal): BigDecimal` – can be written as `x / y`. -- `equals(y: BigDecimal): bool` – can be written as `x == y`. -- `notEqual(y: BigDecimal): bool` – can be written as `x != y`. -- `lt(y: BigDecimal): bool` – can be written as `x < y`. -- `le(y: BigDecimal): bool` – can be written as `x <= y`. -- `gt(y: BigDecimal): bool` – can be written as `x > y`. -- `ge(y: BigDecimal): bool` – can be written as `x >= y`. +_数学_ + +- `plus(y: BigDecimal): BigDecimal` – can be written as `x + y` +- `minus(y: BigDecimal): BigDecimal` – can be written as `x - y` +- `times(y: BigDecimal): BigDecimal` – can be written as `x * y` +- `div(y: BigDecimal): BigDecimal` – can be written as `x / y` +- `equals(y: BigDecimal): bool` – can be written as `x == y` +- `notEqual(y: BigDecimal): bool` – can be written as `x != y` +- `lt(y: BigDecimal): bool` – can be written as `x < y` +- `le(y: BigDecimal): bool` – can be written as `x <= y` +- `gt(y: BigDecimal): bool` – can be written as `x > y` +- `ge(y: BigDecimal): bool` – can be written as `x >= y` - `neg(): BigDecimal` - can be written as `-x`. #### BigInt ```typescript -import { BigInt } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から { BigInt } をインポートします。 ``` -`BigInt` is used to represent big integers. This includes Ethereum values of type `uint32` to `uint256` and `int64` to `int256`. Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. +`BigInt`は大きな整数を表すのに使われます。 これには、Ethereum の`uint32`~`uint256` 、`int64` ~`int256`の値が含まれます。 `uint32`、`int32`、`uint24`、`int8`以下のものはすべて`i32`で表されます。 -The `BigInt` class has the following API: +`BigInt`クラスの API は以下の通りです。 -_Construction_ +_構造_ -- `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32`. -- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string. -- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interprets `bytes` as an unsigned, little-endian integer. If your input is big-endian, call `.reverse()` first. +- `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32` +- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string +- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string. If your input is big-endian, call `.reverse()` first. - `BigInt.fromSignedBytes(x: Bytes): BigInt` – Interprets `bytes` as a signed, little-endian integer. If your input is big-endian, call `.reverse()` first. - _Type conversions_ + _型変換_ - `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.toBigDecimal(): BigDecimal` - converts into a decimal with no fractional part. -_Math_ +_数学_ - `x.plus(y: BigInt): BigInt` – can be written as `x + y`. - `x.minus(y: BigInt): BigInt` – can be written as `x - y`. @@ -164,12 +164,12 @@ _Math_ #### TypedMap ```typescript -import { TypedMap } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から { TypedMap } をインポートします。 ``` -`TypedMap` can be used to stored key-value pairs. See [this example](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). +`TypedMap` はキーと値のペアを格納するために使用することができます。 [この例](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51)を参照してください。 -The `TypedMap` class has the following 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` @@ -180,12 +180,12 @@ The `TypedMap` class has the following API: #### Bytes ```typescript -import { Bytes } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から { Bytes } をインポートします。 ``` -`Bytes` is used to represent arbitrary-length arrays of bytes. This includes Ethereum values of type `bytes`, `bytes32` etc. +`Bytes` は、任意の長さの bytes 配列を表すために使用されます。 これには、Ethereum の `bytes`、`bytes32` などの型の値が含まれます。 -The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) and this supports all the `Uint8Array` functionality, plus the following new methods: +`Bytes`クラスは AssemblyScript の[Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64)を継承しており、`Uint8Array` のすべての機能に加えて、以下の新しいメソッドをサポートしています。 - `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 @@ -194,28 +194,28 @@ The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/Assem #### Address ```typescript -import { Address } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から { Address } をインポートします。 ``` -`Address` extends `Bytes` to represent Ethereum `address` values. +`Address`は Ethereum の`address`値を表現するために`Bytes`を拡張しています。 -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 ### Store API ```typescript -import { store } from '@graphprotocol/graph-ts' +'@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`型のサブクラスであるエンティティ・クラスを生成します。 -#### Creating entities +#### エンティティの作成 -The following is a common pattern for creating entities from Ethereum events. +Ethereum のイベントからエンティティを作成する際の一般的なパターンを以下に示します。 ```typescript // Import the Transfer event class generated from the ERC20 ABI @@ -241,13 +241,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 としてエンティティを作成しないことを前提としています。 -#### Loading entities from the store +#### ストアからのエンティティの読み込み -If an entity already exists, it can be loaded from the store with the following: +エンティティがすでに存在する場合、以下の方法でストアからロードすることができます。 ```typescript let id = event.transaction.hash.toHex() // or however the ID is constructed @@ -259,18 +259,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:** Loading entities is only necessary if the changes made in the mapping depend on the previous data of an entity. See the next section for the two ways of updating existing entities. +> **Note:** エンティティのロードは、マッピングでの変更がエンティティの以前のデータに依存する場合にのみ必要です。 既存のエンティティを更新する 2 つの方法については、次のセクションを参照してください。 -#### Updating existing entities +#### 既存のエンティティの更新 -There are two ways to update an existing entity: +既存のエンティティを更新するには 2 つの方法があります。 -1. Load the entity with e.g. `Transfer.load(id)`, set properties on the entity, then `.save()` it back to the store. -2. Simply create the entity with e.g. `new Transfer(id)`, set properties on the entity, then `.save()` it to the store. If the entity already exists, the changes are merged into it. +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) @@ -279,16 +279,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 @@ -302,9 +302,9 @@ entity.numbers = numbers entity.save() ``` -#### Removing entities from the 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`: +現在、生成された型を使ってエンティティを削除する方法はありません。 代わりに、エンティティを削除するには、エンティティタイプの名前とエンティティ ID を`store.remove`に渡す必要があります。 ```typescript import { store } from '@graphprotocol/graph-ts' @@ -315,15 +315,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 データのエンコード/デコードへのアクセスを提供します。 -#### Support for Ethereum Types +#### 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 { @@ -344,9 +344,9 @@ transfer.amount = event.params.amount transfer.save() ``` -#### Events and Block/Transaction Data +#### イベントとブロック/トランザクションデータ -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 { @@ -390,11 +390,11 @@ class Transaction { } ``` -#### Access to Smart Contract State +#### スマートコントラクトの状態へのアクセス -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 @@ -411,13 +411,13 @@ 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. +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. +サブグラフの一部である他のコントラクトは、生成されたコードからインポートすることができ、有効なアドレスにバインドすることができます。 -#### Handling Reverted Calls +#### リバートされた呼び出しの処理 -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) @@ -429,11 +429,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 ノードを使用することをお勧めします。 -#### Encoding/Decoding ABI +#### 符号化/復号化 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' @@ -450,7 +450,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) @@ -459,12 +459,12 @@ For more information: ### Logging API ```typescript -import { log } from '@graphprotocol/graph-ts' +'@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. @@ -472,17 +472,17 @@ 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('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue.toString(), 'already a string']) +log.info('表示されるメッセージ。{}, {}, {}', [value.toString(), anotherValue.toString(), 'すでに文字列']) ``` -#### Logging one or more values +#### 1 つまたは複数の値を記録する -##### Logging a single value +##### 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' @@ -493,9 +493,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -##### Logging a single entry from an existing array +##### 既存の配列から 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'] @@ -506,9 +506,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -#### Logging multiple entries from an existing array +#### 既存の配列から複数のエントリを記録する -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'] @@ -519,9 +519,9 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -##### Logging a specific entry from an existing array +##### 既存の配列から特定のエントリをロギングする -To display a specific value in the array, the indexed value must be provided. +配列内の特定の値を表示するには、インデックス化された値を指定する必要があります。 ```typescript export function handleSomeEvent(event: SomeEvent): void { @@ -530,12 +530,12 @@ export function handleSomeEvent(event: SomeEvent): void { } ``` -##### Logging event information +##### イベント情報の記録 -The example below logs the block number, block hash and transaction hash from an event: +以下の例では、イベントからブロック番号、ブロックハッシュ、トランザクションハッシュをログに記録しています。 ```typescript -import { log } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'から { log } をインポートします。 export function handleSomeEvent(event: SomeEvent): void { log.debug('Block number: {}, block hash: {}, transaction hash: {}', [ @@ -549,12 +549,12 @@ export function handleSomeEvent(event: SomeEvent): void { ### IPFS API ```typescript -import { ipfs } from '@graphprotocol/graph-ts' +'@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 @@ -567,9 +567,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](/developer/create-subgraph-hosted#ipfs-pinning) section for more information. +**注意:** `ipfs.cat` は現時点では決定論的ではありません。 このため、結果に`null`が含まれていないかどうかを常にチェックする必要があります。 リクエストがタイムアウトする前に、Ipfs ネットワーク上でファイルを取得できない場合は、`null`が返されます。 ファイルを確実に取得するためには、グラフノードが接続する IPFS ノードにファイルを固定する必要があります。 [hosted service](https://thegraph.com/hosted-service)では、[https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs)です。 詳細は、[IPFS pinning](/developer/create-subgraph-hosted#ipfs-pinning) のセクションを参照してください。 -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' @@ -599,34 +599,34 @@ 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 ```typescript -import { crypto } from '@graphprotocol/graph-ts' +'@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` ### JSON API ```typescript -import { json, JSONValueKind } from '@graphprotocol/graph-ts' +'@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 - `json.try_fromBytes(data: Bytes): Result` – safe version of `json.fromBytes`, 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: Bytes): Result` – safe version of `json.fromString`, it returns an error variant if the parsing failed -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(...) @@ -635,11 +635,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` @@ -648,7 +648,7 @@ When the type of a value is certain, it can be converted to a [built-in type](#b - `value.toString(): string` - `value.toArray(): Array` - (and then convert `JSONValue` with one of the 5 methods above) -### Type Conversions Reference +### タイプ 変換参照 | Source(s) | Destination | Conversion function | | -------------------- | -------------------- | ---------------------------- | @@ -688,17 +688,17 @@ When the type of a value is certain, it can be converted to a [built-in type](#b | String (hexadecimal) | Bytes | ByteArray.fromHexString(s) | | String (UTF-8) | Bytes | ByteArray.fromUTF8(s) | -### Data Source Metadata +### データソースのメタデータ -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` - `dataSource.context(): DataSourceContext` -### Entity and DataSourceContext +### エンティティと 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` diff --git a/pages/ja/developer/assemblyscript-migration-guide.mdx b/pages/ja/developer/assemblyscript-migration-guide.mdx index c63a1af95d7b..951158bf610b 100644 --- a/pages/ja/developer/assemblyscript-migration-guide.mdx +++ b/pages/ja/developer/assemblyscript-migration-guide.mdx @@ -1,18 +1,18 @@ --- -title: AssemblyScript Migration Guide +title: AssemblyScript マイグレーションガイド --- -Up until now, subgraphs have been using one of the [first versions of AssemblyScript](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). Finally we've added support for the [newest one available](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉 +これまでサブグラフは、[AssemblyScriptの最初のバージョン](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6)を使用していました。 ついに[最新のバージョン](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10)(v0.19.10) のサポートを追加しました! 🎉 -That will enable subgraph developers to use newer features of the AS language and standard library. +これにより、サブグラフの開発者は、AS言語と標準ライブラリの新しい機能を使用できるようになります。 -This guide is applicable for anyone using `graph-cli`/`graph-ts` below version `0.22.0`. If you're already at a higher than (or equal) version to that, you've already been using version `0.19.10` of AssemblyScript 🙂 +このガイドは、バージョン`0.22.0`以下の`graph-cli`/`graph-ts` をお使いの方に適用されます。 もしあなたがすでにそれ以上のバージョンにいるなら、あなたはすでに AssemblyScript のバージョン`0.19.10` を使っています。 -> Note: As of `0.24.0`, `graph-node` can support both versions, depending on the `apiVersion` specified in the subgraph manifest. +> 注:`0.24.0`以降、`graph-node`はサブグラフマニフェストで指定された`apiVersion`に応じて、両方のバージョンをサポートしています。 -## Features +## 特徴 -### New functionality +### 新機能 - `TypedArray`s can now be built from `ArrayBuffer`s by using the [new `wrap` static method](https://www.assemblyscript.org/stdlib/typedarray.html#static-members) ([v0.8.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.8.1)) - New standard library functions: `String#toUpperCase`, `String#toLowerCase`, `String#localeCompare`and `TypedArray#set` ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) @@ -30,21 +30,21 @@ This guide is applicable for anyone using `graph-cli`/`graph-ts` below version ` - Add `toUTCString` for `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) - Add `nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) -### Optimizations +### 最適化 - `Math` functions such as `exp`, `exp2`, `log`, `log2` and `pow` have been replaced by faster variants ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) - Slightly optimize `Math.mod` ([v0.17.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.1)) - Cache more field accesses in std Map and Set ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) - Optimize for powers of two in `ipow32/64` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) -### Other +### その他 - The type of an array literal can now be inferred from its contents ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) - Updated stdlib to Unicode 13.0.0 ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) -## How to upgrade? +## アップグレードの方法 -1. Change your mappings `apiVersion` in `subgraph.yaml` to `0.0.6`: +1. `subgraph.yaml`のマッピングの`apiVersion`を`0.0.6`に変更してください。 ```yaml ... @@ -56,7 +56,7 @@ dataSources: ... ``` -2. Update the `graph-cli` you're using to the `latest` version by running: +2. 使用している`graph-cli`を`最新版`に更新するには、次のように実行します。 ```bash # if you have it globally installed @@ -66,20 +66,20 @@ npm install --global @graphprotocol/graph-cli@latest npm install --save-dev @graphprotocol/graph-cli@latest ``` -3. Do the same for `graph-ts`, but instead of installing globally, save it in your main dependencies: +3. `graph-ts`についても同様ですが、グローバルにインストールするのではなく、メインの依存関係に保存します。 ```bash npm install --save @graphprotocol/graph-ts@latest ``` -4. Follow the rest of the guide to fix the language breaking changes. -5. Run `codegen` and `deploy` again. +4. ガイドの残りの部分に従って、言語の変更を修正します。 +5. `codegen`を実行し、再度`deploy`します。 -## Breaking changes +## 変更点 ### Nullability -On the older version of AssemblyScript, you could create code like this: +古いバージョンのAssemblyScriptでは、以下のようなコードを作ることができました: ```typescript function load(): Value | null { ... } @@ -88,7 +88,7 @@ let maybeValue = load(); maybeValue.aMethod(); ``` -However on the newer version, because the value is nullable, it requires you to check, like this: +しかし、新しいバージョンでは、値がnullableであるため、次のようにチェックする必要があります: ```typescript let maybeValue = load() @@ -98,7 +98,7 @@ if (maybeValue) { } ``` -Or force it like this: +あるいは、次のように強制します: ```typescript let maybeValue = load()! // breaks in runtime if value is null @@ -106,11 +106,11 @@ let maybeValue = load()! // breaks in runtime if value is null maybeValue.aMethod() ``` -If you are unsure which to choose, we recommend always using the safe version. If the value doesn't exist you might want to just do an early if statement with a return in you subgraph handler. +どちらを選択すべきか迷った場合は、常に安全なバージョンを使用することをお勧めします。 値が存在しない場合は、サブグラフハンドラの中でreturnを伴う初期のif文を実行するとよいでしょう。 -### Variable Shadowing +### 変数シャドウイング -Before you could do [variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) and code like this would work: +以前は、[変数のシャドウイング](https://en.wikipedia.org/wiki/Variable_shadowing)を行うことができ、次のようなコードが動作していました。 ```typescript let a = 10 @@ -118,7 +118,7 @@ let b = 20 let a = a + b ``` -However now this isn't possible anymore, and the compiler returns this error: +しかし、現在はこれができなくなり、コンパイラは次のようなエラーを返します。 ```typescript ERROR TS2451: Cannot redeclare block-scoped variable 'a' @@ -127,12 +127,9 @@ ERROR TS2451: Cannot redeclare block-scoped variable 'a' ~~~~~~~~~~~~~ in assembly/index.ts(4,3) ``` - -You'll need to rename your duplicate variables if you had variable shadowing. - -### Null Comparisons - -By doing the upgrade on your subgraph, sometimes you might get errors like these: +変数シャドウイングを行っていた場合は、重複する変数の名前を変更する必要があります。 +### Null比較 +サブグラフのアップグレードを行うと、時々以下のようなエラーが発生することがあります。 ```typescript ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' is not assignable to type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt'. @@ -140,8 +137,7 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i ~~~~ in src/mappings/file.ts(41,21) ``` - -To solve you can simply change the `if` statement to something like this: +解決するには、 `if` 文を以下のように変更するだけです。 ```typescript if (!decimals) { @@ -151,23 +147,23 @@ To solve you can simply change the `if` statement to something like this: if (decimals === null) { ``` -The same applies if you're doing != instead of ==. +これは、==ではなく!=の場合も同様です。 -### Casting +### キャスト -The common way to do casting before was to just use the `as` keyword, like this: +以前の一般的なキャストの方法は、次のように`as`キーワードを使うだけでした。 ```typescript let byteArray = new ByteArray(10) let uint8Array = byteArray as Uint8Array // equivalent to: byteArray ``` -However this only works in two scenarios: +しかし、これは2つのシナリオでしか機能しません。 -- Primitive casting (between types such as `u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); -- Upcasting on class inheritance (subclass → superclass) +- プリミティブなキャスト(between types such as `u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); +- クラス継承のアップキャスティング(サブクラス→スーパークラス) -Examples: +例 ```typescript // primitive casting @@ -183,10 +179,10 @@ class Bytes extends Uint8Array {} let bytes = new Bytes(2) < Uint8Array > bytes // same as: bytes as Uint8Array ``` -There are two scenarios where you may want to cast, but using `as`/`var` **isn't safe**: +キャストしたくても、`as`/`var`を使うと**安全ではない**というシナリオが2つあります。 -- Downcasting on class inheritance (superclass → subclass) -- Between two types that share a superclass +- クラス継承のダウンキャスト(スーパークラス → サブクラス) +- スーパークラスを共有する2つの型の間 ```typescript // downcasting on class inheritance @@ -203,7 +199,7 @@ class ByteArray extends Uint8Array {} let bytes = new Bytes(2) < ByteArray > bytes // breaks in runtime :( ``` -For those cases, you can use the `changetype` function: +このような場合には、`changetype`関数を使用します。 ```typescript // downcasting on class inheritance @@ -222,7 +218,7 @@ let bytes = new Bytes(2) changetype(bytes) // works :) ``` -If you just want to remove nullability, you can keep using the `as` operator (or `variable`), but make sure you know that value can't be null, otherwise it will break. +単にnull性を除去したいだけなら、`as` オペレーター(or `variable`)を使い続けることができますが、値がnullではないことを確認しておかないと壊れてしまいます。 ```typescript // remove nullability @@ -235,18 +231,18 @@ if (previousBalance != null) { let newBalance = new AccountBalance(balanceId) ``` -For the nullability case we recommend taking a look at the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks), it will make your code cleaner 🙂 +Nullabilityについては、[nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks)を利用することをお勧めします。 -Also we've added a few more static methods in some types to ease casting, they are: +また、キャストを容易にするために、いくつかの型にスタティックメソッドを追加しました。 - Bytes.fromByteArray - Bytes.fromUint8Array - BigInt.fromByteArray - ByteArray.fromBigInt -### Nullability check with property access +### プロパティアクセスによるNullabilityチェック -To use the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks) you can use either `if` statements or the ternary operator (`?` and `:`) like this: +[nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks)を使用するには、次のように`if`文や三項演算子(`?` and `:`) を使用します。 ```typescript let something: string | null = 'data' @@ -264,7 +260,7 @@ if (something) { } ``` -However that only works when you're doing the `if` / ternary on a variable, not on a property access, like this: +しかし、これは、以下のように、プロパティのアクセスではなく、変数に対して`if`/ternaryを行っている場合にのみ機能します。 ```typescript class Container { @@ -277,7 +273,7 @@ container.data = 'data' let somethingOrElse: string = container.data ? container.data : 'else' // doesn't compile ``` -Which outputs this error: +すると、このようなエラーが出力されます。 ```typescript ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/string/String'. @@ -285,8 +281,7 @@ ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/s let somethingOrElse: string = container.data ? container.data : "else"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` - -To fix this issue, you can create a variable for that property access so that the compiler can do the nullability check magic: +この問題を解決するには、そのプロパティアクセスのための変数を作成して、コンパイラがnullability checkのマジックを行うようにします。 ```typescript class Container { @@ -301,9 +296,9 @@ let data = container.data let somethingOrElse: string = data ? data : 'else' // compiles just fine :) ``` -### Operator overloading with property access +### プロパティアクセスによるオペレーターオーバーロード -If you try to sum (for example) a nullable type (from a property access) with a non nullable one, the AssemblyScript compiler instead of giving a compile time error warning that one of the values is nullable, it just compiles silently, giving chance for the code to break at runtime. +アセンブリスクリプトのコンパイラは、値の片方がnullableであることを警告するコンパイル時のエラーを出さずに、ただ黙ってコンパイルするので、実行時にコードが壊れる可能性があります。 ```typescript class BigInt extends Uint8Array { @@ -327,7 +322,7 @@ let wrapper = new Wrapper(y) wrapper.n = wrapper.n + x // doesn't give compile time errors as it should ``` -We've opened a issue on the AssemblyScript compiler for this, but for now if you do these kind of operations in your subgraph mappings, you should change them to do a null check before it. +この件に関して、アセンブリ・スクリプト・コンパイラーに問題を提起しましたが、 今のところ、もしサブグラフ・マッピングでこの種の操作を行う場合には、 その前にNULLチェックを行うように変更してください。 ```typescript let wrapper = new Wrapper(y) @@ -339,9 +334,9 @@ if (!wrapper.n) { wrapper.n = wrapper.n + x // now `n` is guaranteed to be a BigInt ``` -### Value initialization +### 値の初期化 -If you have any code like this: +もし、このようなコードがあった場合: ```typescript var value: Type // null @@ -349,7 +344,7 @@ value.x = 10 value.y = 'content' ``` -It will compile but break at runtime, that happens because the value hasn't been initialized, so make sure your subgraph has initialized their values, like this: +これは、値が初期化されていないために起こります。したがって、次のようにサブグラフが値を初期化していることを確認してください。 ```typescript var value = new Type() // initialized @@ -357,7 +352,7 @@ value.x = 10 value.y = 'content' ``` -Also if you have nullable properties in a GraphQL entity, like this: +また、以下のようにGraphQLのエンティティにNullableなプロパティがある場合も同様です。 ```graphql type Total @entity { @@ -366,7 +361,7 @@ type Total @entity { } ``` -And you have code similar to this: +そして、以下のようなコードになります: ```typescript let total = Total.load('latest') @@ -378,7 +373,7 @@ if (total === null) { total.amount = total.amount + BigInt.fromI32(1) ``` -You'll need to make sure to initialize the `total.amount` value, because if you try to access like in the last line for the sum, it will crash. So you either initialize it first: +`total.amount`の値を確実に初期化する必要があります。なぜなら、最後の行のsumのようにアクセスしようとすると、クラッシュしてしまうからです。 そのため、最初に初期化する必要があります。 ```typescript let total = Total.load('latest') @@ -391,7 +386,7 @@ if (total === null) { total.tokens = total.tokens + BigInt.fromI32(1) ``` -Or you can just change your GraphQL schema to not use a nullable type for this property, then we'll initialize it as zero on the `codegen` step 😉 +あるいは、このプロパティに nullable 型を使用しないように GraphQL スキーマを変更することもできます。そうすれば、`コード生成`の段階でゼロとして初期化されます。 ```graphql type Total @entity { @@ -410,9 +405,9 @@ if (total === null) { total.amount = total.amount + BigInt.fromI32(1) ``` -### Class property initialization +### クラスのプロパティの初期化 -If you export any classes with properties that are other classes (declared by you or by the standard library) like this: +以下のように、他のクラス(自分で宣言したものや標準ライブラリで宣言したもの)のプロパティを持つクラスをエクスポートした場合、そのクラスのプロパティを初期化します: ```typescript class Thing {} @@ -422,7 +417,7 @@ export class Something { } ``` -The compiler will error because you either need to add an initializer for the properties that are classes, or add the `!` operator: +コンパイラがエラーになるのは、クラスであるプロパティにイニシャライザを追加するか、`!` オペレーターを追加する必要があるからです。 ```typescript export class Something { @@ -446,11 +441,11 @@ export class Something { } ``` -### GraphQL schema +### GraphQLスキーマ -This is not a direct AssemblyScript change, but you may have to update your `schema.graphql` file. +これはAssemblyScriptの直接的な変更ではありませんが、`schema.graphql`ファイルを更新する必要があるかもしれません。 -Now you no longer can define fields in your types that are Non-Nullable Lists. If you have a schema like this: +タイプの中にNon-Nullable Listのフィールドを定義することができなくなりました。 次のようなスキーマを持っているとします。 ```graphql type Something @entity { @@ -463,7 +458,7 @@ type MyEntity @entity { } ``` -You'll have to add an `!` to the member of the List type, like this: +Listタイプのメンバーには、以下のように`!` を付ける必要があります。 ```graphql type Something @entity { @@ -476,9 +471,9 @@ type MyEntity @entity { } ``` -This changed because of nullability differences between AssemblyScript versions, and it's related to the `src/generated/schema.ts` file (default path, you might have changed this). +これはAssemblyScriptのバージョンによるnullabilityの違いから変更されたもので、`src/generated/schema.ts`ファイル(デフォルトのパス、あなたはこれを変更したかもしれません)に関連しています。 -### Other +### その他 - Aligned `Map#set` and `Set#add` with the spec, returning `this` ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) - Arrays no longer inherit from ArrayBufferView, but are now distinct ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) diff --git a/pages/ja/developer/create-subgraph-hosted.mdx b/pages/ja/developer/create-subgraph-hosted.mdx index 3b05b2548456..6b235e379634 100644 --- a/pages/ja/developer/create-subgraph-hosted.mdx +++ b/pages/ja/developer/create-subgraph-hosted.mdx @@ -218,15 +218,15 @@ Each entity must have an `id` field, which is of type `ID!` (string). The `id` f We support the following scalars in our GraphQL API: -| Type | Description | -| --- | --- | -| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | -| `ID` | Stored as a `string`. | -| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | -| `Boolean` | Scalar for `boolean` values. | -| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | -| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | -| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | +| Type | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | +| `ID` | Stored as a `string`. | +| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | +| `Boolean` | Scalar for `boolean` values. | +| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | +| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | +| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | #### Enums @@ -627,7 +627,7 @@ export function handleNewExchange(event: NewExchange): void { ``` > **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks. -> +> > If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created. ### Data Source Context @@ -684,7 +684,7 @@ dataSources: ``` > **Note:** The contract creation block can be quickly looked up on Etherscan: -> +> > 1. Search for the contract by entering its address in the search bar. > 2. Click on the creation transaction hash in the `Contract Creator` section. > 3. Load the transaction details page where you'll find the start block for that contract. diff --git a/pages/ja/developer/graphql-api.mdx b/pages/ja/developer/graphql-api.mdx index 65928d8734e0..f9cb6214fcd9 100644 --- a/pages/ja/developer/graphql-api.mdx +++ b/pages/ja/developer/graphql-api.mdx @@ -204,12 +204,12 @@ Fulltext search queries have one required field, `text`, for supplying search te Fulltext search operators: -| Symbol | Operator | Description | -| --- | --- | --- | -| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | -| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | -| `<->` | `Follow by` | Specify the distance between two words. | -| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | +| Symbol | Operator | Description | +| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | +| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | +| `<->` | `Follow by` | Specify the distance between two words. | +| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | #### Examples diff --git a/pages/ja/developer/publish-subgraph.mdx b/pages/ja/developer/publish-subgraph.mdx index 2f35f5eb1bae..e2458c5412d8 100644 --- a/pages/ja/developer/publish-subgraph.mdx +++ b/pages/ja/developer/publish-subgraph.mdx @@ -1,27 +1,27 @@ --- -title: Publish a Subgraph to the Decentralized Network +title: 分散型ネットワークへのサブグラフの公開 --- -Once your subgraph has been [deployed to the Subgraph Studio](/studio/deploy-subgraph-studio), you have tested it out, and are ready to put it into production, you can then publish it to the decentralized network. +サブグラフが [Subgraph Studioにデプロイ](/studio/deploy-subgraph-studio)され、それをテストし、本番の準備ができたら、分散型ネットワークにパブリッシュすることができます。 -Publishing a Subgraph to the decentralized network makes it available for [curators](/curating) to begin curating on it, and [indexers](/indexing) to begin indexing it. +サブグラフを分散型ネットワークに公開すると、[キュレーター](/curating)がキュレーションを開始したり、[インデクサー](/indexing)がインデックスを作成したりできるようになります。 -For a walkthrough of how to publish a subgraph to the decentralized network, see [this video](https://youtu.be/HfDgC2oNnwo?t=580). +分散型ネットワークにサブグラフを公開する方法については、[こちらのビデオ](https://youtu.be/HfDgC2oNnwo?t=580)をご覧ください。 -### Networks +### ネットワーク -The decentralized network currently supports both Rinkeby and Ethereum Mainnet. +分散型ネットワークは現在、RinkebyとEthereum Mainnetの両方をサポートしています。 -### Publishing a subgraph +### サブグラフの公開 -Subgraphs can be published to the decentralized network directly from the Subgraph Studio dashboard by clicking on the **Publish** button. Once a subgraph is published, it will be available to view in the [Graph Explorer](https://thegraph.com/explorer/). +サブグラフは、Subgraph Studioのダッシュボードから**Publish** ボタンをクリックすることで、直接分散型ネットワークに公開することができます。 サブグラフが公開されると、[Graph Explorer](https://thegraph.com/explorer/)で閲覧できるようになります。 -- Subgraphs published to Rinkeby can index and query data from either the Rinkeby network or Ethereum Mainnet. +- Rinkebyに公開されたサブグラフは、RinkebyネットワークまたはEthereum Mainnetのいずれかからデータをインデックス化してクエリすることができます。 -- Subgraphs published to Ethereum Mainnet can only index and query data from Ethereum Mainnet, meaning that you cannot publish subgraphs to the main decentralized network that index and query testnet data. +- Ethereum Mainnetに公開されたサブグラフは、Ethereum Mainnetのデータのみをインデックス化してクエリすることができます。つまり、テストネットのデータをインデックス化して照会するサブグラフをメインの分散型ネットワークに公開することはできません。 -- When publishing a new version for an existing subgraph the same rules apply as above. +- 既存のサブグラフの新バージョンを公開する場合は、上記と同じルールが適用されます。 -### Updating metadata for a published subgraph +### 公開されたサブグラフのメタデータの更新 -Once your subgraph has been published to the decentralized network, you can modify the metadata at any time by making the update in the Subgraph Studio dashboard of the subgraph. After saving the changes and publishing your updates to the network, they will be reflected in the Graph Explorer. This won’t create a new version, as your deployment hasn’t changed. +サブグラフが分散型ネットワークに公開されると、サブグラフのSubgraph Studioダッシュボードで更新を行うことにより、いつでもメタデータを変更することができます。 変更を保存し、更新内容をネットワークに公開すると、グラフエクスプローラーに反映されます。 デプロイメントが変更されていないため、新しいバージョンは作成されません。 diff --git a/pages/ja/developer/query-the-graph.mdx b/pages/ja/developer/query-the-graph.mdx index ae480b1e6883..5be6824eaafa 100644 --- a/pages/ja/developer/query-the-graph.mdx +++ b/pages/ja/developer/query-the-graph.mdx @@ -1,14 +1,14 @@ --- -title: Query The Graph +title: グラフのクエリ --- -With the subgraph deployed, visit the [Graph Explorer](https://thegraph.com/explorer) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. +サブグラフがデプロイされた状態で、[Graph Explorer](https://thegraph.com/explorer)にアクセスすると、[GraphiQL](https://github.com/graphql/graphiql)インターフェースが表示され、サブグラフにデプロイされた GraphQL API を探索して、クエリを発行したり、スキーマを表示したりすることができます。 -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +以下に例を示しますが、サブグラフのエンティティへのクエリの方法については、[Query API](/developer/graphql-api)を参照してください。 -#### Example +#### 例 -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +このクエリは、マッピングが作成したすべてのカウンターを一覧表示します。 作成するのは 1 つだけなので、結果には 1 つの`デフォルトカウンター ```graphql { @@ -19,14 +19,14 @@ This query lists all the counters our mapping has created. Since we only create } ``` -## Using The Graph Explorer +## グラフエクスプローラの利用 -Each subgraph published to the decentralized Graph Explorer has a unique query URL that you can find by navigating to the subgraph details page and clicking on the "Query" button on the top right corner. This will open a side pane that will give you the unique query URL of the subgraph as well as some instructions about how to query it. +分散型グラフエクスプローラに公開されているサブグラフには、それぞれ固有のクエリ URL が設定されており、サブグラフの詳細ページに移動し、右上の「クエリ」ボタンをクリックすることで確認できます。 これは、サブグラフの詳細ページに移動し、右上の「クエリ」ボタンをクリックすると、サブグラフの固有のクエリ URL と、そのクエリの方法を示すサイドペインが表示されます。 ![Query Subgraph Pane](/img/query-subgraph-pane.png) -As you can notice, this query URL must use a unique API key. You can create and manage your API keys in the [Subgraph Studio](https://thegraph.com/studio) in the "API Keys" section. Learn more about how to use Subgraph Studio [here](/studio/subgraph-studio). +お気づきのように、このクエリ URL には固有の API キーを使用する必要があります。 API キーの作成と管理は、[Subgraph Studio](https://thegraph.com/studio)の「API Keys」セクションで行うことができます。 Subgraph Studio の使用方法については、[こちら](/studio/subgraph-studio)をご覧ください。 -Querying subgraphs using your API keys will generate query fees that will be paid in GRT. You can learn more about billing [here](/studio/billing). +API キーを使用してサブグラフをクエリすると、GRT で支払われるクエリ料金が発生します。 課金については[こちら](/studio/billing)をご覧ください。 -You can also use the GraphQL playground in the "Playground" tab to query a subgraph within The Graph Explorer. +また、「プレイグラウンド」タブの GraphQL プレイグラウンドを使用して、The Graph Explorer 内のサブグラフに問い合わせを行うことができます。 diff --git a/pages/ja/developer/querying-from-your-app.mdx b/pages/ja/developer/querying-from-your-app.mdx index c09c44efee72..e94a6f50046e 100644 --- a/pages/ja/developer/querying-from-your-app.mdx +++ b/pages/ja/developer/querying-from-your-app.mdx @@ -1,40 +1,40 @@ --- -title: Querying from an Application +title: アプリケーションからのクエリ --- -Once a subgraph is deployed to the Subgraph Studio or to the Graph Explorer, you will be given the endpoint for your GraphQL API that should look something like this: +サブグラフがSubgraph StudioまたはGraph Explorerにデプロイされると、GraphQL APIのエンドポイントが与えられ、以下のような形になります。 -**Subgraph Studio (testing endpoint)** +**Subgraph Studio (テスト用エンドポイント)** ```sh Queries (HTTP) https://api.studio.thegraph.com/query/// ``` -**Graph Explorer** +**グラフエクスプローラ** ```sh Queries (HTTP) https://gateway.thegraph.com/api//subgraphs/id/ ``` -Using the GraphQL endpoint, you can use various GraphQL Client libraries to query the subgraph and populate your app with the data indexed by the subgraph. +GraphQLエンドポイントを使用すると、さまざまなGraphQLクライアントライブラリを使用してサブグラフをクエリし、サブグラフによってインデックス化されたデータをアプリに入力することができます。 -Here are a couple of the more popular GraphQL clients in the ecosystem and how to use them: +ここでは、エコシステムで人気のあるGraphQLクライアントをいくつか紹介し、その使い方を説明します: -### Apollo client +### Apolloクライアント -[Apollo client](https://www.apollographql.com/docs/) supports web projects including frameworks like React and Vue, as well as mobile clients like iOS, Android, and React Native. +[Apolloクライアント](https://www.apollographql.com/docs/)は、ReactやVueなどのフレームワークを含むWebプロジェクトや、iOS、Android、React Nativeなどのモバイルクライアントをサポートしています。 -Let's look at how fetch data from a subgraph with Apollo client in a web project. +WebプロジェクトでApolloクライアントを使ってサブグラフからデータを取得する方法を見てみましょう。 -First, install `@apollo/client` and `graphql`: +まず、`@apollo/client`と`graphql`をインストールします: ```sh npm install @apollo/client graphql ``` -Then you can query the API with the following code: +その後、以下のコードでAPIをクエリできます: ```javascript import { ApolloClient, InMemoryCache, gql } from '@apollo/client' @@ -67,7 +67,7 @@ client }) ``` -To use variables, you can pass in a `variables` argument to the query: +変数を使うには、クエリの引数に`variables` を渡します。 ```javascript const tokensQuery = ` @@ -100,17 +100,17 @@ client ### URQL -Another option is [URQL](https://formidable.com/open-source/urql/), a somewhat lighter weight GraphQL client library. +もう一つの選択肢は[URQL](https://formidable.com/open-source/urql/)で、URQLは、やや軽量なGraphQLクライアントライブラリです。 -Let's look at how fetch data from a subgraph with URQL in a web project. +URQLは、やや軽量なGraphQLクライアントライブラリです。 -First, install `urql` and `graphql`: +WebプロジェクトでURQLを使ってサブグラフからデータを取得する方法を見てみましょう。 まず、`urql`と`graphql`をインストールします。 ```sh npm install urql graphql ``` -Then you can query the API with the following code: +その後、以下のコードでAPIをクエリできます: ```javascript import { createClient } from 'urql' diff --git a/pages/ja/developer/quick-start.mdx b/pages/ja/developer/quick-start.mdx index 6893d424ddc2..023f229a1f39 100644 --- a/pages/ja/developer/quick-start.mdx +++ b/pages/ja/developer/quick-start.mdx @@ -1,17 +1,17 @@ --- -title: Quick Start +title: クイックスタート --- -This guide will quickly take you through how to initialize, create, and deploy your subgraph on: +このガイドでは、サブグラフの初期化、作成、デプロイの方法を素早く説明します: -- **Subgraph Studio** - used only for subgraphs that index **Ethereum mainnet** -- **Hosted Service** - used for subgraphs that index **other networks** outside of Ethereum mainnnet (e.g. Binance, Matic, etc) +- **Subgraph Studio** - **Ethereum mainnet**をインデックスするサブグラフにのみ使用されます。 +- **Hosted Service** - Ethereumメインネット以外の **他のネットワーク**(Binance、Maticなど)にインデックスを付けるサブグラフに使用されます。 ## Subgraph Studio -### 1. Install the Graph CLI +### 1. Graph CLIのインストール -The Graph CLI is written in JavaScript and you will need to have either `npm` or `yarn` installed to use it. +Graph CLIはJavaScriptで書かれており、使用するには `npm` または `yarn` のいずれかをインストールする必要があります。 ```sh # NPM @@ -21,51 +21,51 @@ $ npm install -g @graphprotocol/graph-cli $ yarn global add @graphprotocol/graph-cli ``` -### 2. Initialize your Subgraph +### 2. サブグラフの初期化 -- Initialize your subgraph from an existing contract. +- 既存のコントラクトからサブグラフを初期化します。 ```sh graph init --studio ``` -- Your subgraph slug is an identifier for your subgraph. The CLI tool will walk you through the steps for creating a subgraph, such as contract address, network, etc as you can see in the screenshot below. +- サブグラフのスラッグは、サブグラフの識別子です。 CLIツールでは、以下のスクリーンショットに見られるように、コントラクトアドレス、ネットワークなど、サブグラフを作成するための手順を説明します。 ![Subgraph command](/img/Subgraph-Slug.png) -### 3. Write your Subgraph +### 3. サブグラフの作成 -The previous commands creates a scaffold subgraph that you can use as a starting point for building your subgraph. When making changes to the subgraph, you will mainly work with three files: +前述のコマンドでは、サブグラフを作成するための出発点として使用できるscaffoldサブグラフを作成します。 サブグラフに変更を加える際には、主に3つのファイルを使用します: -- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraphs will index. -- Schema (schema.graphql) - The GraphQL schema defines what data you wish to retreive from the subgraph. -- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema. +- マニフェスト (subgraph.yaml) - マニフェストは、サブグラフがインデックスするデータソースを定義します。 +- スキーマ (schema.graphql) - GraphQLスキーマは、サブグラフから取得したいデータを定義します。 +- AssemblyScript Mappings (mapping.ts) - データソースからのデータを、スキーマで定義されたエンティティに変換するコードです。 -For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). +サブグラフの書き方の詳細については、 [Create a Subgraph](/developer/create-subgraph-hosted) を参照してください。 -### 4. Deploy to the Subgraph Studio +### 4. Subgraph Studioへのデプロイ -- Go to the Subgraph Studio [https://thegraph.com/studio/](https://thegraph.com/studio/) and connect your wallet. -- Click "Create" and enter the subgraph slug you used in step 2. -- Run these commands in the subgraph folder +- [https://thegraph.com/studio/](https://thegraph.com/studio/) にアクセスし、ウォレットを接続します。 +- 「Create」をクリックし、ステップ2で使用したサブグラフのスラッグを入力します。 +- サブグラフのフォルダで以下のコマンドを実行します。 ```sh $ graph codegen $ graph build ``` -- Authenticate and deploy your subgraph. The deploy key can be found on the Subgraph page in Subgraph Studio. +- サブグラフの認証とデプロイを行います。 デプロイキーは、Subgraph StudioのSubgraphページにあります。 ```sh $ graph auth --studio $ graph deploy --studio ``` -- You will be asked for a version label. It's strongly recommended to use the following conventions for naming your versions. Example: `0.0.1`, `v1`, `version1` +- バージョンラベルの入力を求められます。 バージョンラベルの命名には、以下のような規約を使用することを強くお勧めします。 例: `0.0.1`, `v1`, `version1` -### 5. Check your logs +### 5. ログの確認 -The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: +エラーが発生した場合は、ログを確認してください。 サブグラフが失敗している場合は、 [GraphiQL Playground](https://graphiql-online.com/) を使ってサブグラフの健全性をクエリすることができます。 [このエンドポイント](https://api.thegraph.com/index-node/graphql) を使用します。 なお、以下のクエリを活用して、サブグラフのデプロイメントIDを入力することができます。 この場合、 `Qm...` がデプロイメントIDです(これはSubgraphページの**Details**に記載されています)。 以下のクエリは、サブグラフが失敗したときに教えてくれるので、適宜デバッグすることができます: ```sh { @@ -109,15 +109,15 @@ The logs should tell you if there are any errors. If your subgraph is failing, y } ``` -### 6. Query your Subgraph +### 6. サブグラフのクエリ -You can now query your subgraph by following [these instructions](/developer/query-the-graph). You can query from your dapp if you don't have your API key via the free, rate limited temporary query URL that can be used for development and staging. You can read the additional instructions for how to query a subgraph from a frontend application [here](/developer/querying-from-your-app). +[以下の手順](/developer/query-the-graph)でサブグラフのクエリを実行できます。 APIキーを持っていない場合は、開発やステージングに使用できる無料の一時的なクエリURLを使って、自分のdappからクエリを実行できます。 フロントエンドアプリケーションからサブグラフを照会する方法については、[こちら](/developer/querying-from-your-app)の説明をご覧ください。 -## Hosted Service +## ホスティングサービス -### 1. Install the Graph CLI +### 1. Graph CLIのインストール -"The Graph CLI is an npm package and you will need `npm` or `yarn` installed to use it. +"Graph CLI "はnpmパッケージなので、使用するには`npm`または `yarn`がインストールされていなければなりません。 ```sh # NPM @@ -127,39 +127,39 @@ $ npm install -g @graphprotocol/graph-cli $ yarn global add @graphprotocol/graph-cli ``` -### 2. Initialize your Subgraph +### 2. サブグラフの初期化 -- Initialize your subgraph from an existing contract. +- 既存のコントラクトからサブグラフを初期化します。 ```sh $ graph init --product hosted-service --from-contract
``` -- You will be asked for a subgraph name. The format is `/`. Ex: `graphprotocol/examplesubgraph` +- サブグラフの名前を聞かれます。 形式は`/`です。 例:`graphprotocol/examplesubgraph` -- If you'd like to initialize from an example, run the command below: +- 例題から初期化したい場合は、以下のコマンドを実行します。 ```sh $ graph init --product hosted-service --from-example ``` -- In the case of the example, the subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. +- 例の場合、サブグラフはDani GrantによるGravityコントラクトに基づいており、ユーザーのアバターを管理し、アバターが作成または更新されるたびに`NewGravatar`または`UpdateGravatar`イベントを発行します。 -### 3. Write your Subgraph +### 3. サブグラフの作成 -The previous command will have created a scaffold from where you can build your subgraph. When making changes to the subgraph, you will mainly work with three files: +先ほどのコマンドで、サブグラフを作成するための足場ができました。 サブグラフに変更を加える際には、主に3つのファイルを使用します: -- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraph will index -- Schema (schema.graphql) - The GraphQL schema define what data you wish to retrieve from the subgraph -- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema +- マニフェスト (subgraph.yaml) - マニフェストは、サブグラフがインデックスするデータソースを定義します。 +- スキーマ (schema.graphql) - GraphQLスキーマは、サブグラフから取得したいデータを定義します。 +- AssemblyScript Mappings (mapping.ts) - データソースからのデータを、スキーマで定義されたエンティティに変換するコードです。 -For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). +サブグラフの書き方の詳細については、 [Create a Subgraph](/developer/create-subgraph-hosted) を参照してください。 -### 4. Deploy your Subgraph +### 4. サブグラフのデプロイ -- Sign into the [Hosted Service](https://thegraph.com/hosted-service/) using your github account -- Click Add Subgraph and fill out the required information. Use the same subgraph name as in step 2. -- Run codegen in the subgraph folder +- Github アカウントを使用して[Hosted Service](https://thegraph.com/hosted-service/) にサインインします。 +- 「Add Subgraph」をクリックし、必要な情報を入力します。 手順2と同じサブグラフ名を使用します。 +- サブグラフのフォルダでcodegenを実行します。 ```sh # NPM @@ -169,16 +169,16 @@ $ npm run codegen $ yarn codegen ``` -- Add your Access token and deploy your subgraph. The access token is found on your dashboard in the Hosted Service. +- アクセストークンを追加して、サブグラフをデプロイします。 アクセストークンは、ダッシュボードのHosted Serviceにあります。 ```sh $ graph auth --product hosted-service $ graph deploy --product hosted-service / ``` -### 5. Check your logs +### 5. ログの確認 -The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: +エラーが発生した場合は、ログを確認してください。 サブグラフが失敗している場合は、 [GraphiQL Playground](https://graphiql-online.com/) を使ってサブグラフの健全性をクエリすることができます。 [このエンドポイント](https://api.thegraph.com/index-node/graphql) を使用します。 なお、以下のクエリを活用して、サブグラフのデプロイメントIDを入力することができます。 この場合、 `Qm...` がデプロイメントIDです(これはSubgraphページの**Details**に記載されています)。 以下のクエリは、サブグラフが失敗したときに教えてくれるので、適宜デバッグすることができます: ```sh { @@ -222,6 +222,6 @@ The logs should tell you if there are any errors. If your subgraph is failing, y } ``` -### 6. Query your Subgraph +### 6. サブグラフのクエリ -Follow [these instructions](/hosted-service/query-hosted-service) to query your subgraph on the Hosted Service. +[こちらの手順](/hosted-service/query-hosted-service)に従って、ホステッドサービスでサブグラフをクエリします。 diff --git a/pages/ja/explorer.mdx b/pages/ja/explorer.mdx index 1d97785791c9..c0ed9a036920 100644 --- a/pages/ja/explorer.mdx +++ b/pages/ja/explorer.mdx @@ -2,7 +2,7 @@ title: エクスプローラー --- -Welcome to the Graph Explorer, or as we like to call it, your decentralized portal into the world of subgraphs and network data. 👩🏽‍🚀 The Graph Explorer consists of multiple parts where you can interact with other subgraph developers, dapp developers, Curators, Indexers, and Delegators. グラフエクスプローラーの概要については、以下のビデオをご覧ください。 +グラフエクスプローラーは、サブグラフとネットワークデータの世界への分散型ポータルです。 👩🏽‍🚀 グラフエクスプローラーは、他のサブグラフ開発者、dapp開発者、キュレーター、インデクサー、デリゲーターと交流できる複数のパートで構成されています。 グラフエクスプローラーの概要については、以下のビデオをご覧ください。
+>
## サブグラフ @@ -115,7 +115,7 @@ Welcome to the Graph Explorer, or as we like to call it, your decentralized port 特筆すべき重要な詳細をいくつか挙げます: - **クエリフィーは消費者によって生成された報酬を表し**、サブグラフへの割り当てが終了し、提供したデータが消費者によって検証された後、少なくとも 7 エポック(下記参照)の期間後にインデクサが請求することができます(または請求しないこともできます)。 -- **Indexing rewards represent the amount of rewards the Indexers claimed from the network issuance during the epoch.** Although the protocol issuance is fixed, the rewards only get minted once the Indexers close their allocations towards the subgraphs they’ve been indexing. Thus the per-epoch number of rewards varies (ie. during some epochs, Indexers might’ve collectively closed allocations that have been open for many days). +- **Iインデックス報酬は、エポック期間中にインデクサーがネットワーク発行から請求した報酬の量を表しています。**プロトコルの発行は固定されていますが、報酬はインデクサーがインデックスを作成したサブグラフへの割り当てを終了して初めてミントされます。 そのため、エポックごとの報酬数は変動します(例えば、あるエポックでは、インデクサーが何日も前から開いていた割り当てをまとめて閉じたかもしれません)。 ![エクスプローラーイメージ 8](/img/Network-Stats.png) @@ -178,7 +178,7 @@ Welcome to the Graph Explorer, or as we like to call it, your decentralized port ページの後半には、デリゲーションテーブルがあります。 ここには、あなたがデリゲートしたインデクサーとその詳細(報酬のカットやクールダウンなど)が表示されています。 -With the buttons on the right side of the table, you can manage your delegation - delegate more, undelegate, or withdraw your delegation after the thawing period. +テーブルの右側にあるボタンで、デリゲートを管理することができます。追加でデリゲートする、デリゲートを解除する、解凍期間後にデリゲートを取り消すなどの操作が可能です。 表の右側にあるボタンで、デリゲーションを管理することができます。 diff --git a/pages/ja/hosted-service/migrating-subgraph.mdx b/pages/ja/hosted-service/migrating-subgraph.mdx index dc4d99ca4108..8d556f5644db 100644 --- a/pages/ja/hosted-service/migrating-subgraph.mdx +++ b/pages/ja/hosted-service/migrating-subgraph.mdx @@ -2,7 +2,7 @@ title: Migrating an Existing Subgraph to The Graph Network --- -## Introduction +## イントロダクション This is a guide for the migration of subgraphs from the Hosted Service (also known as 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. @@ -142,7 +142,7 @@ If you're still confused, fear not! Check out the following resources or watch o title="YouTube ビデオプレイヤー" frameBorder="0" allowFullScreen - > +> - [The Graph Network Contracts](https://github.com/graphprotocol/contracts) diff --git a/pages/ja/hosted-service/query-hosted-service.mdx b/pages/ja/hosted-service/query-hosted-service.mdx index 731e3a3120b2..0fe2dbf03bb0 100644 --- a/pages/ja/hosted-service/query-hosted-service.mdx +++ b/pages/ja/hosted-service/query-hosted-service.mdx @@ -4,11 +4,11 @@ title: Query the Hosted Service With the subgraph deployed, visit the [Hosted Service](https://thegraph.com/hosted-service/) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +以下に例を示しますが、サブグラフのエンティティへのクエリの方法については、[Query API](/developer/graphql-api)を参照してください。 #### Example -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +このクエリは、マッピングが作成したすべてのカウンターを一覧表示します。 作成するのは 1 つだけなので、結果には 1 つの`デフォルトカウンター ```graphql { diff --git a/pages/ja/indexing.mdx b/pages/ja/indexing.mdx index 8a823e93b331..e02be5538cbc 100644 --- a/pages/ja/indexing.mdx +++ b/pages/ja/indexing.mdx @@ -26,7 +26,7 @@ import { Difficulty } from '@/components' ### 報酬の分配方法は? -インデキシング報酬は、年間 3%の発行量に設定されているプロトコル・インフレから得られます。 報酬は、それぞれのサブグラフにおけるすべてのキュレーション・シグナルの割合に基づいてサブグラフに分配され、そのサブグラフに割り当てられたステークに基づいてインデクサーに分配されます。 **An allocation must be closed with a valid proof of indexing (POI) that meets the standards set by the arbitration charter in order to be eligible for rewards.** +インデキシング報酬は、年間 3%の発行量に設定されているプロトコル・インフレから得られます。 報酬は、それぞれのサブグラフにおけるすべてのキュレーション・シグナルの割合に基づいてサブグラフに分配され、そのサブグラフに割り当てられたステークに基づいてインデクサーに分配されます。 **特典を受けるためには、仲裁憲章で定められた基準を満たす有効なPOI(Proof of Indexing)で割り当てを終了する必要があります。** コミュニティでは、報酬を計算するための数多くのツールが作成されており、それらは[コミュニティガイドコレクション](https://www.notion.so/Community-Guides-abbb10f4dba040d5ba81648ca093e70c)にまとめられています。 また、[Discord サーバー](https://discord.gg/vtvv7FP)の#delegators チャンネルや#indexers チャンネルでも、最新のツールリストを見ることができます。 @@ -48,7 +48,7 @@ Etherscan を使った`getRewards()`の呼び出し: ```graphql query indexerAllocations { - indexer(id: "") { + indexer(id: "") { allocations { activeForIndexer { allocations { @@ -65,13 +65,13 @@ Use Etherscan to call `getRewards()`: - Etherscan interface to Rewards contract に移動します。 * `getRewards()`を呼び出します - - Expand the **10. getRewards** dropdown. + - **10を拡大します。 getRewards**のドロップダウン - 入力欄に**allocationID**を入力 - **Query**ボタンをクリック ### 争議(disputes)とは何で、どこで見ることができますか? -インデクサークエリとアロケーションは、期間中に The Graph 上で争議することができます。 争議期間は、争議の種類によって異なります。 Queries/attestations have 7 epochs dispute window, whereas allocations have 56 epochs. After these periods pass, disputes cannot be opened against either of allocations or queries. When a dispute is opened, a deposit of a minimum of 10,000 GRT is required by the Fishermen, which will be locked until the dispute is finalized and a resolution has been given. Fisherman are any network participants that open disputes. +インデクサークエリとアロケーションは、期間中に The Graph 上で争議することができます。 争議期間は、争議の種類によって異なります。 クエリ/裁定には7エポックスの紛争窓口があり、割り当てには56エポックスがあります。 これらの期間が経過した後は、割り当てやクエリのいずれに対しても紛争を起こすことはできません。 紛争が開始されると、Fishermenは最低10,000GRTのデポジットを要求され、このデポジットは紛争が最終的に解決されるまでロックされます。 フィッシャーマンとは、紛争を開始するネットワーク参加者のことです。 争議は UI のインデクサーのプロフィールページの`Disputes`タブで確認できます。 @@ -79,7 +79,7 @@ Use Etherscan to call `getRewards()`: - 争議が引き分けた場合、フィッシャーマンのデポジットは返還され、争議中のインデクサーはスラッシュされることはありません。 - 争議が受け入れられた場合、フィッシャーマンがデポジットした GRT は返却され、争議中のインデクサーはスラッシュされ、フィッシャーマンはスラッシュされた GRT の 50%を獲得します。 -Disputes can be viewed in the UI in an Indexer's profile page under the `Disputes` tab. +紛争は、UIのインデクサーのプロファイルページの`紛争`タブで確認できます。 ### クエリフィーリベートとは何ですか、またいつ配布されますか? @@ -114,12 +114,12 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute - **Medium** - 100 個のサブグラフと 1 秒あたり 200 ~ 500 のリクエストをサポートするプロダクションインデクサー - **Large** - 現在使用されているすべてのサブグラフのインデックスを作成し、関連するトラフィックのリクエストに対応します -| Setup | (CPUs) | (memory in GB) | (disk in TBs) | (CPUs) | (memory in GB) | -| -------- | :----: | :------------: | :-----------: | :----: | :------------: | -| Small | 4 | 8 | 1 | 4 | 16 | -| Standard | 8 | 30 | 1 | 12 | 48 | -| Medium | 16 | 64 | 2 | 32 | 64 | -| Large | 72 | 468 | 3.5 | 48 | 184 | +| Setup | Postgres
(CPUs) | Postgres
(memory in GBs) | Postgres
(disk in TBs) | VMs
(CPUs) | VMs
(memory in GBs) | +| -------- |:--------------------------:|:-----------------------------------:|:---------------------------------:|:---------------------:|:------------------------------:| +| Small | 4 | 8 | 1 | 4 | 16 | +| Standard | 8 | 30 | 1 | 12 | 48 | +| Medium | 16 | 64 | 2 | 32 | 64 | +| Large | 72 | 468 | 3.5 | 48 | 184 | ### インデクサーが取るべきセキュリティ対策は? @@ -149,20 +149,20 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute #### グラフノード -| Port | Purpose | Routes | CLI Argument | Environment Variable | -| --- | --- | --- | --- | --- | -| 8000 | GraphQL HTTP server
(for subgraph queries) | /subgraphs/id/...

/subgraphs/name/.../... | --http-port | - | -| 8001 | GraphQL WS
(for subgraph subscriptions) | /subgraphs/id/...

/subgraphs/name/.../... | --ws-port | - | -| 8020 | JSON-RPC
(for managing deployments) | / | --admin-port | - | -| 8030 | Subgraph indexing status API | /graphql | --index-node-port | - | -| 8040 | Prometheus metrics | /metrics | --metrics-port | - | +| Port | Purpose | Routes | CLI Argument | Environment Variable | +| ---- | ------------------------------------------------------- | ------------------------------------------------------------------- | ----------------- | -------------------- | +| 8000 | GraphQL HTTP server
(for subgraph queries) | /subgraphs/id/...

/subgraphs/name/.../... | --http-port | - | +| 8001 | GraphQL WS
(for subgraph subscriptions) | /subgraphs/id/...

/subgraphs/name/.../... | --ws-port | - | +| 8020 | JSON-RPC
(for managing deployments) | / | --admin-port | - | +| 8030 | Subgraph indexing status API | /graphql | --index-node-port | - | +| 8040 | Prometheus metrics | /metrics | --metrics-port | - | #### Indexer Service -| Port | Purpose | Routes | CLI Argument | Environment Variable | -| --- | --- | --- | --- | --- | -| 7600 | GraphQL HTTP server
(for paid subgraph queries) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | -| 7300 | Prometheus metrics | /metrics | --metrics-port | - | +| Port | Purpose | Routes | CLI Argument | Environment Variable | +| ---- | ------------------------------------------------------------ | --------------------------------------------------------------------------- | -------------- | ---------------------- | +| 7600 | GraphQL HTTP server
(for paid subgraph queries) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | +| 7300 | Prometheus metrics | /metrics | --metrics-port | - | #### Indexer Agent @@ -261,7 +261,7 @@ EOF #### Terraform を使ってインフラを構築 -Before running any commands, read through [variables.tf](https://github.com/graphprotocol/indexer/blob/main/terraform/variables.tf) and create a file `terraform.tfvars` in this directory (or modify the one we created in the last step). For each variable where you want to override the default, or where you need to set a value, enter a setting into `terraform.tfvars`. +コマンドを実行する前に、[variables.tf](https://github.com/graphprotocol/indexer/blob/main/terraform/variables.tf)に目を通し、このディレクトリに`terraform.tfvars`というファイルを作成します(または、前のステップで作成したものを修正します)。 デフォルトを上書きしたい、あるいは値を設定したい各変数について、`terraform.tfvars`に設定を入力します。 - 以下のコマンドを実行して、インフラを作成します。 @@ -658,7 +658,7 @@ setDelegationParameters(950000, 600000, 500) ### アロケーションの寿命 -After being created by an indexer a healthy allocation goes through four states. +インデクサーによって作成された後、健全なアロケーションは4つの状態を経ます。 - **Active**- オンチェーンでアロケーションが作成されると(allocateFrom())、それは**active**であるとみなされます。 インデクサー自身やデリゲートされたステークの一部がサブグラフの配置に割り当てられ、これによりインデクシング報酬を請求したり、そのサブグラフの配置のためにクエリを提供したりすることができます。 インデクサエージェントは、インデキシングルールに基づいて割り当ての作成を管理します。 diff --git a/pages/ja/studio/billing.mdx b/pages/ja/studio/billing.mdx index 2ec869670090..7f23343baa17 100644 --- a/pages/ja/studio/billing.mdx +++ b/pages/ja/studio/billing.mdx @@ -2,7 +2,7 @@ title: Billing on the Subgraph Studio --- -### Overview +### 概要 Invoices are statements of payment amounts owed by a customer and are typically generated on a weekly basis in the system. You’ll be required to pay fees based on the query fees you generate using your API keys. The billing contract lives on the [Polygon](https://polygon.technology/) network. It’ll allow you to: @@ -46,7 +46,7 @@ For a quick demo of how billing works on the Subgraph Studio, check out the vide title="YouTube ビデオプレイヤー" frameBorder="0" allowFullScreen - > +> ### Multisig Users diff --git a/pages/ja/studio/deploy-subgraph-studio.mdx b/pages/ja/studio/deploy-subgraph-studio.mdx index 2155d8fe8976..69b6786ebda4 100644 --- a/pages/ja/studio/deploy-subgraph-studio.mdx +++ b/pages/ja/studio/deploy-subgraph-studio.mdx @@ -29,7 +29,7 @@ npm install -g @graphprotocol/graph-cli Before deploying your actual subgraph you need to create a subgraph in [Subgraph Studio](https://thegraph.com/studio/). We recommend you read our [Studio documentation](/studio/subgraph-studio) to learn more about this. -## Initialize your Subgraph +## サブグラフの初期化 Once your subgraph has been created in Subgraph Studio you can initialize the subgraph code using this command: diff --git a/pages/ja/studio/subgraph-studio.mdx b/pages/ja/studio/subgraph-studio.mdx index 5e2cf18ce86e..1f5ecf6a7011 100644 --- a/pages/ja/studio/subgraph-studio.mdx +++ b/pages/ja/studio/subgraph-studio.mdx @@ -73,7 +73,7 @@ You’ve made it this far - congrats! Publishing your subgraph means that an IPF title="YouTube ビデオプレイヤー" frameBorder="0" allowFullScreen - > +> Remember, while you’re going through your publishing flow, you’ll be able to push to either mainnet or Rinkeby, the testnet we support. If you’re a first time subgraph developer, we highly suggest you start with publishing to Rinkeby, which is free to do. This will allow you to see how the subgraph will work in The Graph Explorer and will allow you to test curation elements. diff --git a/pages/ko/about/introduction.mdx b/pages/ko/about/introduction.mdx index 5f840c040400..f401d4070f1f 100644 --- a/pages/ko/about/introduction.mdx +++ b/pages/ko/about/introduction.mdx @@ -1,47 +1,47 @@ --- -title: Introduction +title: 소개 --- -This page will explain what The Graph is and how you can get started. +이 페이지는 더 그래프가 무엇이며, 여러분들이 시작하는 방법에 대해 설명합니다. -## What The Graph Is +## 더 그래프란 무엇인가? -The Graph is a decentralized protocol for indexing and querying data from blockchains, starting with Ethereum. It makes it possible to query data that is difficult to query directly. +더 그래프는 이더리움으로부터 시작한 블록체인 데이터를 인덱싱하고 쿼리하기 위한 분산형 프로토콜입니다. 이는 직접 쿼리하기 어려운 데이터 쿼리를 가능하게 해줍니다. -Projects with complex smart contracts like [Uniswap](https://uniswap.org/) and NFTs initiatives like [Bored Ape Yacht Club](https://boredapeyachtclub.com/) store data on the Ethereum blockchain, making it really difficult to read anything other than basic data directly from the blockchain. +[유니스왑](https://uniswap.org/) 처럼 복잡한 스마트 컨트렉트를 구현하는 프로젝트나 [Bored Ape Yacht Club](https://boredapeyachtclub.com/)과 같은 NFT 이니셔티브들은 이더리움 블록체인에 데이터를 저장하기 때문에, 블록체인의 기본 데이터 외에는 직접적으로 읽기가 매우 어렵습니다. -In the case of Bored Ape Yacht Club, we can perform basic read operations on [the contract](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) like getting the owner of a certain Ape, getting the content URI of an Ape based on their ID, or the total supply, as these read operations are programmed directly into the smart contract, but more advanced real-world queries and operations like aggregation, search, relationships, and non-trivial filtering are not possible. For example, if we wanted to query for apes that are owned by a certain address, and filter by one of its characteristics, we would not be able to get that information by interacting directly with the contract itself. +Bored Ape Yacht Club의 경우에 우리는 [해당 컨트렉트](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) 에서 특정 유인원의 주인을 확인하거나, 그들의 ID를 기반으로 Ape의 콘텐츠 URI를 확인하거나, 혹은 총 공급량을 확인하는 등의 기본적인 읽기 작업을 수행할 수 있습니다. 이는 이러한 읽기 작업이 스마트 컨트렉트에 직접적으로 프로그래밍 되었기 때문에 가능하지만, 집계, 검색, 관계 및 단순하지 않은 필터링과 같은 더 고급 적인 실생활 쿼리 및 작업은 불가능합니다. 예를 들어 여러분들이 특정 주소가 소유한 유인원을 쿼리하고, 그 특성 중 하나로 필터링하고자 하는 경우, 우리는 해당 컨트렉트 자체와 직접 상호 작용하여 해당 정보를 얻을 수 없습니다. -To get this data, you would have to process every single [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) event ever emitted, read the metadata from IPFS using the Token ID and IPFS hash, and then aggregate it. Even for these types of relatively simple questions, it would take **hours or even days** for a decentralized application (dapp) running in a browser to get an answer. +이러한 데이터를 얻기 위해서, 여러분들은 아마 그동안 발생한 모든 단일 [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) 이벤트 들을 모두 처리하고, 토큰 ID와 IPFS 해시를 사용하여 IPFS로부터 메타데이터를 읽은 후 이들을 집계해야 합니다. 이러한 유형의 비교적 간단한 쿼리에 대해서도, 아마 브라우저에서 실행되는 탈중앙화 애필리케이션(dapp)은 답을 얻기 위해 **몇 시간 혹은 며칠**이 걸릴 수도 있습니다. -You could also build out your own server, process the transactions there, save them to a database, and build an API endpoint on top of it all in order to query the data. However, this option is resource intensive, needs maintenance, presents a single point of failure, and breaks important security properties required for decentralization. +또한 여러분들은 데이터를 쿼리하기 위해 자체 서버를 구축하고, 그곳에서 트랜잭션을 처리하고, 데이터베이스에 저장하고, 그 위에 API 엔드포인트를 구축할 수도 있습니다. 하지만 이 옵션은 많은 리소스를 사용하고, 유지 관리가 필요하며, 단일 실패 지점을 제공하고 또한 탈중앙화에 필수적인 중요한 보안 속성을 손상시킵니다. -**Indexing blockchain data is really, really hard.** +**블록체인 데이터를 인덱싱하는 것은 정말로, 정말로 어렵습니다.** -Blockchain properties like finality, chain reorganizations, or uncled blocks complicate this process further, and make it not just time consuming but conceptually hard to retrieve correct query results from blockchain data. +최종성, 체인 재구성 또는 언클 블록과 같은 블록체인 속성들은 이 프로세스를 더욱 복잡하게 만들고, 블록체인 데이터에서 정확한 쿼리 결과가 검색되도록 하기 위해 많은 시간이 소요될 뿐만 아니라 개념적으로도 어렵게 만듭니다. -The Graph solves this with a decentralized protocol that indexes and enables the performant and efficient querying of blockchain data. These APIs (indexed "subgraphs") can then be queried with a standard GraphQL API. Today, there is a hosted service as well as a decentralized protocol with the same capabilities. Both are backed by the open source implementation of [Graph Node](https://github.com/graphprotocol/graph-node). +더 그래프는 블록체인 데이터를 인덱싱하고 효율적이고 효과적인 쿼리를 가능하게 하는 분산형 프로토콜로 이를 해결합니다. 이러한 API(인덱싱된 "서브그래프")들을 표준 GraphQL API로 쿼리할 수 있습니다. 오늘날, 호스팅 서비스와 동일한 기능을 가진 탈중앙화 프로토콜이 존재합니다. 둘 다 [Graph Node](https://github.com/graphprotocol/graph-node)의 오픈소스 구현에 의해 뒷받침 됩니다. -## How The Graph Works +## 더 그래프의 작동 방식 -The Graph learns what and how to index Ethereum data based on subgraph descriptions, known as the subgraph manifest. The subgraph description defines the smart contracts of interest for a subgraph, the events in those contracts to pay attention to, and how to map event data to data that The Graph will store in its database. +더 그래프는 서브 매니페스트라고 하는 서브그래프 설명을 기반으로 이더리움 데이터를 인덱싱하는 항목과 방법을 학습합니다. 서브그래프 설명은 서브그래프에 대한 스마트 컨트렉트, 주의를 기울여야 할 컨트렉트들의 이벤트 및 더 그래프가 데이터베이스에 저장할 데이터에 이벤트 데이터를 매핑하는 방법을 정의합니다. -Once you have written a `subgraph manifest`, you use the Graph CLI to store the definition in IPFS and tell the indexer to start indexing data for that subgraph. +여러분들이 `subgraph manifest`를 작성한 후에 , Graph CLI를 사용하여 IPFS에 정의를 저장하고 인덱서에게 해당 서브그래프에 대한 데이터 인덱싱을 시작하도록 지시합니다. -This diagram gives more detail about the flow of data once a subgraph manifest has been deployed, dealing with Ethereum transactions: +이 다이어그램은 이더리움 트랜잭션을 처리하는 서브그래프 매니페스트가 배포된 후 데이터 흐름에 대한 자세한 정보를 제공합니다. ![](/img/graph-dataflow.png) -The flow follows these steps: +해당 플로우는 다음 단계를 따릅니다 : -1. A decentralized application adds data to Ethereum through a transaction on a smart contract. -2. The smart contract emits one or more events while processing the transaction. -3. Graph Node continually scans Ethereum for new blocks and the data for your subgraph they may contain. -4. Graph Node finds Ethereum events for your subgraph in these blocks and runs the mapping handlers you provided. The mapping is a WASM module that creates or updates the data entities that Graph Node stores in response to Ethereum events. -5. The decentralized application queries the Graph Node for data indexed from the blockchain, using the node's [GraphQL endpoint](https://graphql.org/learn/). The Graph Node in turn translates the GraphQL queries into queries for its underlying data store in order to fetch this data, making use of the store's indexing capabilities. The decentralized application displays this data in a rich UI for end-users, which they use to issue new transactions on Ethereum. The cycle repeats. +1. 탈중앙화 애플리케이션은 스마트 컨트렉트의 트랜잭션을 통해 이더리움에 데이터를 추가합니다. +2. 스마트 컨트렉트는 트랜잭션을 처리하는 동안 하나 이상의 이벤트를 발생시킵니다. +3. 그래프 노드는 이더리움에서 새 블록들과 해당 블록들에 포함될 수 있는 서브그래프 데이터를 지속적으로 검색합니다. +4. 그래프 노드는 이러한 블록에서 서브그래프에 대한 이더리움 이벤트를 찾고 사용자가 제공한 매핑 핸들러를 실행합니다. 매핑은 이더리움 이벤트들에 대응해 그래프 노드가 저장하는 데이터 엔티티들을 생성하거나 업데이트하는 WASM 모듈입니다. +5. 탈중앙화 애플리케이션은 노드의 [GraphQL endpoint](https://graphql.org/learn/)를 사용하여 블록체인에서 인덱싱된 데이터를 위해 그래프 노드를 쿼리합니다. 더 그래프 노드는 GraphQL 쿼리를 기본 데이터 저장소에 대한 쿼리로 변환하여 이 데이터를 가져오고 저장소의 인덱싱 기능들을 활용합니다. 분산형 애플리케이션은 최종 사용자를 위해 이더리움에서 새로운 트랜잭션을 발생시킬 때 사용하는 풍부한 UI로 이 데이터를 표시합니다. 이 싸이클이 반복됩니다. -## Next Steps +## 다음 단계 -In the following sections we will go into more detail on how to define subgraphs, how to deploy them, and how to query data from the indexes that Graph Node builds. +다음 섹션에서 우리는 서브그래프를 정의하는 방법, 배포하는 방법 및 그래프 노드가 구축하는 인덱스들로부터 데이터를 쿼리하는 방법에 대해 더 자세히 알아볼 것입니다. -Before you start writing your own subgraph, you might want to have a look at the Graph Explorer and explore some of the subgraphs that have already been deployed. The page for each subgraph contains a playground that lets you query that subgraph's data with GraphQL. +자체 서브그래프를 작성하기 전에, 여러분들은 그래프 탐색기를 살펴보고 이미 배포된 일부 서브 그래프들에 대해 알아보길 희망하실 수 있습니다. 각 서브 그래프 페이지에는 여러분들이 GraphQL로 서브그래프의 데이터를 쿼리할 수 있는 영역이 포함되어 있습니다. diff --git a/pages/ko/about/network.mdx b/pages/ko/about/network.mdx index b19f08d12bc7..b7a6a6139801 100644 --- a/pages/ko/about/network.mdx +++ b/pages/ko/about/network.mdx @@ -1,15 +1,15 @@ --- -title: Network Overview +title: 네트워크 개요 --- -The Graph Network is a decentralized indexing protocol for organizing blockchain data. Applications use GraphQL to query open APIs called subgraphs, to retrieve data that is indexed on the network. With The Graph, developers can build serverless applications that run entirely on public infrastructure. +더 그래프 네트워크는 블록체인 데이터를 구성하기 위한 분산형 인덱싱 프로토콜입니다. 애플리케이션들은 GraphQL을 사용하여 서브그래프라고 하는 개방형 API를 쿼리하여 네트워크에서 인덱싱된 데이터를 검색합니다. 더 그래프를 사용하여 개발자는 완전히 범용 인프라에서 실행되는 서버리스 애플리케이션을 구축할 수 있습니다. -> GRT Token Address: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) +> GRT 토큰 주소: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) -## Overview +## 개요 -The Graph Network consists of Indexers, Curators and Delegators that provide services to the network, and serve data to Web3 applications. Consumers use the applications and consume the data. +더 그래프 네트워크는 네트워크에 서비스를 제공하고 Web3 애플리케이션들에 데이터를 제공하는 인덱서, 큐레이터 및 위임자로 구성됩니다. 소비자는 애플리케이션을 사용하고 데이터를 소비합니다. -![Token Economics](/img/Network-roles@2x.png) +![토큰 이코노믹스](/img/Network-roles@2x.png) -To ensure economic security of The Graph Network and the integrity of data being queried, participants stake and use Graph Tokens (GRT). GRT is a work token that is an ERC-20 on the Ethereum blockchain, used to allocate resources in the network. Active Indexers, Curators and Delegators can provide services and earn income from the network, proportional to the amount of work they perform and their GRT stake. +더 그래프 네트워크의 경제적 보안과 쿼리 되는 데이터의 무결성을 보장하기 위해 참여자들은 그래프 토큰(GRT)을 스테이킹하고 사용합니다. GRT는 이더리움 블록체인 상의 ERC-20 작업 토큰이며, 네트워크 내의 리소스들을 할당하는 데 사용됩니다. 활성 인덱서, 큐레이터 및 위임자는 수행하는 작업의 양과 GRT 지분에 비례하여 네트워크에 서비스를 제공하고 수익을 창출할 수 있습니다. diff --git a/pages/ko/curating.mdx b/pages/ko/curating.mdx index dcb329288947..456deec666f7 100644 --- a/pages/ko/curating.mdx +++ b/pages/ko/curating.mdx @@ -100,5 +100,5 @@ title: 큐레이팅 title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> diff --git a/pages/ko/delegating.mdx b/pages/ko/delegating.mdx index 22b1e8c5bfd4..20cd2496fa04 100644 --- a/pages/ko/delegating.mdx +++ b/pages/ko/delegating.mdx @@ -28,7 +28,9 @@ This guide will explain how to be an effective delegator in the Graph Network. D 또한 고려해야 할 한 가지는 위임을 위한 인덱서를 현명하게 선택하는 것입니다. 만약 여러분들이 신뢰할 수 없거나 작업을 제대로 수행하지 않는 인덱서를 선택하면 여러분들은 해당 위임의 취소를 원할 것입니다. 이 경우, 보상을 받는 기회를 잃음과 더불어, 단지 여러분의 GRT를 소각하기만 한 결과를 초래할 것입니다. -
위임 UI에는 0.5%의 수수료 및 28일의 위임 해지 기간이 명시되어있습니다.
+
+ 위임 UI에는 0.5%의 수수료 및 28일의 위임 해지 기간이 명시되어있습니다. +
### 위임자들에 대한 공정한 보상 지급 규칙을 지닌 신뢰할 수 있는 인덱서 선택 @@ -87,5 +89,5 @@ A delegator can therefore do the math to determine that the Indexer offering 20% title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> diff --git a/pages/ko/developer/assemblyscript-api.mdx b/pages/ko/developer/assemblyscript-api.mdx index 2b6aa855c4a3..7ddd83d90288 100644 --- a/pages/ko/developer/assemblyscript-api.mdx +++ b/pages/ko/developer/assemblyscript-api.mdx @@ -2,220 +2,220 @@ title: AssemblyScript API --- -> Note: if you created a subgraph prior to `graph-cli`/`graph-ts` version `0.22.0`, you're using an older version of AssemblyScript, we recommend taking a look at the [`Migration Guide`](/developer/assemblyscript-migration-guide) +> 참고: 만약 `graph-cli`/`graph-ts` 버전 `0.22.0` 이전의 서브그래프를 생성하는 경우, 이전 버젼의 AssemblyScript를 사용중인 경우, [`Migration Guide`](/developer/assemblyscript-migration-guide)를 참고하시길 권장드립니다. -This page documents what built-in APIs can be used when writing subgraph mappings. Two kinds of APIs are available out of the box: +이 페이지는 서브그래프 매핑을 작성할 때 사용할 수 있는 내장 API를 설명합니다. 다음 두 가지 종류의 API를 즉시 사용할 수 있습니다 : -- the [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) and -- code generated from subgraph files by `graph codegen`. +- [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) 그리고 +- `graph codegen`에 의해 서브그래프 파일들에서 생성된 코드 -It is also possible to add other libraries as dependencies, as long as they are compatible with [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Since this is the language mappings are written in, the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) is a good source for language and standard library features. +[AssemblyScript](https://github.com/AssemblyScript/assemblyscript)와 호환되는 한 다른 라이브러리들을 의존성(dependencies)으로서 추가할 수도 있습니다. 이것은 언어 매핑이 작성되기 때문에 [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) 위키는 언어 및 표준 라이브러리 기능과 관련한 좋은 소스입니다. -## Installation +## 설치 -Subgraphs created with [`graph init`](/developer/create-subgraph-hosted) come with preconfigured dependencies. All that is required to install these dependencies is to run one of the following commands: +[`graph init`](/developer/create-subgraph-hosted)로 생성된 서브그래프는 미리 구성된 의존성들(dependencies)을 함께 동반합니다. 이러한 의존성들을 설치하려면 다음 명령 중 하나를 실행해야 합니다. ```sh yarn install # Yarn npm install # NPM ``` -If the subgraph was created from scratch, one of the following two commands will install the Graph TypeScript library as a dependency: +서브그래프가 처음부터 만들어진 경우 다음 두 명령 중 하나가 의존성으로서 그래프 타입스크립트 라이브러리를 설치할 것입니다. ```sh yarn add --dev @graphprotocol/graph-ts # Yarn npm install --save-dev @graphprotocol/graph-ts # NPM ``` -## API Reference +## API 참조 -The `@graphprotocol/graph-ts` library provides the following APIs: +`@graphprotocol/graph-ts` 라이브러리가 다음과 같은 API들을 제공합니다. -- An `ethereum` API for working with Ethereum smart contracts, events, blocks, transactions, and Ethereum values. -- A `store` API to load and save entities from and to the Graph Node store. -- A `log` API to log messages to the Graph Node output and the Graph Explorer. -- An `ipfs` API to load files from IPFS. -- A `json` API to parse JSON data. -- A `crypto` API to use cryptographic functions. -- Low-level primitives to translate between different type systems such as Ethereum, JSON, GraphQL and AssemblyScript. +- 이더리움 스마트 컨트렉트, 이벤트, 블록, 트랜젝션, 그리고 이더리움 값들과 작업하기 위한 `ethereum` API +- 더그래프 노드 스토어에서 엔티티를 로드하고 저장하기 위한 `store` API +- 더그래프 노드 출력 및 그래프 탐색기에 메세지를 기록하는 `log` API +- IPFS로부터 파일들을 로드하기 위한 `ipfs` API +- JSON 데이터를 구문 분석하는 `json` API +- 암호화 기능을 사용하기 위한 `crypto` API +- Ethereum, JSON, GraphQL 및 AssemblyScript와 같은 다양한 유형 시스템 간의 변환을 위한 저수준 프리미티브 -### Versions +### 버전 -The `apiVersion` in the subgraph manifest specifies the mapping API version which is run by Graph Node for a given subgraph. The current mapping API version is 0.0.6. +서브그래프 매니페스트의 `apiVersion`은 주어진 서브그래프에 대해 그래프 노드가 실행하는 매핑 API 버전을 지정합니다. 현재 맵핑 API 버전은 0.0.6 입니다. -| Version | Release notes | +| 버전 | 릴리스 노트 | | :-: | --- | -| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | -| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | -| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | -| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | -| 0.0.2 | Added `input` field to the Ethereum Transaction object | +| 0.0.6 | 이더리움 트랜잭션 개체에 `nonce` 필드를 추가했습니다.
`baseFeePerGas`가 이더리움 블록 개체에 추가되었습니다. | +| 0.0.5 | AssemblyScript를 버전 0.19.10으로 업그레이드했습니다(변경 내용 깨짐 포함. [`Migration Guide`](/developer/assemblyscript-migration-guide) 참조)
`ethereum.transaction.gasUsed`의 이름이 `ethereum.transaction.gasLimit`로 변경되었습니다. | +| 0.0.4 | Ethereum SmartContractCall 개체에 `functionSignature` 필드를 추가했습니다. | +| 0.0.3 | Ethereum Call 개체에 `from` 필드를 추가했습니다.
`etherem.call.address`의 이름이 `ethereum.call.to`로 변경되었습니다. | +| 0.0.2 | Ethereum Transaction 개체에 `input` 필드를 추가했습니다. | -### Built-in Types +### 기본 제공 유형 -Documentation on the base types built into AssemblyScript can be found in the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types). +AssemblyScript에 내장된 기본 유형에 대한 설명서는 [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types)에서 확인할 수 있습니다. -The following additional types are provided by `@graphprotocol/graph-ts`. +다음의 추가적인 유형들이 `@graphprotocol/graph-ts`에 의해 제공됩니다. #### ByteArray ```typescript -import { ByteArray } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'에서 { ByteArray }를 입력합니다. ``` -`ByteArray` represents an array of `u8`. +`ByteArray`가 `u8`의 배열을 나타냅니다. _Construction_ -- `fromI32(x: i32): ByteArray` - Decomposes `x` into bytes. -- `fromHexString(hex: string): ByteArray` - Input length must be even. Prefixing with `0x` is optional. +- `fromI32(x: i32): ByteArray` - `x`를 바이트로 분해합니다. +- `fromHexString(hex: string): ByteArray` - 입력 길이는 반드시 짝수여야 합니다. `0x` 접두사는 선택사항입니다. -_Type conversions_ +_유형 변환_ -- `toHexString(): string` - Converts to a hex string prefixed with `0x`. -- `toString(): string` - Interprets the bytes as a UTF-8 string. -- `toBase58(): string` - Encodes the bytes into a base58 string. -- `toU32(): u32` - Interprets the bytes as a little-endian `u32`. Throws in case of overflow. -- `toI32(): i32` - Interprets the byte array as a little-endian `i32`. Throws in case of overflow. +- `toHexString(): string` - 접두사가 `0x`인 16진 문자열로 변환합니다. +- `toString(): string` - 바이트를 UTF-8 문자열로 해석합니다. +- `toBase58(): string` - 바이트를 base58 문자열로 인코딩합니다. +- `toU32(): u32` - 바이트를 little-endian `u32`로 해석합니다. 오버플로우의 경우에는 Throws 합니다. +- `toI32(): i32` - 바이트 배열을 little-endian `i32`로 해석합니다. 오버플로우의 경우에는 Throws 합니다. -_Operators_ +_연산자_ -- `equals(y: ByteArray): bool` – can be written as `x == y`. +- `equals(y: ByteArray): bool` – `x == y`로 쓸 수 있습니다 #### BigDecimal ```typescript -import { BigDecimal } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'로 부터 { BigDecimal }을 입력합니다. ``` -`BigDecimal` is used to represent arbitrary precision decimals. +`BigDecimal`은 임의의 정밀도 소수를 나타내는 데 사용됩니다. _Construction_ -- `constructor(bigInt: BigInt)` – creates a `BigDecimal` from an `BigInt`. -- `static fromString(s: string): BigDecimal` – parses from a decimal string. +- `constructor(bigInt: BigInt)` – `BigInt`로 부터 `BigDecimal`을 생성합니다. +- `static fromString(s: string): BigDecimal` – 10진수 문자열에서 구문 분석을 수행합니다. -_Type conversions_ +_유형 변환_ -- `toString(): string` – prints to a decimal string. +- `toString(): string` – 10진수 문자열로 인쇄합니다. _Math_ -- `plus(y: BigDecimal): BigDecimal` – can be written as `x + y`. -- `minus(y: BigDecimal): BigDecimal` – can be written as `x - y`. -- `times(y: BigDecimal): BigDecimal` – can be written as `x * y`. -- `div(y: BigDecimal): BigDecimal` – can be written as `x / y`. -- `equals(y: BigDecimal): bool` – can be written as `x == y`. -- `notEqual(y: BigDecimal): bool` – can be written as `x != y`. -- `lt(y: BigDecimal): bool` – can be written as `x < y`. -- `le(y: BigDecimal): bool` – can be written as `x <= y`. -- `gt(y: BigDecimal): bool` – can be written as `x > y`. -- `ge(y: BigDecimal): bool` – can be written as `x >= y`. -- `neg(): BigDecimal` - can be written as `-x`. +- `plus(y: BigDecimal): BigDecimal` – `x + y`로 쓸 수 있습니다. +- `minus(y: BigDecimal): BigDecimal` – `x - y`로 쓸 수 있습니다. +- `times(y: BigDecimal): BigDecimal` – `x * y`로 쓸 수 있습니다. +- `div(y: BigDecimal): BigDecimal` – `x / y`로 쓸 수 있습니다. +- `equals(y: BigDecimal): bool` – `x == y`로 쓸 수 있습니다. +- `notEqual(y: BigDecimal): bool` – `x != y`로 쓸 수 있습니다. +- `lt(y: BigDecimal): bool` – `x < y`로 쓸 수 있습니다. +- `le(y: BigDecimal): bool` – `x <= y`로 쓸 수 있습니다. +- `gt(y: BigDecimal): bool` – `x > y`로 쓸 수 있습니다. +- `ge(y: BigDecimal): bool` – `x >= y`로 쓸 수 있습니다. +- `neg(): BigDecimal` - `-x`로 쓸 수 있습니다. #### BigInt ```typescript -import { BigInt } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'에서 { BigInt }를 입력합니다. ``` -`BigInt` is used to represent big integers. This includes Ethereum values of type `uint32` to `uint256` and `int64` to `int256`. Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. +`BigInt`는 큰 정수를 나타내는 데 사용됩니다. 여기에는 `uint32` ~ `uint256` 및 `int64` ~ `int256`값이 포함됩니다. `int32`, `uint24` 혹은 `int8`과 같은 `uint32` 이하는 전부 `i32`로 표시됩니다. -The `BigInt` class has the following API: +`BigInt` 클래스에는 다음의 API가 있습니다: _Construction_ -- `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32`. -- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string. -- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interprets `bytes` as an unsigned, little-endian integer. If your input is big-endian, call `.reverse()` first. -- `BigInt.fromSignedBytes(x: Bytes): BigInt` – Interprets `bytes` as a signed, little-endian integer. If your input is big-endian, call `.reverse()` first. +- `BigInt.fromI32(x: i32): BigInt` – `i32`로 부터 `BigInt`를 생성합니다. +- `BigInt.fromString(s: string): BigInt`– 문자열로부터 `BigInt`를 구문 분석합니다. +- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – `bytes`를 부호 없는 little-endian 정수로 해석합니다. 입력 값이 big-endian인 경우, 먼저 `.reverse()`를 호출하십시오. +- `BigInt.fromSignedBytes(x: Bytes): BigInt` – `bytes`를 signed, little-endian 정수로 해석합니다. 입력 값이 big-endian인 경우, 먼저 `.reverse()`를 호출하십시오. - _Type conversions_ + _유형 변환_ -- `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.toBigDecimal(): BigDecimal` - converts into a decimal with no fractional part. +- `x.toHex(): string` – `BigInt`를 16진수 문자열로 바꿉니다. +- `x.toString(): string` – `BigInt`를 10진수 문자열로 바꿉니다. +- `x.toI32(): i32` – `BigInt`를 `i32`로 반환합니다; 만약 값이 `i32`에 부합하지 않으면, 실패합니다. `x.isI32()`를 먼저 확인하는 것이 좋습니다. +- `x.toBigDecimal(): BigDecimal` - 소수 부분 없이 십진수로 변환합니다. _Math_ -- `x.plus(y: BigInt): BigInt` – can be written as `x + y`. -- `x.minus(y: BigInt): BigInt` – can be written as `x - y`. -- `x.times(y: BigInt): BigInt` – can be written as `x * y`. -- `x.div(y: BigInt): BigInt` – can be written as `x / y`. -- `x.mod(y: BigInt): BigInt` – can be written as `x % y`. -- `x.equals(y: BigInt): bool` – can be written as `x == y`. -- `x.notEqual(y: BigInt): bool` – can be written as `x != y`. -- `x.lt(y: BigInt): bool` – can be written as `x < y`. -- `x.le(y: BigInt): bool` – can be written as `x <= y`. -- `x.gt(y: BigInt): bool` – can be written as `x > y`. -- `x.ge(y: BigInt): bool` – can be written as `x >= y`. -- `x.neg(): BigInt` – can be written as `-x`. -- `x.divDecimal(y: BigDecimal): BigDecimal` – divides by a decimal, giving a decimal result. -- `x.isZero(): bool` – Convenience for checking if the number is zero. -- `x.isI32(): bool` – Check if the number fits in an `i32`. -- `x.abs(): BigInt` – Absolute value. -- `x.pow(exp: u8): BigInt` – Exponentiation. -- `bitOr(x: BigInt, y: BigInt): BigInt` – can be written as `x | y`. -- `bitAnd(x: BigInt, y: BigInt): BigInt` – can be written as `x & y`. -- `leftShift(x: BigInt, bits: u8): BigInt` – can be written as `x << y`. -- `rightShift(x: BigInt, bits: u8): BigInt` – can be written as `x >> y`. +- `x.plus(y: BigInt): BigInt` – `x + y`로 쓸 수 있습니다. +- `x.minus(y: BigInt): BigInt` – `x - y`로 쓸 수 있습니다. +- `x.times(y: BigInt): BigInt` – `x * y`로 쓸 수 있습니다. +- `x.div(y: BigInt): BigInt` – `x / y`로 쓸 수 있습니다. +- `x.mod(y: BigInt): BigInt` – `x % y`로 쓸 수 있습니다. +- `x.equals(y: BigInt): bool` – `x == y`로 쓸 수 있습니다. +- `x.notEqual(y: BigInt): bool` – `x != y`로 쓸 수 있습니다. +- `x.lt(y: BigInt): bool` – `x < y`로 쓸 수 있습니다. +- `x.le(y: BigInt): bool` – `x <= y`로 쓸 수 있습니다. +- `x.gt(y: BigInt): bool` – `x > y`로 쓸 수 있습니다. +- `x.ge(y: BigInt): bool` – `x >= y`로 쓸 수 있습니다. +- `x.neg(): BigInt` – `-x`로 쓸 수 있습니다. +- `x.divDecimal(y: BigDecimal): BigDecimal` – 십진수로 나누어, 십진 결과를 제공합니다. +- `x.isZero(): bool` – 숫자가 0인지 확인하는데 편리합니다. +- `x.isI32(): bool` – 숫자가 `i32`에 부합하는지 확인합니다. +- `x.abs(): BigInt` – 절대값. +- `x.pow(exp: u8): BigInt` – 지수화. +- `bitOr(x: BigInt, y: BigInt): BigInt` – `x | y`로 쓸 수 있습니다. +- `bitAnd(x: BigInt, y: BigInt): BigInt` – `x & y`로 쓸 수 있습니다. +- `leftShift(x: BigInt, bits: u8): BigInt` – `x << y`로 쓸 수 있습니다. +- `rightShift(x: BigInt, bits: u8): BigInt` – `x >> y`로 쓸 수 있습니다. #### TypedMap ```typescript -import { TypedMap } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'에서 { TypedMap }를 입력합니다. ``` -`TypedMap` can be used to stored key-value pairs. See [this example](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). +`TypedMap`는 key-value 쌍을 저장하는데 사용될 수 있습니다. [이 예](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51)를 보시기 바랍니다. -The `TypedMap` class has the following 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` -- `map.getEntry(key: K): TypedMapEntry | null` – returns the key-value pair for a `key` or `null` if the `key` does not exist in the map -- `map.get(key: K): V | null` – returns the value for a `key` or `null` if the `key` does not exist in the map -- `map.isSet(key: K): bool` – returns `true` if the `key` exists in the map and `false` if it does not +- `new TypedMap()` – 유형 `K`의 키와 유형 `T`의 값을 사용하여 빈 맵을 생성합니다. +- `map.set(key: K, value: V): void` – `key` 값을 `value`로 설정합니다. +- `map.getEntry(key: K): TypedMapEntry | null` – 만약 `key`가 맵에 존재하지 않는 경우, `key` 혹은 `null` 에 대한 key-value 쌍을 반환합니다. +- `map.get(key: K): V | null` – 만약 `key`가 맵에 존재하지 않으면, `key` 혹은 `null` 값을 반환합니다. +- `map.isSet(key: K): bool` – 만약 `key`는 맵에 존재하나, `false`가 맵에 존재하지 않는 경우, `true`를 반환합니다. #### Bytes ```typescript -import { Bytes } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'에서 { Bytes }를 입력합니다. ``` -`Bytes` is used to represent arbitrary-length arrays of bytes. This includes Ethereum values of type `bytes`, `bytes32` etc. +`Bytes`는 임의 길이의 바이트 배열을 나타내는 데 사용됩니다. 이는 `bytes`, `bytes32` 등의 이더리움 값을 포함합니다. -The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) and this supports all the `Uint8Array` functionality, plus the following new methods: +`Bytes` 클래스는 AssemblyScript의 [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64)를 확장하며, 모든 `Uint8Array` 기능과 다음과 같은 새 매서드를 지원합니다: -- `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()` – 배열상의 바이트를 나타내는 16진수 문자열을 반환합니다. +- `b.toString()` – 배열상의 바이트를 유니코드 문자 문자열로 변환합니다. +- `b.toBase58()` – 이더리움 바이트 값을 base58 인코딩(IPFS 해시에 사용)으로 변환합니다. #### Address ```typescript -import { Address } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'에서 { Address } 를 입력합니다. ``` -`Address` extends `Bytes` to represent Ethereum `address` values. +`Address`는 `Bytes`를 확장하여 이더리움 `address` 값을 나타냅니다. -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.fromString(s: string): Address` – 16진수 문자열에서 `Address` 를 생성합니다. ### Store API ```typescript -import { store } from '@graphprotocol/graph-ts' +'@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` 유형의 서브 클래스인 엔터티 클래스를 생성하며, 스키마의 필드에 대한 속성 getter 및 setter와 이러한 엔티티를 로드 및 저장하는 메서드를 사용합니다. #### Creating entities -The following is a common pattern for creating entities from Ethereum events. +다음은 이더리움 이벤트에서 엔티티를 생성하기 위한 일반적인 패턴입니다. ```typescript // Import the Transfer event class generated from the ERC20 ABI @@ -241,13 +241,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로 사용하여 엔티티를 만들지 않는다고 가정합니다. -#### Loading entities from the store +#### 스토어에서 엔티티 로드 -If an entity already exists, it can be loaded from the store with the following: +엔티티가 이미 존재하는 경우, 이는 다음을 사용하여 스토어에서 로드할 수 있습니다. ```typescript let id = event.transaction.hash.toHex() // or however the ID is constructed @@ -259,18 +259,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:** Loading entities is only necessary if the changes made in the mapping depend on the previous data of an entity. See the next section for the two ways of updating existing entities. +> **Note:**: 매핑에서 변경한 내용이 엔티티의 이전 데이터에 종속된 경우에만 엔티티 로드가 필요합니다. 다음 섹션에서 기존 엔티티들을 업데이트하는 두 가지 방법을 확인하시기 바랍니다. -#### Updating existing entities +#### 기존 엔티티 업데이트 -There are two ways to update an existing entity: +기존 엔티티를 업데이트 하는 방법에는 두 가지가 있습니다. -1. Load the entity with e.g. `Transfer.load(id)`, set properties on the entity, then `.save()` it back to the store. -2. Simply create the entity with e.g. `new Transfer(id)`, set properties on the entity, then `.save()` it to the store. If the entity already exists, the changes are merged into it. +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) @@ -279,51 +279,51 @@ transfer.to = ... transfer.amount = ... ``` -It is also possible to unset properties with one of the following two instructions: +다음 두 가지 지침 중 하나로 속성을 설정 해제할 수도 있습니다. ```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 +// 이는 작동하지 않을 것입니다. entity.numbers.push(BigInt.fromI32(1)) entity.save() -// This will work +// 이는 작동 할 것입니다. let numbers = entity.numbers numbers.push(BigInt.fromI32(1)) entity.numbers = numbers entity.save() ``` -#### Removing entities from the 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`: +현재 생성된 유형을 통해 엔티티를 제거할 수 있는 방법은 없습니다. 대신 엔티티를 제거하려면 엔티티 유형의 이름과 엔티티 ID를 `store.remove`에 전달해야 합니다. ```typescript -import { store } from '@graphprotocol/graph-ts' +'@graphprotocol/graph-ts'에서 { store }를 입력합니다. ... let id = event.transaction.hash.toHex() store.remove('Transfer', id) ``` -### Ethereum API +### 이더리움 API -The Ethereum API provides access to smart contracts, public state variables, contract functions, events, transactions, blocks and the encoding/decoding Ethereum data. +이더리움 API는 스마트 컨트렉트, 퍼블릭 상태 변수, 컨트렉트 기능, 이벤트, 트랜잭션, 블록 및 이더리움 데이터 인코딩/디코딩에 대한 액세스를 제공합니다. -#### Support for Ethereum Types +#### 이더리움 유형 지원 -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. +생성된 클래스를 사용하면 이더리움 유형과 [내장 유형](#built-in-types) 간의 변환이 뒤에서 이루어지므로 서브그래프 작성자는 이에 대해 걱정할 필요가 없습니다. -The following example illustrates this. Given a subgraph schema like +다음의 예가 이를 보여줍니다. 다음과 같은 서브그래프 스키마가 주어지면 ```graphql type Transfer @entity { @@ -333,7 +333,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: +그리고 이더리움 상의 `Transfer(address,address,uint256)` 이벤트 서명, `from`, `to` 및 `amount` 유형 값 `address`, `address` 그리고 `uint256`는 `Address` 및 `BigInt`로 변환되고, `Bytes!` 및 `Transfer` 엔티티의 `BigInt!` 속성에 전달됩니다: ```typescript let id = event.transaction.hash.toHex() @@ -344,9 +344,9 @@ transfer.amount = event.params.amount transfer.save() ``` -#### Events and Block/Transaction Data +#### 이벤트 및 블록/트랜젝션 데이터 -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` 이벤트에 대해 설명한 바와 같이, 이벤트 핸들로들에게 전달된 이더리움 이벤트들은 이벤트 매개변수에 엑세스를 제공할 뿐만 아니라 상위 트랜잭션과 이벤트 핸들러가 속한 블록에 대한 액세스를 제공합니다. 다음의 데이터는 이벤트 인스턴스(이러한 클래스들은 `graph-ts`의 `ethereum` 모듈의 일부입니다)에서 얻을 수 있습니다: ```typescript class Event { @@ -646,9 +646,9 @@ When the type of a value is certain, it can be converted to a [built-in type](#b - `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` - (이후 `JSONValue`를 상기 5개 방법 중 하나로 변환합니다.) -### Type Conversions Reference +### 유형 변환 참조 | Source(s) | Destination | Conversion function | | -------------------- | -------------------- | ---------------------------- | @@ -688,17 +688,17 @@ When the type of a value is certain, it can be converted to a [built-in type](#b | String (hexadecimal) | Bytes | ByteArray.fromHexString(s) | | String (UTF-8) | Bytes | ByteArray.fromUTF8(s) | -### Data Source Metadata +### 데이터 소스 메타데이터 -You can inspect the contract address, network and context of the data source that invoked the handler through the `dataSource` namespace: +`dataSource` 네임스페이스를 통해 핸들러를 호출한 데이터 소스의 계약 주소, 네트워크 및 컨텍스트를 검사할 수 있습니다 - `dataSource.address(): Address` - `dataSource.network(): string` - `dataSource.context(): DataSourceContext` -### Entity and DataSourceContext +### 엔티티 및 Entity and DataSourceContext -The base `Entity` class and the child `DataSourceContext` class have helpers to dynamically set and get fields: +기본 `Entity` 클래스 및 child `DataSourceContext`는 필드를 동적으로 설정하고 필드를 가져오는 도우미가 있습니다. - `setString(key: string, value: string): void` - `setI32(key: string, value: i32): void` diff --git a/pages/ko/developer/assemblyscript-migration-guide.mdx b/pages/ko/developer/assemblyscript-migration-guide.mdx index c63a1af95d7b..2db90a608110 100644 --- a/pages/ko/developer/assemblyscript-migration-guide.mdx +++ b/pages/ko/developer/assemblyscript-migration-guide.mdx @@ -127,11 +127,8 @@ ERROR TS2451: Cannot redeclare block-scoped variable 'a' ~~~~~~~~~~~~~ in assembly/index.ts(4,3) ``` - You'll need to rename your duplicate variables if you had variable shadowing. - ### Null Comparisons - By doing the upgrade on your subgraph, sometimes you might get errors like these: ```typescript @@ -140,7 +137,6 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i ~~~~ in src/mappings/file.ts(41,21) ``` - To solve you can simply change the `if` statement to something like this: ```typescript @@ -285,7 +281,6 @@ ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/s let somethingOrElse: string = container.data ? container.data : "else"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` - To fix this issue, you can create a variable for that property access so that the compiler can do the nullability check magic: ```typescript diff --git a/pages/ko/developer/create-subgraph-hosted.mdx b/pages/ko/developer/create-subgraph-hosted.mdx index 3b05b2548456..6b235e379634 100644 --- a/pages/ko/developer/create-subgraph-hosted.mdx +++ b/pages/ko/developer/create-subgraph-hosted.mdx @@ -218,15 +218,15 @@ Each entity must have an `id` field, which is of type `ID!` (string). The `id` f We support the following scalars in our GraphQL API: -| Type | Description | -| --- | --- | -| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | -| `ID` | Stored as a `string`. | -| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | -| `Boolean` | Scalar for `boolean` values. | -| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | -| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | -| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | +| Type | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | +| `ID` | Stored as a `string`. | +| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | +| `Boolean` | Scalar for `boolean` values. | +| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | +| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | +| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | #### Enums @@ -627,7 +627,7 @@ export function handleNewExchange(event: NewExchange): void { ``` > **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks. -> +> > If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created. ### Data Source Context @@ -684,7 +684,7 @@ dataSources: ``` > **Note:** The contract creation block can be quickly looked up on Etherscan: -> +> > 1. Search for the contract by entering its address in the search bar. > 2. Click on the creation transaction hash in the `Contract Creator` section. > 3. Load the transaction details page where you'll find the start block for that contract. diff --git a/pages/ko/developer/graphql-api.mdx b/pages/ko/developer/graphql-api.mdx index 65928d8734e0..f9cb6214fcd9 100644 --- a/pages/ko/developer/graphql-api.mdx +++ b/pages/ko/developer/graphql-api.mdx @@ -204,12 +204,12 @@ Fulltext search queries have one required field, `text`, for supplying search te Fulltext search operators: -| Symbol | Operator | Description | -| --- | --- | --- | -| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | -| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | -| `<->` | `Follow by` | Specify the distance between two words. | -| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | +| Symbol | Operator | Description | +| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | +| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | +| `<->` | `Follow by` | Specify the distance between two words. | +| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | #### Examples diff --git a/pages/ko/explorer.mdx b/pages/ko/explorer.mdx index 7132fa01731d..816139ae9a58 100644 --- a/pages/ko/explorer.mdx +++ b/pages/ko/explorer.mdx @@ -11,7 +11,7 @@ title: 탐색기 title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> ## 서브그래프 diff --git a/pages/ko/hosted-service/migrating-subgraph.mdx b/pages/ko/hosted-service/migrating-subgraph.mdx index 3456b4f166e4..260f084c0e7d 100644 --- a/pages/ko/hosted-service/migrating-subgraph.mdx +++ b/pages/ko/hosted-service/migrating-subgraph.mdx @@ -2,7 +2,7 @@ title: Migrating an Existing Subgraph to The Graph Network --- -## Introduction +## 소개 This is a guide for the migration of subgraphs from the Hosted Service (also known as 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. @@ -142,7 +142,7 @@ If you're still confused, fear not! Check out the following resources or watch o title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> - [The Graph Network Contracts](https://github.com/graphprotocol/contracts) diff --git a/pages/ko/indexing.mdx b/pages/ko/indexing.mdx index 1f6508d99ced..7485645acff9 100644 --- a/pages/ko/indexing.mdx +++ b/pages/ko/indexing.mdx @@ -114,12 +114,12 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute - **Medium** - 100개의 Subgraph 및 초당 200 - 500개의 요청을 서포트 할 수 있는 프로덕션 인덱서입니다. - **Large** - 현재 사용되는 모든 서브그래프들 및 관련 트레픽 요청의 처리에 대한 요건을 충족합니다. -| Setup | (CPUs) | (memory in GB) | (disk in TBs) | (CPUs) | (memory in GB) | -| -------- | :----: | :------------: | :-----------: | :----: | :------------: | -| Small | 4 | 8 | 1 | 4 | 16 | -| Standard | 8 | 30 | 1 | 12 | 48 | -| Medium | 16 | 64 | 2 | 32 | 64 | -| Large | 72 | 468 | 3.5 | 48 | 184 | +| Setup | Postgres
(CPUs) | Postgres
(memory in GBs) | Postgres
(disk in TBs) | VMs
(CPUs) | VMs
(memory in GBs) | +| -------- |:--------------------------:|:-----------------------------------:|:---------------------------------:|:---------------------:|:------------------------------:| +| Small | 4 | 8 | 1 | 4 | 16 | +| Standard | 8 | 30 | 1 | 12 | 48 | +| Medium | 16 | 64 | 2 | 32 | 64 | +| Large | 72 | 468 | 3.5 | 48 | 184 | ### 인덱서가 취해야 할 기본적인 보안 예방 조치는 무엇인가요? @@ -149,20 +149,20 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute #### 그래프 노드 -| Port | Purpose | Routes | CLI Argument | Environment Variable | -| --- | --- | --- | --- | --- | -| 8000 | GraphQL HTTP server
(for subgraph queries) | /subgraphs/id/...

/subgraphs/name/.../... | --http-port | - | -| 8001 | GraphQL WS
(for subgraph subscriptions) | /subgraphs/id/...

/subgraphs/name/.../... | --ws-port | - | -| 8020 | JSON-RPC
(for managing deployments) | / | --admin-port | - | -| 8030 | Subgraph indexing status API | /graphql | --index-node-port | - | -| 8040 | Prometheus metrics | /metrics | --metrics-port | - | +| Port | Purpose | Routes | CLI Argument | Environment Variable | +| ---- | ------------------------------------------------------- | ---------------------------------------------------- | ----------------- | -------------------- | +| 8000 | GraphQL HTTP server
(for subgraph queries) | /subgraphs/id/...
/subgraphs/name/.../... | --http-port | - | +| 8001 | GraphQL WS
(for subgraph subscriptions) | /subgraphs/id/...
/subgraphs/name/.../... | --ws-port | - | +| 8020 | JSON-RPC
(for managing deployments) | / | --admin-port | - | +| 8030 | Subgraph indexing status API | /graphql | --index-node-port | - | +| 8040 | Prometheus metrics | /metrics | --metrics-port | - | #### Indexer Service -| Port | Purpose | Routes | CLI Argument | Environment Variable | -| --- | --- | --- | --- | --- | -| 7600 | GraphQL HTTP server
(for paid subgraph queries) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | -| 7300 | Prometheus metrics | /metrics | --metrics-port | - | +| Port | Purpose | Routes | CLI Argument | Environment Variable | +| ---- | ------------------------------------------------------------ | ----------------------------------------------------------------------- | -------------- | ---------------------- | +| 7600 | GraphQL HTTP server
(for paid subgraph queries) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | +| 7300 | Prometheus metrics | /metrics | --metrics-port | - | #### Indexer Agent @@ -243,7 +243,8 @@ gcloud compute addresses create google-managed-services-default \ --purpose=VPC_PEERING \ --network default \ --global \ - --description 'IP Range for peer networks.' gcloud services vpc-peerings connect \ + --description 'IP Range for peer networks.' +gcloud services vpc-peerings connect \ --network=default \ --ranges=google-managed-services-default ``` diff --git a/pages/ko/studio/billing.mdx b/pages/ko/studio/billing.mdx index e909da9cd1e1..4788124913d9 100644 --- a/pages/ko/studio/billing.mdx +++ b/pages/ko/studio/billing.mdx @@ -2,7 +2,7 @@ title: Billing on the Subgraph Studio --- -### Overview +### 개요 Invoices are statements of payment amounts owed by a customer and are typically generated on a weekly basis in the system. You’ll be required to pay fees based on the query fees you generate using your API keys. The billing contract lives on the [Polygon](https://polygon.technology/) network. It’ll allow you to: @@ -46,7 +46,7 @@ For a quick demo of how billing works on the Subgraph Studio, check out the vide title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> ### Multisig Users diff --git a/pages/ko/studio/subgraph-studio.mdx b/pages/ko/studio/subgraph-studio.mdx index 492bb376c44b..562d588ef26d 100644 --- a/pages/ko/studio/subgraph-studio.mdx +++ b/pages/ko/studio/subgraph-studio.mdx @@ -73,7 +73,7 @@ You’ve made it this far - congrats! Publishing your subgraph means that an IPF title="YouTubeビデオプレーヤー" frameBorder="0" allowFullScreen - > +> Remember, while you’re going through your publishing flow, you’ll be able to push to either mainnet or Rinkeby, the testnet we support. If you’re a first time subgraph developer, we highly suggest you start with publishing to Rinkeby, which is free to do. This will allow you to see how the subgraph will work in The Graph Explorer and will allow you to test curation elements. diff --git a/pages/vi/about/introduction.mdx b/pages/vi/about/introduction.mdx new file mode 100644 index 000000000000..5f840c040400 --- /dev/null +++ b/pages/vi/about/introduction.mdx @@ -0,0 +1,47 @@ +--- +title: Introduction +--- + +This page will explain what The Graph is and how you can get started. + +## What The Graph Is + +The Graph is a decentralized protocol for indexing and querying data from blockchains, starting with Ethereum. It makes it possible to query data that is difficult to query directly. + +Projects with complex smart contracts like [Uniswap](https://uniswap.org/) and NFTs initiatives like [Bored Ape Yacht Club](https://boredapeyachtclub.com/) store data on the Ethereum blockchain, making it really difficult to read anything other than basic data directly from the blockchain. + +In the case of Bored Ape Yacht Club, we can perform basic read operations on [the contract](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) like getting the owner of a certain Ape, getting the content URI of an Ape based on their ID, or the total supply, as these read operations are programmed directly into the smart contract, but more advanced real-world queries and operations like aggregation, search, relationships, and non-trivial filtering are not possible. For example, if we wanted to query for apes that are owned by a certain address, and filter by one of its characteristics, we would not be able to get that information by interacting directly with the contract itself. + +To get this data, you would have to process every single [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) event ever emitted, read the metadata from IPFS using the Token ID and IPFS hash, and then aggregate it. Even for these types of relatively simple questions, it would take **hours or even days** for a decentralized application (dapp) running in a browser to get an answer. + +You could also build out your own server, process the transactions there, save them to a database, and build an API endpoint on top of it all in order to query the data. However, this option is resource intensive, needs maintenance, presents a single point of failure, and breaks important security properties required for decentralization. + +**Indexing blockchain data is really, really hard.** + +Blockchain properties like finality, chain reorganizations, or uncled blocks complicate this process further, and make it not just time consuming but conceptually hard to retrieve correct query results from blockchain data. + +The Graph solves this with a decentralized protocol that indexes and enables the performant and efficient querying of blockchain data. These APIs (indexed "subgraphs") can then be queried with a standard GraphQL API. Today, there is a hosted service as well as a decentralized protocol with the same capabilities. Both are backed by the open source implementation of [Graph Node](https://github.com/graphprotocol/graph-node). + +## How The Graph Works + +The Graph learns what and how to index Ethereum data based on subgraph descriptions, known as the subgraph manifest. The subgraph description defines the smart contracts of interest for a subgraph, the events in those contracts to pay attention to, and how to map event data to data that The Graph will store in its database. + +Once you have written a `subgraph manifest`, you use the Graph CLI to store the definition in IPFS and tell the indexer to start indexing data for that subgraph. + +This diagram gives more detail about the flow of data once a subgraph manifest has been deployed, dealing with Ethereum transactions: + +![](/img/graph-dataflow.png) + +The flow follows these steps: + +1. A decentralized application adds data to Ethereum through a transaction on a smart contract. +2. The smart contract emits one or more events while processing the transaction. +3. Graph Node continually scans Ethereum for new blocks and the data for your subgraph they may contain. +4. Graph Node finds Ethereum events for your subgraph in these blocks and runs the mapping handlers you provided. The mapping is a WASM module that creates or updates the data entities that Graph Node stores in response to Ethereum events. +5. The decentralized application queries the Graph Node for data indexed from the blockchain, using the node's [GraphQL endpoint](https://graphql.org/learn/). The Graph Node in turn translates the GraphQL queries into queries for its underlying data store in order to fetch this data, making use of the store's indexing capabilities. The decentralized application displays this data in a rich UI for end-users, which they use to issue new transactions on Ethereum. The cycle repeats. + +## Next Steps + +In the following sections we will go into more detail on how to define subgraphs, how to deploy them, and how to query data from the indexes that Graph Node builds. + +Before you start writing your own subgraph, you might want to have a look at the Graph Explorer and explore some of the subgraphs that have already been deployed. The page for each subgraph contains a playground that lets you query that subgraph's data with GraphQL. diff --git a/pages/vi/about/network.mdx b/pages/vi/about/network.mdx new file mode 100644 index 000000000000..b19f08d12bc7 --- /dev/null +++ b/pages/vi/about/network.mdx @@ -0,0 +1,15 @@ +--- +title: Network Overview +--- + +The Graph Network is a decentralized indexing protocol for organizing blockchain data. Applications use GraphQL to query open APIs called subgraphs, to retrieve data that is indexed on the network. With The Graph, developers can build serverless applications that run entirely on public infrastructure. + +> GRT Token Address: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) + +## Overview + +The Graph Network consists of Indexers, Curators and Delegators that provide services to the network, and serve data to Web3 applications. Consumers use the applications and consume the data. + +![Token Economics](/img/Network-roles@2x.png) + +To ensure economic security of The Graph Network and the integrity of data being queried, participants stake and use Graph Tokens (GRT). GRT is a work token that is an ERC-20 on the Ethereum blockchain, used to allocate resources in the network. Active Indexers, Curators and Delegators can provide services and earn income from the network, proportional to the amount of work they perform and their GRT stake. diff --git a/pages/vi/curating.mdx b/pages/vi/curating.mdx new file mode 100644 index 000000000000..626dfc2e1872 --- /dev/null +++ b/pages/vi/curating.mdx @@ -0,0 +1,131 @@ +--- +title: Curator +--- + +Curators rất quan trọng đối với nền kinh tế phi tập trung The Graph. Họ sử dụng kiến thức của mình về hệ sinh thái web3 để đánh giá và báo hiệu trên các subgraph cần được lập chỉ mục bởi Mạng The Graph. Thông qua Explorer, curator có thể xem dữ liệu mạng để đưa ra quyết định báo hiệu. Mạng The Graph thưởng cho những curator báo hiệu trên các subgraph chất lượng tốt sẽ kiếm được một phần phí truy vấn mà các subgraph tạo ra. Curator được khuyến khích về mặt kinh tế để phát tín hiệu sớm. Những tín hiệu này từ curator rất quan trọng đối với Indexer, những người này sau đó có thể xử lý hoặc lập chỉ mục dữ liệu từ các subgraph được báo hiệu này. + +Khi phát tín hiệu, người phụ trách có thể quyết định báo hiệu trên một phiên bản cụ thể của subgraph hoặc báo hiệu bằng tính năng tự động di chuyển. Khi báo hiệu bằng cách sử dụng tính năng tự động di chuyển, cổ phần của curator sẽ luôn được nâng cấp lên phiên bản mới nhất do nhà phát triển xuất bản. Nếu thay vào đó bạn quyết định báo hiệu trên một phiên bản cụ thể, cổ phần của bạn sẽ luôn ở trên phiên bản cụ thể này. + +Hãy nhớ rằng việc curate là rất rủi ro. Hãy thẩm định kỹ càng trong khả năng của bạn để đảm bảo rằng bạn đang curate các subgraph mà bạn tin tưởng. Việc tạo một subgraph là không cần cấp phép, vì vậy mọi người có thể tạo các subgraph và gọi chúng bằng bất kỳ tên nào họ muốn. Để biết thêm hướng dẫn về rủi ro khi curate, hãy xem [Hướng dẫn curate của Graph Academy.](https://thegraph.academy/curators/) + +## Căn bản về Bonding Curve + +Đầu tiên chúng ta lùi lại một bước trước. Mỗi subgraph có một bonding curve (đường cong liên kết) mà trên đó các cổ phần curate được tạo ra, khi người dùng thêm tín hiệu **vào** đường cong. Đường cong liên kết của mỗi subgraph là độc nhất. Các đường cong liên kết được cấu trúc để giá để đúc ra một cổ phẩn curate trên một subgraph tăng tuyến tính, so với số lượng cổ phần được đúc. + +![Giá mỗi cổ phần](/img/price-per-share.png) + +Kết quả là, giá tăng tuyến tính, có nghĩa là giá mua cổ phần sẽ đắt hơn theo thời gian. Dưới đây là một ví dụ về ý của chúng tôi, hãy xem đường cong liên kết bên dưới: + +![Đường cong liên kết](/img/bonding-curve.png) + +Hãy xem xét chúng ta có hai người curator cùng đúc cổ phần của một subgraph: + +- Curator A là người đầu tiên phát tín hiệu trên subgraph này. Bằng cách thêm 120,000 GRT vào đường cong, anh ấy có thể kiếm được 2000 cổ phần. +- Tín hiệu của người curator B xuất hiện trên subgraph vào một thời điểm nào đó sau đó. Để nhận được cùng một lượng cổ phần như người curator A, thì B sẽ phải thêm 360,000 GRT vào đường cong. +- Vì cả hai người curator này đều nắm giữ một nửa tổng số cổ phần curate, họ sẽ nhận được một số tiền bản quyền của curator bằng nhau. +- Nếu bây giờ bất kỳ 1 trong 2 người đốt 2000 cổ phần curate của họ, họ sẽ nhận được 360,000 GRT. +- Người curator còn lại bây giờ sẽ nhận được tất cả tiền bản quyền của curator cho subgraph đó. Nếu đốt cổ phần để rút GRT, anh ấy sẽ nhận được 120,000 GRT. +- **Tóm tắt:** Định giá theo GRT của cổ phần curate được xác định bởi đường cong liên kết và có thể biến động. Có khả năng thua lỗ lớn. Báo hiệu sớm có nghĩa là bạn đặt vào ít GRT hơn cho mỗi cổ phần. Hiểu rộng ra, điều này có nghĩa là bạn kiếm được nhiều tiền bản quyền của curator hơn trên mỗi GRT so với những curator sau này cho cùng một subgraph. + +Nói chung, đường cong liên kết là một đường cong toán học xác định mối quan hệ giữa lượng cung token và giá tài sản. Trong trường hợp cụ thể của việc curate subgraph, **giá của mỗi cổ phần subgraph tăng lên với mỗi token được đầu tư** và **giá của mỗi cổ phần giảm xuống với mỗi token được bán.** + +Trong trường hợp của The Graph, [Triển khai của Bancor về công thức đường cong liên kết](https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA) được sử dụng. + +## Làm thế nào để phát tín hiệu + +Đến hiện giờ chúng ta đã trình bày những kiến thức cơ bản về cách hoạt động của đường cong liên kết, đây là cách bạn sẽ tiến hành phát tín hiệu trên một subgraph. Trong thẻ Curator trên Graph Explorer, các curator sẽ có thể báo hiệu và hủy báo hiệu trên một số subgraph nhất định dựa trên số liệu thống kê mạng. Để biết tổng quan từng bước về cách thực hiện việc này trong Explorer, [nhấp vào đây.](https://thegraph.com/docs/explorer) + +Curator có thể chọn phát tín hiệu trên một phiên bản subgraph cụ thể hoặc họ có thể chọn để tín hiệu của họ tự động chuyển sang bản dựng sản xuất mới nhất của subgraph đó. Cả hai đều là những chiến lược hợp lệ và đi kèm với những ưu và nhược điểm của riêng chúng. + +Báo hiệu trên một phiên bản cụ thể đặc biệt hữu ích khi một subgraph được sử dụng bởi nhiều dapp. Một dapp có thể có nhu cầu thường xuyên cập nhật subgraph với các tính năng mới. Một dapp khác có thể thích sử dụng phiên bản subgraph cũ hơn, đã được thử nghiệm tốt. Trong lần curate đầu, 1 khoản thuế tiêu chuẩn 1% sẽ được tính. + +Việc để tín hiệu của bạn tự động chuyển sang phiên bản sản xuất mới nhất có thể có giá trị để đảm bảo bạn tiếp tục tích lũy phí truy vấn. Mỗi khi bạn curate, bạn sẽ phải chịu một khoản thuế curation 1%. Bạn cũng sẽ phải trả 0.5% thuế curation cho mỗi lần di chuyển. Các nhà phát triển subgraph không được khuyến khích để thường xuyên xuất bản các phiên bản mới - họ phải trả 0.5% thuế curation đối với tất cả các cổ phần curation được di chuyển tự động. + +> **Lưu ý**: Địa chỉ đầu tiên báo hiệu một subgraph cụ thể được coi là người curator đầu tiên và sẽ phải làm công việc tốn nhiều phí gas hơn nhiều so với phần còn lại của những người curator sau vì người curator đầu tiên phải khởi tạo token cổ phần curate, khởi tạo đường cong liên kết và cũng chuyển token vào proxy the Graph. + +## Việc phát tín hiệu có nghĩa là gì đối với Mạng The Graph? + +Để người tiêu dùng cuối có thể truy vấn một subgraph, subgraph đó trước tiên phải được lập chỉ mục. Indexing (Lập chỉ mục) là một quá trình mà các tệp, dữ liệu và siêu dữ liệu được xem xét, lập danh mục và sau đó được lập chỉ mục để có thể tìm thấy kết quả nhanh hơn. Để dữ liệu của một subgraph có thể tìm kiếm được, nó cần được sắp xếp. + +Và do đó, nếu Indexers (Người lập chỉ mục) phải đoán xem họ nên lập chỉ mục những trang con nào, thì khả năng họ sẽ kiếm được phí truy vấn cao là rất thấp bởi vì họ không có cách nào xác thực những subgraph nào có chất lượng tốt. Đây là lúc cần curation. + +Curators làm cho mạng The Graph trở nên hiệu quả và báo hiệu là quá trình mà curator sử dụng để cho Indexer biết rằng một subgraph là tốt để lập chỉ mục, trong đó GRT được thêm vào đường cong liên kết cho subgraph. Indexer có thể tin tưởng vào tín hiệu từ curator bởi vì khi phát tín hiệu, curator sẽ đúc ra một cổ phần curate cho subgraph đó, cho phép họ hưởng một phần phí truy vấn trong tương lai mà subgraph này thu được. Tín hiệu của curator được biểu diễn dưới dạng token ERC20 được gọi là Graph Curation Shares (GCS). Những curator muốn kiếm thêm phí truy vấn nên báo hiệu GRT của họ đến các subgraph mà họ dự đoán sẽ tạo ra một luồng phí mạnh cho mạng. Curator không thể bị phạt giảm tài sản vì hành vi xấu, nhưng có một khoản thuế nạp tiền đối với curator để ngăn chặn việc đưa ra quyết định kém có thể làm tổn hại đến tính toàn vẹn của mạng. Curator cũng kiếm được ít phí truy vấn hơn nếu họ chọn quản lý trên một subgraph chất lượng thấp, vì sẽ có ít truy vấn hơn để xử lý hoặc ít Indexer xử lý các truy vấn đó. Xem sơ đồ bên dưới! + +![Sơ đồ báo hiệu](/img/curator-signaling.png) + +Indexer có thể tìm các subgraph để lập chỉ mục dựa trên các tín hiệu sắp xếp mà họ thấy trong Graph Explorer (ảnh chụp màn hình bên dưới). + +![Trình khám phá subgraph](/img/explorer-subgraphs.png) + +## Những rủi ro + +
    +
  1. + Thị trường truy vấn vốn còn sơ khai tại The Graph và có rủi ro rằng mức tỉ suất lợi nhuận năm (%APY) của bạn có thể + thấp hơn mức bạn mong đợi do các động lực thị trường non trẻ. +
  2. +
  3. + Phí Curation - khi người phụ trách báo hiệu GRT trên một subgraph, họ phải chịu 1% thuế curation. Phí này được đốt + và phần còn lại được gửi vào nguồn cung dự trữ của đường liên kết. +
  4. +
  5. + Khi curator đốt cổ phần của họ để rút GRT ra, giá trị GRT của số cổ phần còn lại sẽ bị giảm. Hãy lưu ý rằng trong + một số trường hợp, n curator có thể quyết định đốt cổ phẩn của họ tất cả cùng một lúc. Tình huống này có thể + phổ biến nếu một nhà phát triển dapp ngừng lập phiên bản/cải tiến và truy vấn subgraph của họ hoặc nếu một subgraph + thất bại. Kết quả là, những curator còn lại có thể chỉ rút được một phần GRT ban đầu của họ. Đối với một vai trò + mạng với rủi ro thấp hơn, xem [Delegators](https://thegraph.com/docs/delegating). +
  6. +
  7. + Một subgraph có thể thất bại do một lỗi. Một subgraph thất bại không tích lũy phí truy vấn. Do đó, bạn sẽ phải đợi + cho đến khi nhà phát triển sửa lỗi và triển khai phiên bản mới. +
      +
    • + Nếu bạn đã đăng ký phiên bản mới nhất của một subgraph, các cổ phần của bạn sẽ tự động chuyển sang phiên bản mới + đó. Điều này sẽ phát sinh một khoản thuế curation 0.5%. +
    • +
    • + Nếu bạn đã báo hiệu trên một phiên bản subgraph cụ thể và nó không thành công, bạn sẽ phải đốt phần cổ phần + curation của bạn theo cách thủ công. Lưu ý rằng bạn có thể nhận được nhiều hơn hoặc ít hơn GRT so với số tiền + bạn gửi ban đầu vào đường cong curation, đây là một rủi ro của việc trở thành curator. You can then signal on + the new subgraph version, thus incurring a 1% curation tax. +
    • +
    +
  8. +
+ +## Câu hỏi thường gặp về Curation + +### 1. Curator kiếm được bao nhiêu % phí truy vấn? + +Bằng cách báo hiệu trên một subgraph, bạn sẽ kiếm được một phần của tất cả phí truy vấn mà subgraph này tạo ra. 10% của tất cả các khoản phí truy vấn sẽ được chuyển cho các Curator theo tỷ lệ đối với cổ phần curation của họ. Tỉ lệ 10% này là tùy thuộc vào quản trị. + +### 2. Làm cách nào để tôi quyết định xem các subgraph nào có chất lượng cao để báo hiệu? + +Tìm kiếm subgraph chất lượng cao là một nhiệm vụ phức tạp, nhưng nó có thể được tiếp cận theo nhiều cách khác nhau. Với tư cách là curator, bạn muốn tìm kiếm các subgraph đáng tin cậy đang thúc đẩy khối lượng truy vấn. Một subgraph đáng tin cậy có thể có giá trị nếu nó đầy đủ, chính xác và hỗ trợ nhu cầu dữ liệu của dapp. Một trang con có cấu trúc kém có thể cần được sửa đổi hoặc xuất bản lại và cũng có thể cuối cùng là thất bại. Curator cần xem xét kiến trúc hoặc mã lập trình của một subgraph để đánh giá xem nó có giá trị hay không. Kết quả là: + +- Curator có thể sử dụng sự hiểu biết của họ về mạng để thử và dự đoán cách một subgraph riêng lẻ có thể tạo ra khối lượng truy vấn cao hơn hoặc thấp hơn trong tương lai +- Curator cũng nên hiểu các số liệu có sẵn thông qua Graph Explorer. Các chỉ số như khối lượng truy vấn trong quá khứ và nhà phát triển subgraph là ai có thể giúp xác định xem một subgraph có đáng để báo hiệu hay không. + +### 3. Chi phí nâng cấp một subgraph là bao nhiêu? + +Việc di chuyển các cổ phần curation của bạn sang một phiên bản subgraph mới sẽ phát sinh thuế curation là 1%. Curator có thể chọn đăng ký phiên bản mới nhất của subgraph. Khi cổ phần của người curator được tự động chuyển sang phiên bản mới, Curator cũng sẽ phải trả một nửa thuế curation, là 0.5%, bởi vì việc nâng cấp các subgraph là một hành động trên trên gây tốn phí gas. + +### 4. Tôi có thể nâng cấp subgraph của mình bao lâu một lần? + +Chúng tôi khuyên bạn không nên nâng cấp các subgraph của mình quá thường xuyên. Xem câu hỏi ở trên để biết thêm chi tiết. + +### 5. Tôi có thể bán cổ phần curation của mình không? + +Cổ phần curation không thể được "mua" hoặc "bán" như các token ERC20 khác mà bạn có thể quen thuộc. Chúng chỉ có thể được đúc (tạo) hoặc đốt (hủy) dọc theo đường cong liên kết cho một subgraph cụ thể. Lượng GRT cần thiết để tạo ra tín hiệu mới và lượng GRT bạn nhận được khi đốt tín hiệu hiện có, được xác định bởi đường cong liên kết đó. Là một curator, bạn cần biết rằng khi đốt cổ phần curation của mình để rút GRT, bạn có thể nhận được nhiều hơn hoặc ít hơn GRT so với số tiền bạn đã gửi ban đầu. + +Vẫn còn thắc mắc? Xem video hướng dẫn Curation của chúng tôi bên dưới: + +
+ +
diff --git a/pages/vi/delegating.mdx b/pages/vi/delegating.mdx new file mode 100644 index 000000000000..caa911c5c7ad --- /dev/null +++ b/pages/vi/delegating.mdx @@ -0,0 +1,94 @@ +--- +title: Delegator +--- + +Delegator (Người ủy quyền) không bị phạt cắt tài sản (slash) vì hành vi xấu, nhưng có một khoản thuế đặt cọc đối với Delegator để ngăn cản việc đưa ra quyết định kém có thể làm tổn hại đến tính toàn vẹn của mạng. + +## Hướng dẫn Delegator + +This guide will explain how to be an effective delegator in the Graph Network. Delegators share earnings of the protocol alongside all indexers on their delegated stake. A Delegator must use their best judgement to choose Indexers based on multiple factors. Please note this guide will not go over steps such as setting up Metamask properly, as that information is widely available on the internet. There are three sections in this guide: + +- Rủi ro của việc ủy quyền token trong Mạng The Graph +- Cách tính lợi nhuận kỳ vọng với tư cách là delegator +- Hướng dẫn bằng video hiển thị các bước để ủy quyền trong Giao diện người dùng Mạng The Graph + +## Rủi ro Ủy quyền + +Dưới đây là những rủi ro chính của việc trở thành delegator trong giao thức. + +### Phí ủy quyền + +Lưu ý quan trọng là mỗi lần bạn ủy quyền, bạn sẽ bị tính phí 0.5%. Nghĩa là nếu bạn đang ủy quyền 1000 GRT, bạn sẽ tự động đốt 5 GRT. + +Nên là, để an toàn, Delegator nên tính toán trước lợi nhuận của họ sẽ như thế nào khi ủy quyền cho Indexer. Ví dụ: Delegator có thể tính toán xem sẽ mất bao nhiêu ngày trước khi họ kiếm lại bù được phần thuế đặt cọc 0.5% cho việc ủy quyền của họ. + +### Khoảng thời gian bỏ ràng buộc ủy quyền + +Bất cứ khi nào Delegator muốn hủy ủy quyền, token của họ phải chịu khoảng thời gian 28 ngày bỏ ràng buộc ủy quyền. Điều này có nghĩa là họ không thể chuyển token của mình hoặc kiếm bất kỳ phần thưởng nào trong 28 ngày. + +Một điều nữa cũng cần xem xét là lựa chọn Indexer một cách khôn ngoan. Nếu bạn chọn một Indexer không đáng tin cậy hoặc không hoàn thành tốt công việc, bạn sẽ muốn hủy ủy quyền, khi đó bạn sẽ mất rất nhiều cơ hội kiếm được phần thưởng, cũng tệ như việc đốt đi GRT vậy. + +
+ ![Delegation unbonding](/img/Delegation-Unbonding.png) Lưu ý khoản phí 0.5% trong Giao diện người dùng Ủy quyền, cũng + như khoảng thời gian 28 ngày bỏ ràng buộc ủy quyền. +
+ +### Chọn một indexer đáng tin cậy với phần thưởng hợp lý cho delegator + +Đây là một phần quan trọng cần hiểu. Đầu tiên chúng ta hãy thảo luận về ba giá trị rất quan trọng, đó là các Tham số Ủy quyền. + +Phần cắt Thưởng Indexing - Phần cắt thưởng indexing là phần mà Indexer sẽ giữ lại cho họ trong số lượng Thưởng Indexing. Nghĩa là, nếu nó được đặt thành 100%, thì delegator sẽ nhận được 0 phần thưởng indexing. Nếu bạn thấy 80% trong giao diện người dùng, có delegator sẽ nhận được 20%. Một lưu ý quan trọng - trong thời gian đầu của mạng lưới, Thưởng Indexing sẽ chiếm phần lớn trong tổng phần thưởng. + +
+ ![Indexing Reward Cut](/img/Indexing-Reward-Cut.png) Indexer hàng đầu đang trao cho delegator 90% phần thưởng. Những + Indexer tầm trung đang trao cho delegator 20%. Những Indexer dưới cùng đang trao cho delegator khoản 83%. +
+ +- Phần cắt Phí Truy vấn - cũng như Phần cắt Thưởng Indexing. Tuy nhiên, điều này đặc biệt dành cho lợi nhuận từ phí truy vấn mà Indexer thu thập. Cần lưu ý rằng khi bắt đầu mạng, lợi nhuận từ phí truy vấn sẽ rất nhỏ so với phần thưởng indexing. Bạn nên chú ý đến mạng lưới để xác định khi nào phí truy vấn trong mạng sẽ bắt đầu đáng kể hơn. + +Như bạn có thể thấy, có rất nhiều suy nghĩ phải cân nhắc khi lựa chọn Indexer phù hợp. Đây là lý do tại sao chúng tôi thực sự khuyên bạn nên khám phá The Graph Discord để xác định ai là Indexers có danh tiếng xã hội và danh tiếng kỹ thuật tốt nhất, để thưởng cho delegator trên cơ sở nhất quán. Nhiều Indexers rất tích cực trong Discord và sẽ sẵn lòng trả lời câu hỏi của bạn. Nhiều người trong số họ đã Indexing trong nhiều tháng testnet và đang cố gắng hết sức để giúp những các delegator kiếm được lợi nhuận tốt, vì nó cải thiện sức khỏe và sự thành công của mạng. + +### Tính toán lợi nhuận dự kiến của Delegator + +Một Delegator phải xem xét rất nhiều yếu tố khi xác định lợi nhuận. Như là + +- Một Delegator có trình độ kỹ thuật cũng có thể xem xét cách mà Indexer sử dụng các token được Ủy quyền khả dụng cho họ. Nếu một indexer không phân bổ tất cả các token khả dụng, họ sẽ không kiếm được lợi nhuận tối đa mà họ có thể dành cho chính họ hoặc Delegator của họ. +- Ngay bây giờ trong mạng lưới, Indexer có thể chọn đóng phân bổ và nhận phần thưởng bất kỳ lúc nào trong khoảng thời gian từ 1 đến 28 ngày. Vì vậy, có thể một Indexer có rất nhiều phần thưởng mà họ chưa thu thập được, và do đó, tổng phần thưởng của họ thấp. Điều này cần được xem xét từ những ngày đầu. + +### Xem xét Phần cắt Phí Truy vấn và Phần cắt Phí indexing + +Như được mô tả trong các phần trên, bạn nên chọn một Indexer minh bạch và trung thực về việc thiết lập Phần cắt Phí Truy vấn và Phần cắt Phí Indexing của họ. Delegator cũng nên xem thời gian Cooldown (thời gian chờ) của Tham số để xem họ có bao nhiêu bộ đệm thời gian. Sau khi hoàn thành, việc tính toán số lượng phần thưởng mà delegator nhận được khá đơn giản. Công thức là: + +![Ảnh Ủy quyền 3](/img/Delegation-Reward-Formula.png) + +### Xem xét Delegation pool của Indexer + +Một điều khác mà Delegator phải xem xét là tỷ lệ Delegation Pool (Nhóm Ủy quyền) mà họ sở hữu. Tất cả phần thưởng ủy quyền được chia sẻ đồng đều, với một sự tái cân bằng đơn giản của nhóm được xác định bởi số tiền Delegator đã gửi vào pool. Việc này cung cấp cho delegator một phần của pool: + +![Chia sẻ công thức](/img/Share-Forumla.png) + +Sử dụng công thức này, chúng ta có thể thấy rằng một Indexer đang cung cấp chỉ 20% cho Delegator thực sự có thể thực sự trao cho Delegator một phần thưởng thậm chí còn tốt hơn một Indexer đang chia 90% cho Delegator. + +Do đó, Delegator có thể thực hiện phép toán để xác định rằng người Indexer mục cung cấp 20% cho Delegator kia, đang mang lại lợi nhuận tốt hơn. + +### Xem xét Delegation Capacity (Năng lực Ủy quyền) + +Một điều khác cần xem xét là Năng lực Ủy quyền. Hiện tại, Delegation Ratio (Tỷ lệ Ủy quyền) đang được đặt thành 16. Điều này có nghĩa là nếu một Indexer đã stake 1.000.000 GRT, thì Năng lực Ủy quyền của họ là 16.000.000 GRT Token được Ủy quyền mà họ có thể sử dụng trong giao thức. Bất kỳ lượng token được ủy quyền nào vượt quá con số này sẽ làm loãng tất cả phần thưởng Delegator. + +Ví dụ một Indexer có 100.000.000 GRT được ủy quyền cho họ, và năng lực của họ chỉ là 16.000.000 GRT. Điều này nghĩa là 84.000.000 GRT token không được sử dụng để kiếm token. Và toàn bộ Delegator, và cả Indexer, đang kiếm được ít phần thưởng hơn so với mức họ có thể. + +Do đó, delegator phải luôn xem xét Năng lực Ủy quyền của Indexer và cân nhắc nó trong quá trình ra quyết định của họ. + +## Video hướng dẫn cho giao diện người dùng mạng lưới + +Hướng dẫn này cung cấp đánh giá đầy đủ về tài liệu này và cách xem xét mọi thứ trong tài liệu này khi tương tác với giao diện người dùng. + +
+ +
diff --git a/pages/vi/developer/assemblyscript-api.mdx b/pages/vi/developer/assemblyscript-api.mdx new file mode 100644 index 000000000000..b5066fab02f2 --- /dev/null +++ b/pages/vi/developer/assemblyscript-api.mdx @@ -0,0 +1,714 @@ +--- +title: AssemblyScript API +--- + +> Note: if you created a subgraph prior to `graph-cli`/`graph-ts` version `0.22.0`, you're using an older version of AssemblyScript, we recommend taking a look at the [`Migration Guide`](/developer/assemblyscript-migration-guide) + +This page documents what built-in APIs can be used when writing subgraph mappings. Two kinds of APIs are available out of the box: + +- the [Graph TypeScript library](https://github.com/graphprotocol/graph-ts) (`graph-ts`) and +- code generated from subgraph files by `graph codegen`. + +It is also possible to add other libraries as dependencies, as long as they are compatible with [AssemblyScript](https://github.com/AssemblyScript/assemblyscript). Since this is the language mappings are written in, the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki) is a good source for language and standard library features. + +## Installation + +Subgraphs created with [`graph init`](/developer/create-subgraph-hosted) come with preconfigured dependencies. All that is required to install these dependencies is to run one of the following commands: + +```sh +yarn install # Yarn +npm install # NPM +``` + +If the subgraph was created from scratch, one of the following two commands will install the Graph TypeScript library as a dependency: + +```sh +yarn add --dev @graphprotocol/graph-ts # Yarn +npm install --save-dev @graphprotocol/graph-ts # NPM +``` + +## API Reference + +The `@graphprotocol/graph-ts` library provides the following APIs: + +- An `ethereum` API for working with Ethereum smart contracts, events, blocks, transactions, and Ethereum values. +- A `store` API to load and save entities from and to the Graph Node store. +- A `log` API to log messages to the Graph Node output and the Graph Explorer. +- An `ipfs` API to load files from IPFS. +- A `json` API to parse JSON data. +- A `crypto` API to use cryptographic functions. +- Low-level primitives to translate between different type systems such as Ethereum, JSON, GraphQL and AssemblyScript. + +### Versions + +The `apiVersion` in the subgraph manifest specifies the mapping API version which is run by Graph Node for a given subgraph. The current mapping API version is 0.0.6. + +| Version | Release notes | +|:-------:| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | +| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | +| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | +| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | +| 0.0.2 | Added `input` field to the Ethereum Transaction object | + +### Built-in Types + +Documentation on the base types built into AssemblyScript can be found in the [AssemblyScript wiki](https://github.com/AssemblyScript/assemblyscript/wiki/Types). + +The following additional types are provided by `@graphprotocol/graph-ts`. + +#### ByteArray + +```typescript +import { ByteArray } from '@graphprotocol/graph-ts' +``` + +`ByteArray` represents an array of `u8`. + +_Construction_ + +- `fromI32(x: i32): ByteArray` - Decomposes `x` into bytes. +- `fromHexString(hex: string): ByteArray` - Input length must be even. Prefixing with `0x` is optional. + +_Type conversions_ + +- `toHexString(): string` - Converts to a hex string prefixed with `0x`. +- `toString(): string` - Interprets the bytes as a UTF-8 string. +- `toBase58(): string` - Encodes the bytes into a base58 string. +- `toU32(): u32` - Interprets the bytes as a little-endian `u32`. Throws in case of overflow. +- `toI32(): i32` - Interprets the byte array as a little-endian `i32`. Throws in case of overflow. + +_Operators_ + +- `equals(y: ByteArray): bool` – can be written as `x == y`. + +#### BigDecimal + +```typescript +import { BigDecimal } from '@graphprotocol/graph-ts' +``` + +`BigDecimal` is used to represent arbitrary precision decimals. + +_Construction_ + +- `constructor(bigInt: BigInt)` – creates a `BigDecimal` from an `BigInt`. +- `static fromString(s: string): BigDecimal` – parses from a decimal string. + +_Type conversions_ + +- `toString(): string` – prints to a decimal string. + +_Math_ + +- `plus(y: BigDecimal): BigDecimal` – can be written as `x + y`. +- `minus(y: BigDecimal): BigDecimal` – can be written as `x - y`. +- `times(y: BigDecimal): BigDecimal` – can be written as `x * y`. +- `div(y: BigDecimal): BigDecimal` – can be written as `x / y`. +- `equals(y: BigDecimal): bool` – can be written as `x == y`. +- `notEqual(y: BigDecimal): bool` – can be written as `x != y`. +- `lt(y: BigDecimal): bool` – can be written as `x < y`. +- `le(y: BigDecimal): bool` – can be written as `x <= y`. +- `gt(y: BigDecimal): bool` – can be written as `x > y`. +- `ge(y: BigDecimal): bool` – can be written as `x >= y`. +- `neg(): BigDecimal` - can be written as `-x`. + +#### BigInt + +```typescript +import { BigInt } from '@graphprotocol/graph-ts' +``` + +`BigInt` is used to represent big integers. This includes Ethereum values of type `uint32` to `uint256` and `int64` to `int256`. Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. + +The `BigInt` class has the following API: + +_Construction_ + +- `BigInt.fromI32(x: i32): BigInt` – creates a `BigInt` from an `i32`. +- `BigInt.fromString(s: string): BigInt`– Parses a `BigInt` from a string. +- `BigInt.fromUnsignedBytes(x: Bytes): BigInt` – Interprets `bytes` as an unsigned, little-endian integer. If your input is big-endian, call `.reverse()` first. +- `BigInt.fromSignedBytes(x: Bytes): BigInt` – Interprets `bytes` as a signed, little-endian integer. If your input is big-endian, call `.reverse()` first. + + _Type conversions_ + +- `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.toBigDecimal(): BigDecimal` - converts into a decimal with no fractional part. + +_Math_ + +- `x.plus(y: BigInt): BigInt` – can be written as `x + y`. +- `x.minus(y: BigInt): BigInt` – can be written as `x - y`. +- `x.times(y: BigInt): BigInt` – can be written as `x * y`. +- `x.div(y: BigInt): BigInt` – can be written as `x / y`. +- `x.mod(y: BigInt): BigInt` – can be written as `x % y`. +- `x.equals(y: BigInt): bool` – can be written as `x == y`. +- `x.notEqual(y: BigInt): bool` – can be written as `x != y`. +- `x.lt(y: BigInt): bool` – can be written as `x < y`. +- `x.le(y: BigInt): bool` – can be written as `x <= y`. +- `x.gt(y: BigInt): bool` – can be written as `x > y`. +- `x.ge(y: BigInt): bool` – can be written as `x >= y`. +- `x.neg(): BigInt` – can be written as `-x`. +- `x.divDecimal(y: BigDecimal): BigDecimal` – divides by a decimal, giving a decimal result. +- `x.isZero(): bool` – Convenience for checking if the number is zero. +- `x.isI32(): bool` – Check if the number fits in an `i32`. +- `x.abs(): BigInt` – Absolute value. +- `x.pow(exp: u8): BigInt` – Exponentiation. +- `bitOr(x: BigInt, y: BigInt): BigInt` – can be written as `x | y`. +- `bitAnd(x: BigInt, y: BigInt): BigInt` – can be written as `x & y`. +- `leftShift(x: BigInt, bits: u8): BigInt` – can be written as `x << y`. +- `rightShift(x: BigInt, bits: u8): BigInt` – can be written as `x >> y`. + +#### TypedMap + +```typescript +import { TypedMap } from '@graphprotocol/graph-ts' +``` + +`TypedMap` can be used to stored key-value pairs. See [this example](https://github.com/graphprotocol/aragon-subgraph/blob/29dd38680c5e5104d9fdc2f90e740298c67e4a31/individual-dao-subgraph/mappings/constants.ts#L51). + +The `TypedMap` class has the following 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` +- `map.getEntry(key: K): TypedMapEntry | null` – returns the key-value pair for a `key` or `null` if the `key` does not exist in the map +- `map.get(key: K): V | null` – returns the value for a `key` or `null` if the `key` does not exist in the map +- `map.isSet(key: K): bool` – returns `true` if the `key` exists in the map and `false` if it does not + +#### Bytes + +```typescript +import { Bytes } from '@graphprotocol/graph-ts' +``` + +`Bytes` is used to represent arbitrary-length arrays of bytes. This includes Ethereum values of type `bytes`, `bytes32` etc. + +The `Bytes` class extends AssemblyScript's [Uint8Array](https://github.com/AssemblyScript/assemblyscript/blob/3b1852bc376ae799d9ebca888e6413afac7b572f/std/assembly/typedarray.ts#L64) and this supports all the `Uint8Array` functionality, plus the following new methods: + +- `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) + +#### Address + +```typescript +import { Address } from '@graphprotocol/graph-ts' +``` + +`Address` extends `Bytes` to represent Ethereum `address` values. + +It adds the following method on top of the `Bytes` API: + +- `Address.fromString(s: string): Address` – creates an `Address` from a hexadecimal string + +### Store API + +```typescript +import { store } from '@graphprotocol/graph-ts' +``` + +The `store` API allows to load, save and remove entities from and to the Graph Node store. + +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. + +#### Creating entities + +The following is a common pattern for creating entities from Ethereum events. + +```typescript +// Import the Transfer event class generated from the ERC20 ABI +import { Transfer as TransferEvent } from '../generated/ERC20/ERC20' + +// Import the Transfer entity type generated from the GraphQL schema +import { Transfer } from '../generated/schema' + +// Transfer event handler +export function handleTransfer(event: TransferEvent): void { + // Create a Transfer entity, using the hexadecimal string representation + // of the transaction hash as the entity ID + let id = event.transaction.hash.toHex() + let transfer = new Transfer(id) + + // Set properties on the entity, using the event parameters + transfer.from = event.params.from + transfer.to = event.params.to + transfer.amount = event.params.amount + + // Save the entity to the store + transfer.save() +} +``` + +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. + +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. + +#### Loading entities from the store + +If an entity already exists, it can be loaded from the store with the following: + +```typescript +let id = event.transaction.hash.toHex() // or however the ID is constructed +let transfer = Transfer.load(id) +if (transfer == null) { + transfer = new Transfer(id) +} + +// 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. + +> **Note:** Loading entities is only necessary if the changes made in the mapping depend on the previous data of an entity. See the next section for the two ways of updating existing entities. + +#### Updating existing entities + +There are two ways to update an existing entity: + +1. Load the entity with e.g. `Transfer.load(id)`, set properties on the entity, then `.save()` it back to the store. +2. Simply create the entity with e.g. `new Transfer(id)`, set properties on the entity, then `.save()` it to the store. If the entity already exists, the changes are merged into it. + +Changing properties is straight forward in most cases, thanks to the generated property setters: + +```typescript +let transfer = new Transfer(id) +transfer.from = ... +transfer.to = ... +transfer.amount = ... +``` + +It is also possible to unset properties with one of the following two instructions: + +```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`. + +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. + +```typescript +// This won't work +entity.numbers.push(BigInt.fromI32(1)) +entity.save() + +// This will work +let numbers = entity.numbers +numbers.push(BigInt.fromI32(1)) +entity.numbers = numbers +entity.save() +``` + +#### Removing entities from the 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`: + +```typescript +import { store } from '@graphprotocol/graph-ts' +... +let id = event.transaction.hash.toHex() +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. + +#### Support for Ethereum Types + +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. + +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. + +The following example illustrates this. Given a subgraph schema like + +```graphql +type Transfer @entity { + from: Bytes! + to: Bytes! + amount: BigInt! +} +``` + +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: + +```typescript +let id = event.transaction.hash.toHex() +let transfer = new Transfer(id) +transfer.from = event.params.from +transfer.to = event.params.to +transfer.amount = event.params.amount +transfer.save() +``` + +#### Events and Block/Transaction Data + +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`): + +```typescript +class Event { + address: Address + logIndex: BigInt + transactionLogIndex: BigInt + logType: string | null + block: Block + transaction: Transaction + parameters: Array +} + +class Block { + hash: Bytes + parentHash: Bytes + unclesHash: Bytes + author: Address + stateRoot: Bytes + transactionsRoot: Bytes + receiptsRoot: Bytes + number: BigInt + gasUsed: BigInt + gasLimit: BigInt + timestamp: BigInt + difficulty: BigInt + totalDifficulty: BigInt + size: BigInt | null + baseFeePerGas: BigInt | null +} + +class Transaction { + hash: Bytes + index: BigInt + from: Address + to: Address | null + value: BigInt + gasLimit: BigInt + gasPrice: BigInt + input: Bytes + nonce: BigInt +} +``` + +#### Access to Smart Contract State + +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. + +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 entity class +import { Transfer } from '../generated/schema' + +export function handleTransfer(event: Transfer) { + // Bind the contract to the address that emitted the event + let contract = ERC20Contract.bind(event.address) + + // 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. + +Any other contract that is part of the subgraph can be imported from the generated code and can be bound to a valid address. + +#### Handling Reverted Calls + +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: + +```typescript +let gravity = Gravity.bind(event.address) +let callResult = gravity.try_gravatarToOwner(gravatar) +if (callResult.reverted) { + log.info('getGravatar reverted', []) +} else { + let owner = callResult.value +} +``` + +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. + +#### Encoding/Decoding ABI + +Data can be encoded and decoded according to Ethereum's ABI encoding format using the `encode` and `decode` functions in the `ethereum` module. + +```typescript +import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts' + +let tupleArray: Array = [ + ethereum.Value.fromAddress(Address.fromString('0x0000000000000000000000000000000000000420')), + ethereum.Value.fromUnsignedBigInt(BigInt.fromI32(62)), +] + +let tuple = tupleArray as ethereum.Tuple + +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) +- More [complex example](https://github.com/graphprotocol/graph-node/blob/6a7806cc465949ebb9e5b8269eeb763857797efc/tests/integration-tests/host-exports/src/mapping.ts#L72). + +### Logging API + +```typescript +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. + +The `log` API includes the following functions: + +- `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. + +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. + +```typescript +log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue.toString(), 'already a string']) +``` + +#### Logging one or more values + +##### Logging a single value + +In the example below, the string value "A" is passed into an array to become`['A']` before being logged: + +```typescript +let myValue = 'A' + +export function handleSomeEvent(event: SomeEvent): void { + // Displays : "My value is: A" + log.info('My value is: {}', [myValue]) +} +``` + +##### Logging a single entry from an existing array + +In the example below, only the first value of the argument array is logged, despite the array containing three values. + +```typescript +let myArray = ['A', 'B', 'C'] + +export function handleSomeEvent(event: SomeEvent): void { + // Displays : "My value is: A" (Even though three values are passed to `log.info`) + log.info('My value is: {}', myArray) +} +``` + +#### Logging multiple entries from an existing array + +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. + +```typescript +let myArray = ['A', 'B', 'C'] + +export function handleSomeEvent(event: SomeEvent): void { + // Displays : "My first value is: A, second value is: B, third value is: C" + log.info('My first value is: {}, second value is: {}, third value is: {}', myArray) +} +``` + +##### Logging a specific entry from an existing array + +To display a specific value in the array, the indexed value must be provided. + +```typescript +export function handleSomeEvent(event: SomeEvent): void { + // Displays : "My third value is C" + log.info('My third value is: {}', [myArray[2]]) +} +``` + +##### Logging event information + +The example below logs the block number, block hash and transaction hash from an event: + +```typescript +import { log } from '@graphprotocol/graph-ts' + +export function handleSomeEvent(event: SomeEvent): void { + log.debug('Block number: {}, block hash: {}, transaction hash: {}', [ + event.block.number.toString(), // "47596000" + event.block.hash.toHexString(), // "0x..." + event.transaction.hash.toHexString(), // "0x..." + ]) +} +``` + +### IPFS API + +```typescript +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. + +Given an IPFS hash or path, reading a file from IPFS is done as follows: + +```typescript +// Put this inside an event handler in the mapping +let hash = 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D' +let data = ipfs.cat(hash) + +// Paths like `QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile` +// that include files in directories are also supported +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](/developer/create-subgraph-hosted#ipfs-pinning) section for more information. + +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: + +```typescript +import { JSONValue, Value } from '@graphprotocol/graph-ts' + +export function processItem(value: JSONValue, userData: Value): void { + // See the JSONValue documentation for details on dealing + // with JSON values + let obj = value.toObject() + let id = obj.get('id') + let title = obj.get('title') + + if (!id || !title) { + return + } + + // Callbacks can also created entities + let newItem = new Item(id.toString()) + newItem.title = title.toString() + newitem.parent = userData.toString() // Set parent to "parentId" + newitem.save() +} + +// Put this inside an event handler in the mapping +ipfs.map('Qm...', 'processItem', Value.fromString('parentId'), ['json']) + +// Alternatively, use `ipfs.mapJSON` +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. + +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. + +### Crypto API + +```typescript +import { crypto } from '@graphprotocol/graph-ts' +``` + +The `crypto` API makes a cryptographic functions available for use in mappings. Right now, there is only one: + +- `crypto.keccak256(input: ByteArray): ByteArray` + +### JSON API + +```typescript +import { json, JSONValueKind } from '@graphprotocol/graph-ts' +``` + +JSON data can be parsed using the `json` API: + +- `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: Bytes): JSONValue` – parses JSON data from a valid UTF-8 `String` +- `json.try_fromString(data: Bytes): Result` – safe version of `json.fromString`, it returns an error variant if the parsing failed + +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: + +```typescript +let value = json.fromBytes(...) +if (value.kind == JSONValueKind.BOOL) { + ... +} +``` + +In addition, there is a method to check if the value is `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: + +- `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) + +### Type Conversions Reference + +| Source(s) | Destination | Conversion function | +| -------------------- | -------------------- | ---------------------------- | +| Address | Bytes | none | +| Address | ID | s.toHexString() | +| Address | 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) | +| 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 | +| int32 | BigInt | Bigint.fromI32(s) | +| uint24 | i32 | none | +| int64 - int256 | BigInt | none | +| uint32 - uint256 | BigInt | none | +| 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 | Object | s.toObject() | +| String | Address | Address.fromString(s) | +| String | BigDecimal | BigDecimal.fromString(s) | +| String (hexadecimal) | Bytes | ByteArray.fromHexString(s) | +| String (UTF-8) | Bytes | ByteArray.fromUTF8(s) | + +### Data Source Metadata + +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` +- `dataSource.context(): DataSourceContext` + +### Entity and DataSourceContext + +The base `Entity` class and the child `DataSourceContext` class have helpers to dynamically set and get fields: + +- `setString(key: string, value: string): void` +- `setI32(key: string, value: i32): void` +- `setBigInt(key: string, value: BigInt): void` +- `setBytes(key: string, value: Bytes): void` +- `setBoolean(key: string, value: bool): void` +- `setBigDecimal(key, value: BigDecimal): void` +- `getString(key: string): string` +- `getI32(key: string): i32` +- `getBigInt(key: string): BigInt` +- `getBytes(key: string): Bytes` +- `getBoolean(key: string): boolean` +- `getBigDecimal(key: string): BigDecimal` diff --git a/pages/vi/developer/assemblyscript-migration-guide.mdx b/pages/vi/developer/assemblyscript-migration-guide.mdx new file mode 100644 index 000000000000..2db90a608110 --- /dev/null +++ b/pages/vi/developer/assemblyscript-migration-guide.mdx @@ -0,0 +1,484 @@ +--- +title: AssemblyScript Migration Guide +--- + +Up until now, subgraphs have been using one of the [first versions of AssemblyScript](https://github.com/AssemblyScript/assemblyscript/tree/v0.6) (v0.6). Finally we've added support for the [newest one available](https://github.com/AssemblyScript/assemblyscript/tree/v0.19.10) (v0.19.10)! 🎉 + +That will enable subgraph developers to use newer features of the AS language and standard library. + +This guide is applicable for anyone using `graph-cli`/`graph-ts` below version `0.22.0`. If you're already at a higher than (or equal) version to that, you've already been using version `0.19.10` of AssemblyScript 🙂 + +> Note: As of `0.24.0`, `graph-node` can support both versions, depending on the `apiVersion` specified in the subgraph manifest. + +## Features + +### New functionality + +- `TypedArray`s can now be built from `ArrayBuffer`s by using the [new `wrap` static method](https://www.assemblyscript.org/stdlib/typedarray.html#static-members) ([v0.8.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.8.1)) +- New standard library functions: `String#toUpperCase`, `String#toLowerCase`, `String#localeCompare`and `TypedArray#set` ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- Added support for x instanceof GenericClass ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) +- Added `StaticArray`, a more efficient array variant ([v0.9.3](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.3)) +- Added `Array#flat` ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- Implemented `radix` argument on `Number#toString` ([v0.10.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.1)) +- Added support for separators in floating point literals ([v0.13.7](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.13.7)) +- Added support for first class functions ([v0.14.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.0)) +- Add builtins: `i32/i64/f32/f64.add/sub/mul` ([v0.14.13](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.14.13)) +- Implement `Array/TypedArray/String#at` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) +- Added support for template literal strings ([v0.18.17](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.17)) +- Add `encodeURI(Component)` and `decodeURI(Component)` ([v0.18.27](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.27)) +- Add `toString`, `toDateString` and `toTimeString` to `Date` ([v0.18.29](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.29)) +- Add `toUTCString` for `Date` ([v0.18.30](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.30)) +- Add `nonnull/NonNullable` builtin type ([v0.19.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.19.2)) + +### Optimizations + +- `Math` functions such as `exp`, `exp2`, `log`, `log2` and `pow` have been replaced by faster variants ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- Slightly optimize `Math.mod` ([v0.17.1](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.1)) +- Cache more field accesses in std Map and Set ([v0.17.8](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.17.8)) +- Optimize for powers of two in `ipow32/64` ([v0.18.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.18.2)) + +### Other + +- The type of an array literal can now be inferred from its contents ([v0.9.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.0)) +- Updated stdlib to Unicode 13.0.0 ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) + +## How to upgrade? + +1. Change your mappings `apiVersion` in `subgraph.yaml` to `0.0.6`: + +```yaml +... +dataSources: + ... + mapping: + ... + apiVersion: 0.0.6 + ... +``` + +2. Update the `graph-cli` you're using to the `latest` version by running: + +```bash +# if you have it globally installed +npm install --global @graphprotocol/graph-cli@latest + +# or in your subgraph if you have it as a dev dependency +npm install --save-dev @graphprotocol/graph-cli@latest +``` + +3. Do the same for `graph-ts`, but instead of installing globally, save it in your main dependencies: + +```bash +npm install --save @graphprotocol/graph-ts@latest +``` + +4. Follow the rest of the guide to fix the language breaking changes. +5. Run `codegen` and `deploy` again. + +## Breaking changes + +### Nullability + +On the older version of AssemblyScript, you could create code like this: + +```typescript +function load(): Value | null { ... } + +let maybeValue = load(); +maybeValue.aMethod(); +``` + +However on the newer version, because the value is nullable, it requires you to check, like this: + +```typescript +let maybeValue = load() + +if (maybeValue) { + maybeValue.aMethod() // `maybeValue` is not null anymore +} +``` + +Or force it like this: + +```typescript +let maybeValue = load()! // breaks in runtime if value is null + +maybeValue.aMethod() +``` + +If you are unsure which to choose, we recommend always using the safe version. If the value doesn't exist you might want to just do an early if statement with a return in you subgraph handler. + +### Variable Shadowing + +Before you could do [variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) and code like this would work: + +```typescript +let a = 10 +let b = 20 +let a = a + b +``` + +However now this isn't possible anymore, and the compiler returns this error: + +```typescript +ERROR TS2451: Cannot redeclare block-scoped variable 'a' + + let a = a + b; + ~~~~~~~~~~~~~ +in assembly/index.ts(4,3) +``` +You'll need to rename your duplicate variables if you had variable shadowing. +### Null Comparisons +By doing the upgrade on your subgraph, sometimes you might get errors like these: + +```typescript +ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' is not assignable to type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt'. + if (decimals == null) { + ~~~~ + in src/mappings/file.ts(41,21) +``` +To solve you can simply change the `if` statement to something like this: + +```typescript + if (!decimals) { + + // or + + if (decimals === null) { +``` + +The same applies if you're doing != instead of ==. + +### Casting + +The common way to do casting before was to just use the `as` keyword, like this: + +```typescript +let byteArray = new ByteArray(10) +let uint8Array = byteArray as Uint8Array // equivalent to: byteArray +``` + +However this only works in two scenarios: + +- Primitive casting (between types such as `u8`, `i32`, `bool`; eg: `let b: isize = 10; b as usize`); +- Upcasting on class inheritance (subclass → superclass) + +Examples: + +```typescript +// primitive casting +let a: usize = 10 +let b: isize = 5 +let c: usize = a + (b as usize) +``` + +```typescript +// upcasting on class inheritance +class Bytes extends Uint8Array {} + +let bytes = new Bytes(2) < Uint8Array > bytes // same as: bytes as Uint8Array +``` + +There are two scenarios where you may want to cast, but using `as`/`var` **isn't safe**: + +- Downcasting on class inheritance (superclass → subclass) +- Between two types that share a superclass + +```typescript +// downcasting on class inheritance +class Bytes extends Uint8Array {} + +let uint8Array = new Uint8Array(2) < Bytes > uint8Array // breaks in runtime :( +``` + +```typescript +// between two types that share a superclass +class Bytes extends Uint8Array {} +class ByteArray extends Uint8Array {} + +let bytes = new Bytes(2) < ByteArray > bytes // breaks in runtime :( +``` + +For those cases, you can use the `changetype` function: + +```typescript +// downcasting on class inheritance +class Bytes extends Uint8Array {} + +let uint8Array = new Uint8Array(2) +changetype(uint8Array) // works :) +``` + +```typescript +// between two types that share a superclass +class Bytes extends Uint8Array {} +class ByteArray extends Uint8Array {} + +let bytes = new Bytes(2) +changetype(bytes) // works :) +``` + +If you just want to remove nullability, you can keep using the `as` operator (or `variable`), but make sure you know that value can't be null, otherwise it will break. + +```typescript +// remove nullability +let previousBalance = AccountBalance.load(balanceId) // AccountBalance | null + +if (previousBalance != null) { + return previousBalance as AccountBalance // safe remove null +} + +let newBalance = new AccountBalance(balanceId) +``` + +For the nullability case we recommend taking a look at the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks), it will make your code cleaner 🙂 + +Also we've added a few more static methods in some types to ease casting, they are: + +- Bytes.fromByteArray +- Bytes.fromUint8Array +- BigInt.fromByteArray +- ByteArray.fromBigInt + +### Nullability check with property access + +To use the [nullability check feature](https://www.assemblyscript.org/basics.html#nullability-checks) you can use either `if` statements or the ternary operator (`?` and `:`) like this: + +```typescript +let something: string | null = 'data' + +let somethingOrElse = something ? something : 'else' + +// or + +let somethingOrElse + +if (something) { + somethingOrElse = something +} else { + somethingOrElse = 'else' +} +``` + +However that only works when you're doing the `if` / ternary on a variable, not on a property access, like this: + +```typescript +class Container { + data: string | null +} + +let container = new Container() +container.data = 'data' + +let somethingOrElse: string = container.data ? container.data : 'else' // doesn't compile +``` + +Which outputs this error: + +```typescript +ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/string/String'. + + let somethingOrElse: string = container.data ? container.data : "else"; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``` +To fix this issue, you can create a variable for that property access so that the compiler can do the nullability check magic: + +```typescript +class Container { + data: string | null +} + +let container = new Container() +container.data = 'data' + +let data = container.data + +let somethingOrElse: string = data ? data : 'else' // compiles just fine :) +``` + +### Operator overloading with property access + +If you try to sum (for example) a nullable type (from a property access) with a non nullable one, the AssemblyScript compiler instead of giving a compile time error warning that one of the values is nullable, it just compiles silently, giving chance for the code to break at runtime. + +```typescript +class BigInt extends Uint8Array { + @operator('+') + plus(other: BigInt): BigInt { + // ... + } +} + +class Wrapper { + public constructor(public n: BigInt | null) {} +} + +let x = BigInt.fromI32(2) +let y: BigInt | null = null + +x + y // give compile time error about nullability + +let wrapper = new Wrapper(y) + +wrapper.n = wrapper.n + x // doesn't give compile time errors as it should +``` + +We've opened a issue on the AssemblyScript compiler for this, but for now if you do these kind of operations in your subgraph mappings, you should change them to do a null check before it. + +```typescript +let wrapper = new Wrapper(y) + +if (!wrapper.n) { + wrapper.n = BigInt.fromI32(0) +} + +wrapper.n = wrapper.n + x // now `n` is guaranteed to be a BigInt +``` + +### Value initialization + +If you have any code like this: + +```typescript +var value: Type // null +value.x = 10 +value.y = 'content' +``` + +It will compile but break at runtime, that happens because the value hasn't been initialized, so make sure your subgraph has initialized their values, like this: + +```typescript +var value = new Type() // initialized +value.x = 10 +value.y = 'content' +``` + +Also if you have nullable properties in a GraphQL entity, like this: + +```graphql +type Total @entity { + id: ID! + amount: BigInt +} +``` + +And you have code similar to this: + +```typescript +let total = Total.load('latest') + +if (total === null) { + total = new Total('latest') +} + +total.amount = total.amount + BigInt.fromI32(1) +``` + +You'll need to make sure to initialize the `total.amount` value, because if you try to access like in the last line for the sum, it will crash. So you either initialize it first: + +```typescript +let total = Total.load('latest') + +if (total === null) { + total = new Total('latest') + total.amount = BigInt.fromI32(0) +} + +total.tokens = total.tokens + BigInt.fromI32(1) +``` + +Or you can just change your GraphQL schema to not use a nullable type for this property, then we'll initialize it as zero on the `codegen` step 😉 + +```graphql +type Total @entity { + id: ID! + amount: BigInt! +} +``` + +```typescript +let total = Total.load('latest') + +if (total === null) { + total = new Total('latest') // already initializes non-nullable properties +} + +total.amount = total.amount + BigInt.fromI32(1) +``` + +### Class property initialization + +If you export any classes with properties that are other classes (declared by you or by the standard library) like this: + +```typescript +class Thing {} + +export class Something { + value: Thing +} +``` + +The compiler will error because you either need to add an initializer for the properties that are classes, or add the `!` operator: + +```typescript +export class Something { + constructor(public value: Thing) {} +} + +// or + +export class Something { + value: Thing + + constructor(value: Thing) { + this.value = value + } +} + +// or + +export class Something { + value!: Thing +} +``` + +### GraphQL schema + +This is not a direct AssemblyScript change, but you may have to update your `schema.graphql` file. + +Now you no longer can define fields in your types that are Non-Nullable Lists. If you have a schema like this: + +```graphql +type Something @entity { + id: ID! +} + +type MyEntity @entity { + id: ID! + invalidField: [Something]! # no longer valid +} +``` + +You'll have to add an `!` to the member of the List type, like this: + +```graphql +type Something @entity { + id: ID! +} + +type MyEntity @entity { + id: ID! + invalidField: [Something!]! # valid +} +``` + +This changed because of nullability differences between AssemblyScript versions, and it's related to the `src/generated/schema.ts` file (default path, you might have changed this). + +### Other + +- Aligned `Map#set` and `Set#add` with the spec, returning `this` ([v0.9.2](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.9.2)) +- Arrays no longer inherit from ArrayBufferView, but are now distinct ([v0.10.0](https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.10.0)) +- 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)) +- 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/pages/vi/developer/create-subgraph-hosted.mdx b/pages/vi/developer/create-subgraph-hosted.mdx new file mode 100644 index 000000000000..43c18e98693c --- /dev/null +++ b/pages/vi/developer/create-subgraph-hosted.mdx @@ -0,0 +1,928 @@ +--- +title: Create a Subgraph +--- + +Before being able to use the Graph CLI, you need to create your subgraph in [Subgraph Studio](https://thegraph.com/studio). You will then be able to setup your subgraph project and deploy it to the platform of your choice. Note that **subgraphs that do not index Ethereum mainnet will not be published to The Graph Network**. + +The `graph init` command can be used to set up a new subgraph project, either from an existing contract on any of the public Ethereum networks, or from an example subgraph. This command can be used to create a subgraph on the Subgraph Studio by passing in `graph init --product subgraph-studio`. If you already have a smart contract deployed to Ethereum mainnet or one of the testnets, bootstrapping a new subgraph from that contract can be a good way to get started. But first, a little about the networks The Graph supports. + +## Mạng lưới được hỗ trợ + +The Graph Network supports subgraphs indexing mainnet Ethereum: + +- `mainnet` + +**Additional Networks are supported in beta on the Hosted Service**: + +- `mainnet` +- `kovan` +- `rinkeby` +- `ropsten` +- `goerli` +- `poa-core` +- `poa-sokol` +- `xdai` +- `near-mainnet` +- `near-testnet` +- `matic` +- `mumbai` +- `fantom` +- `bsc` +- `chapel` +- `clover` +- `avalanche` +- `fuji` +- `celo` +- `celo-alfajores` +- `fuse` +- `moonriver` +- `mbase` +- `arbitrum-one` +- `arbitrum-rinkeby` +- `optimism` +- `optimism-kovan` +- `aurora` +- `aurora-testnet` + +The Graph's Hosted Service relies on the stability and reliability of the underlying technologies, namely the provided JSON RPC endpoints. Newer networks will be marked as being in beta until the network has proven itself in terms of stability, reliability, and scalability. During this beta period, there is risk of downtime and unexpected behaviour. + +Remember that you will **not be able** to publish a subgraph that indexes a non-mainnet network to the decentralized Graph Network in [Subgraph Studio](/studio/subgraph-studio). + +## From An Existing Contract + +The following command creates a subgraph that indexes all events of an existing contract. It attempts to fetch the contract ABI from Etherscan and falls back to requesting a local file path. If any of the optional arguments are missing, it takes you through an interactive form. + +```sh +graph init \ + --product subgraph-studio + --from-contract \ + [--network ] \ + [--abi ] \ + [] +``` + +The `` is the ID of your subgraph in Subgraph Studio, it can be found on your subgraph details page. + +## From An Example Subgraph + +The second mode `graph init` supports is creating a new project from an example subgraph. The following command does this: + +``` +graph init --studio +``` + +The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. The following sections will go over the files that make up the subgraph manifest for this example. + +## The Subgraph Manifest + +The subgraph manifest `subgraph.yaml` defines the smart contracts your subgraph indexes, which events from these contracts to pay attention to, and how to map event data to entities that Graph Node stores and allows to query. The full specification for subgraph manifests can be found [here](https://github.com/graphprotocol/graph-node/blob/master/docs/subgraph-manifest.md). + +For the example subgraph, `subgraph.yaml` is: + +```yaml +specVersion: 0.0.4 +description: Gravatar for Ethereum +repository: https://github.com/graphprotocol/example-subgraph +schema: + file: ./schema.graphql +dataSources: + - kind: ethereum/contract + name: Gravity + network: mainnet + source: + address: '0x2E645469f354BB4F5c8a05B3b30A929361cf77eC' + abi: Gravity + startBlock: 6175244 + mapping: + kind: ethereum/events + apiVersion: 0.0.6 + language: wasm/assemblyscript + entities: + - Gravatar + abis: + - name: Gravity + file: ./abis/Gravity.json + eventHandlers: + - event: NewGravatar(uint256,address,string,string) + handler: handleNewGravatar + - event: UpdatedGravatar(uint256,address,string,string) + handler: handleUpdatedGravatar + callHandlers: + - function: createGravatar(string,string) + handler: handleCreateGravatar + blockHandlers: + - function: handleBlock + - function: handleBlockWithCall + filter: + kind: call + file: ./src/mapping.ts +``` + +The important entries to update for the manifest are: + +- `description`: a human-readable description of what the subgraph is. This description is displayed by the Graph Explorer when the subgraph is deployed to the Hosted Service. + +- `repository`: the URL of the repository where the subgraph manifest can be found. This is also displayed by the Graph Explorer. + +- `features`: a list of all used [feature](#experimental-features) names. + +- `dataSources.source`: the address of the smart contract the subgraph sources, and the abi of the smart contract to use. The address is optional; omitting it allows to index matching events from all contracts. + +- `dataSources.source.startBlock`: the optional number of the block that the data source starts indexing from. In most cases we suggest using the block in which the contract was created. + +- `dataSources.mapping.entities`: the entities that the data source writes to the store. The schema for each entity is defined in the the schema.graphql file. + +- `dataSources.mapping.abis`: one or more named ABI files for the source contract as well as any other smart contracts that you interact with from within the mappings. + +- `dataSources.mapping.eventHandlers`: lists the smart contract events this subgraph reacts to and the handlers in the mapping—./src/mapping.ts in the example—that transform these events into entities in the store. + +- `dataSources.mapping.callHandlers`: lists the smart contract functions this subgraph reacts to and handlers in the mapping that transform the inputs and outputs to function calls into entities in the store. + +- `dataSources.mapping.blockHandlers`: lists the blocks this subgraph reacts to and handlers in the mapping to run when a block is appended to the chain. Without a filter, the block handler will be run every block. An optional filter can be provided with the following kinds: call`. A`call` filter will run the handler if the block contains at least one call to the data source contract. + +A single subgraph can index data from multiple smart contracts. Add an entry for each contract from which data needs to be indexed to the `dataSources` array. + +The triggers for a data source within a block are ordered using the following process: + +1. Event and call triggers are first ordered by transaction index within the block. +2. Event and call triggers with in the same transaction are ordered using a convention: event triggers first then call triggers, each type respecting the order they are defined in the manifest. +3. Block triggers are run after event and call triggers, in the order they are defined in the manifest. + +These ordering rules are subject to change. + +### Getting The ABIs + +The ABI file(s) must match your contract(s). There are a few ways to obtain ABI files: + +- If you are building your own project, you will likely have access to your most current ABIs. +- If you are building a subgraph for a public project, you can download that project to your computer and get the ABI by using [`truffle compile`](https://truffleframework.com/docs/truffle/overview) or using solc to compile. +- You can also find the ABI on [Etherscan](https://etherscan.io/), but this isn't always reliable, as the ABI that is uploaded there may be out of date. Make sure you have the right ABI, otherwise running your subgraph will fail. + +## The GraphQL Schema + +The schema for your subgraph is in the file `schema.graphql`. GraphQL schemas are defined using the GraphQL interface definition language. If you've never written a GraphQL schema, it is recommended that you check out this primer on the GraphQL type system. Reference documentation for GraphQL schemas can be found in the [GraphQL API](/developer/graphql-api) section. + +## Defining Entities + +Before defining entities, it is important to take a step back and think about how your data is structured and linked. All queries will be made against the data model defined in the subgraph schema and the entities indexed by the subgraph. Because of this, it is good to define the subgraph schema in a way that matches the needs of your dapp. It may be useful to imagine entities as "objects containing data", rather than as events or functions. + +With The Graph, you simply define entity types in `schema.graphql`, and Graph Node will generate top level fields for querying single instances and collections of that entity type. Each type that should be an entity is required to be annotated with an `@entity` directive. + +### Good Example + +The `Gravatar` entity below is structured around a Gravatar object and is a good example of how an entity could be defined. + +```graphql +type Gravatar @entity { + id: ID! + owner: Bytes + displayName: String + imageUrl: String + accepted: Boolean +} +``` + +### Bad Example + +The example `GravatarAccepted` and `GravatarDeclined` entities below are based around events. It is not recommended to map events or function calls to entities 1:1. + +```graphql +type GravatarAccepted @entity { + id: ID! + owner: Bytes + displayName: String + imageUrl: String +} + +type GravatarDeclined @entity { + id: ID! + owner: Bytes + displayName: String + imageUrl: String +} +``` + +### Optional and Required Fields + +Entity fields can be defined as required or optional. Required fields are indicated by the `!` in the schema. If a required field is not set in the mapping, you will receive this error when querying the field: + +``` +Null value resolved for non-null field 'name' +``` + +Each entity must have an `id` field, which is of type `ID!` (string). The `id` field serves as the primary key, and needs to be unique among all entities of the same type. + +### Built-In Scalar Types + +#### GraphQL Supported Scalars + +We support the following scalars in our GraphQL API: + +| Type | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | +| `ID` | Stored as a `string`. | +| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | +| `Boolean` | Scalar for `boolean` values. | +| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | +| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | +| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | + +#### Enums + +You can also create enums within a schema. Enums have the following syntax: + +```graphql +enum TokenStatus { + OriginalOwner + SecondOwner + ThirdOwner +} +``` + +Once the enum is defined in the schema, you can use the string representation of the enum value to set an enum field on an entity. For example, you can set the `tokenStatus` to `SecondOwner` by first defining your entity and subsequently setting the field with `entity.tokenStatus = "SecondOwner`. The example below demonstrates what the Token entity would look like with an enum field: + +More detail on writing enums can be found in the [GraphQL documentation](https://graphql.org/learn/schema/). + +#### Entity Relationships + +An entity may have a relationship to one or more other entities in your schema. These relationships may be traversed in your queries. Relationships in The Graph are unidirectional. It is possible to simulate bidirectional relationships by defining a unidirectional relationship on either "end" of the relationship. + +Relationships are defined on entities just like any other field except that the type specified is that of another entity. + +#### One-To-One Relationships + +Define a `Transaction` entity type with an optional one-to-one relationship with a `TransactionReceipt` entity type: + +```graphql +type Transaction @entity { + id: ID! + transactionReceipt: TransactionReceipt +} + +type TransactionReceipt @entity { + id: ID! + transaction: Transaction +} +``` + +#### One-To-Many Relationships + +Define a `TokenBalance` entity type with a required one-to-many relationship with a Token entity type: + +```graphql +type Token @entity { + id: ID! +} + +type TokenBalance @entity { + id: ID! + amount: Int! + token: Token! +} +``` + +#### Reverse Lookups + +Reverse lookups can be defined on an entity through the `@derivedFrom` field. This creates a virtual field on the entity that may be queried but cannot be set manually through the mappings API. Rather, it is derived from the relationship defined on the other entity. For such relationships, it rarely makes sense to store both sides of the relationship, and both indexing and query performance will be better when only one side is stored and the other is derived. + +For one-to-many relationships, the relationship should always be stored on the 'one' side, and the 'many' side should always be derived. Storing the relationship this way, rather than storing an array of entities on the 'many' side, will result in dramatically better performance for both indexing and querying the subgraph. In general, storing arrays of entities should be avoided as much as is practical. + +#### Example + +We can make the balances for a token accessible from the token by deriving a `tokenBalances` field: + +```graphql +type Token @entity { + id: ID! + tokenBalances: [TokenBalance!]! @derivedFrom(field: "token") +} + +type TokenBalance @entity { + id: ID! + amount: Int! + token: Token! +} +``` + +#### Many-To-Many Relationships + +For many-to-many relationships, such as users that each may belong to any number of organizations, the most straightforward, but generally not the most performant, way to model the relationship is as an array in each of the two entities involved. If the relationship is symmetric, only one side of the relationship needs to be stored and the other side can be derived. + +#### Example + +Define a reverse lookup from a `User` entity type to an `Organization` entity type. In the example below, this is achieved by looking up the `members` attribute from within the `Organization` entity. In queries, the `organizations` field on `User` will be resolved by finding all `Organization` entities that include the user's ID. + +```graphql +type Organization @entity { + id: ID! + name: String! + members: [User!]! +} + +type User @entity { + id: ID! + name: String! + organizations: [Organization!]! @derivedFrom(field: "members") +} +``` + +A more performant way to store this relationship is through a mapping table that has one entry for each `User` / `Organization` pair with a schema like + +```graphql +type Organization @entity { + id: ID! + name: String! + members: [UserOrganization]! @derivedFrom(field: "user") +} + +type User @entity { + id: ID! + name: String! + organizations: [UserOrganization!] @derivedFrom(field: "organization") +} + +type UserOrganization @entity { + id: ID! # Set to `${user.id}-${organization.id}` + user: User! + organization: Organization! +} +``` + +This approach requires that queries descend into one additional level to retrieve, for example, the organizations for users: + +```graphql +query usersWithOrganizations { + users { + organizations { + # this is a UserOrganization entity + organization { + name + } + } + } +} +``` + +This more elaborate way of storing many-to-many relationships will result in less data stored for the subgraph, and therefore to a subgraph that is often dramatically faster to index and to query. + +#### Adding comments to the schema + +As per GraphQL spec, comments can be added above schema entity attributes using double quotations `""`. This is illustrated in the example below: + +```graphql +type MyFirstEntity @entity { + "unique identifier and primary key of the entity" + id: ID! + address: Bytes! +} +``` + +## Defining Fulltext Search Fields + +Fulltext search queries filter and rank entities based on a text search input. Fulltext queries are able to return matches for similar words by processing the query text input into stems before comparing to the indexed text data. + +A fulltext query definition includes the query name, the language dictionary used to process the text fields, the ranking algorithm used to order the results, and the fields included in the search. Each fulltext query may span multiple fields, but all included fields must be from a single entity type. + +To add a fulltext query, include a `_Schema_` type with a fulltext directive in the GraphQL schema. + +```graphql +type _Schema_ + @fulltext( + name: "bandSearch" + language: en + algorithm: rank + include: [{ entity: "Band", fields: [{ name: "name" }, { name: "description" }, { name: "bio" }] }] + ) + +type Band @entity { + id: ID! + name: String! + description: String! + bio: String + wallet: Address + labels: [Label!]! + discography: [Album!]! + members: [Musician!]! +} +``` + +The example `bandSearch` field can be used in queries to filter `Band` entities based on the text documents in the `name`, `description`, and `bio` fields. Jump to [GraphQL API - Queries](/developer/graphql-api#queries) for a description of the Fulltext search API and for more example usage. + +```graphql +query { + bandSearch(text: "breaks & electro & detroit") { + id + name + description + wallet + } +} +``` + +> **[Feature Management](#experimental-features):** From `specVersion` `0.0.4` and onwards, `fullTextSearch` must be declared under the `features` section in the subgraph manifest. + +### Languages supported + +Choosing a different language will have a definitive, though sometimes subtle, effect on the fulltext search API. Fields covered by a fulltext query field are examined in the context of the chosen language, so the lexemes produced by analysis and search queries vary language to language. For example: when using the supported Turkish dictionary "token" is stemmed to "toke" while, of course, the English dictionary will stem it to "token". + +Supported language dictionaries: + +| Code | Dictionary | +| ------ | ---------- | +| simple | General | +| da | Danish | +| nl | Dutch | +| en | English | +| fi | Finnish | +| fr | French | +| de | German | +| hu | Hungarian | +| it | Italian | +| no | Norwegian | +| pt | Portugese | +| ro | Romanian | +| ru | Russian | +| es | Spanish | +| sv | Swedish | +| tr | Turkish | + +### Ranking Algorithms + +Supported algorithms for ordering results: + +| Algorithm | Description | +| ------------- | ----------------------------------------------------------------------- | +| rank | Use the match quality (0-1) of the fulltext query to order the results. | +| proximityRank | Similar to rank but also includes the proximity of the matches. | + +## Writing Mappings + +The mappings transform the Ethereum data your mappings are sourcing into entities defined in your schema. Mappings are written in a subset of [TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) called [AssemblyScript](https://github.com/AssemblyScript/assemblyscript/wiki) which can be compiled to WASM ([WebAssembly](https://webassembly.org/)). AssemblyScript is stricter than normal TypeScript, yet provides a familiar syntax. + +For each event handler that is defined in `subgraph.yaml` under `mapping.eventHandlers`, create an exported function of the same name. Each handler must accept a single parameter called `event` with a type corresponding to the name of the event which is being handled. + +In the example subgraph, `src/mapping.ts` contains handlers for the `NewGravatar` and `UpdatedGravatar` events: + +```javascript +import { NewGravatar, UpdatedGravatar } from '../generated/Gravity/Gravity' +import { Gravatar } from '../generated/schema' + +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleUpdatedGravatar(event: UpdatedGravatar): void { + let id = event.params.id.toHex() + let gravatar = Gravatar.load(id) + if (gravatar == null) { + gravatar = new Gravatar(id) + } + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} +``` + +The first handler takes a `NewGravatar` event and creates a new `Gravatar` entity with `new Gravatar(event.params.id.toHex())`, populating the entity fields using the corresponding event parameters. This entity instance is represented by the variable `gravatar`, with an id value of `event.params.id.toHex()`. + +The second handler tries to load the existing `Gravatar` from the Graph Node store. If it does not exist yet, it is created on demand. The entity is then updated to match the new event parameters, before it is saved back to the store using `gravatar.save()`. + +### Recommended IDs for Creating New Entities + +Every entity has to have an `id` that is unique among all entities of the same type. An entity's `id` value is set when the entity is created. Below are some recommended `id` values to consider when creating new entities. NOTE: The value of `id` must be a `string`. + +- `event.params.id.toHex()` +- `event.transaction.from.toHex()` +- `event.transaction.hash.toHex() + "-" + event.logIndex.toString()` + +We provide the [Graph Typescript Library](https://github.com/graphprotocol/graph-ts) which contains utilies for interacting with the Graph Node store and conveniences for handling smart contract data and entities. You can use this library in your mappings by importing `@graphprotocol/graph-ts` in `mapping.ts`. + +## Code Generation + +In order to make working smart contracts, events and entities easy and type-safe, the Graph CLI can generate AssemblyScript types from the subgraph's GraphQL schema and the contract ABIs included in the data sources. + +This is done with + +```sh +graph codegen [--output-dir ] [] +``` + +but in most cases, subgraphs are already preconfigured via `package.json` to allow you to simply run one of the following to achieve the same: + +```sh +# Yarn +yarn codegen + +# NPM +npm run codegen +``` + +This will generate an AssemblyScript class for every smart contract in the ABI files mentioned in `subgraph.yaml`, allowing you to bind these contracts to specific addresses in the mappings and call read-only contract methods against the block being processed. It will also generate a class for every contract event to provide easy access to event parameters as well as the block and transaction the event originated from. All of these types are written to `//.ts`. In the example subgraph, this would be `generated/Gravity/Gravity.ts`, allowing mappings to import these types with + +```javascript +import { + // The contract class: + Gravity, + // The events classes: + NewGravatar, + UpdatedGravatar, +} from '../generated/Gravity/Gravity' +``` + +In addition to this, one class is generated for each entity type in the subgraph's GraphQL schema. These classes provide type-safe entity loading, read and write access to entity fields as well as a `save()` method to write entities to store. All entity classes are written to `/schema.ts`, allowing mappings to import them with + +```javascript +import { Gravatar } from '../generated/schema' +``` + +> **Note:** The code generation must be performed again after every change to the GraphQL schema or the ABIs included in the manifest. It must also be performed at least once before building or deploying the subgraph. + +Code generation does not check your mapping code in `src/mapping.ts`. If you want to check that before trying to deploy your subgraph to the Graph Explorer, you can run `yarn build` and fix any syntax errors that the TypeScript compiler might find. + +## Data Source Templates + +A common pattern in Ethereum smart contracts is the use of registry or factory contracts, where one contract creates, manages or references an arbitrary number of other contracts that each have their own state and events. The addresses of these sub-contracts may or may not be known upfront and many of these contracts may be created and/or added over time. This is why, in such cases, defining a single data source or a fixed number of data sources is impossible and a more dynamic approach is needed: _data source templates_. + +### Data Source for the Main Contract + +First, you define a regular data source for the main contract. The snippet below shows a simplified example data source for the [Uniswap](https://uniswap.io) exchange factory contract. Note the `NewExchange(address,address)` event handler. This is emitted when a new exchange contract is created on chain by the factory contract. + +```yaml +dataSources: + - kind: ethereum/contract + name: Factory + network: mainnet + source: + address: '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95' + abi: Factory + mapping: + kind: ethereum/events + apiVersion: 0.0.6 + language: wasm/assemblyscript + file: ./src/mappings/factory.ts + entities: + - Directory + abis: + - name: Factory + file: ./abis/factory.json + eventHandlers: + - event: NewExchange(address,address) + handler: handleNewExchange +``` + +### Data Source Templates for Dynamically Created Contracts + +Then, you add _data source templates_ to the manifest. These are identical to regular data sources, except that they lack a predefined contract address under `source`. Typically, you would define one template for each type of sub-contract managed or referenced by the parent contract. + +```yaml +dataSources: + - kind: ethereum/contract + name: Factory + # ... other source fields for the main contract ... +templates: + - name: Exchange + kind: ethereum/contract + network: mainnet + source: + abi: Exchange + mapping: + kind: ethereum/events + apiVersion: 0.0.6 + language: wasm/assemblyscript + file: ./src/mappings/exchange.ts + entities: + - Exchange + abis: + - name: Exchange + file: ./abis/exchange.json + eventHandlers: + - event: TokenPurchase(address,uint256,uint256) + handler: handleTokenPurchase + - event: EthPurchase(address,uint256,uint256) + handler: handleEthPurchase + - event: AddLiquidity(address,uint256,uint256) + handler: handleAddLiquidity + - event: RemoveLiquidity(address,uint256,uint256) + handler: handleRemoveLiquidity +``` + +### Instantiating a Data Source Template + +In the final step, you update your main contract mapping to create a dynamic data source instance from one of the templates. In this example, you would change the main contract mapping to import the `Exchange` template and call the `Exchange.create(address)` method on it to start indexing the new exchange contract. + +```typescript +import { Exchange } from '../generated/templates' + +export function handleNewExchange(event: NewExchange): void { + // Start indexing the exchange; `event.params.exchange` is the + // address of the new exchange contract + Exchange.create(event.params.exchange) +} +``` + +> **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks. +> +> If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created. + +### Data Source Context + +Data source contexts allow passing extra configuration when instantiating a template. In our example, let's say exchanges are associated with a particular trading pair, which is included in the `NewExchange` event. That information can be passed into the instantiated data source, like so: + +```typescript +import { Exchange } from '../generated/templates' + +export function handleNewExchange(event: NewExchange): void { + let context = new DataSourceContext() + context.setString('tradingPair', event.params.tradingPair) + Exchange.createWithContext(event.params.exchange, context) +} +``` + +Inside a mapping of the `Exchange` template, the context can then be accessed: + +```typescript +import { dataSource } from '@graphprotocol/graph-ts' + +let context = dataSource.context() +let tradingPair = context.getString('tradingPair') +``` + +There are setters and getters like `setString` and `getString` for all value types. + +## Start Blocks + +The `startBlock` is an optional setting that allows you to define from which block in the chain the data source will start indexing. Setting the start block allows the data source to skip potentially millions of blocks that are irrelevant. Typically, a subgraph developer will set `startBlock` to the block in which the smart contract of the data source was created. + +```yaml +dataSources: + - kind: ethereum/contract + name: ExampleSource + network: mainnet + source: + address: '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95' + abi: ExampleContract + startBlock: 6627917 + mapping: + kind: ethereum/events + apiVersion: 0.0.6 + language: wasm/assemblyscript + file: ./src/mappings/factory.ts + entities: + - User + abis: + - name: ExampleContract + file: ./abis/ExampleContract.json + eventHandlers: + - event: NewEvent(address,address) + handler: handleNewEvent +``` + +> **Note:** The contract creation block can be quickly looked up on Etherscan: +> +> 1. Search for the contract by entering its address in the search bar. +> 2. Click on the creation transaction hash in the `Contract Creator` section. +> 3. Load the transaction details page where you'll find the start block for that contract. + +## Call Handlers + +While events provide an effective way to collect relevant changes to the state of a contract, many contracts avoid generating logs to optimize gas costs. In these cases, a subgraph can subscribe to calls made to the data source contract. This is achieved by defining call handlers referencing the function signature and the mapping handler that will process calls to this function. To process these calls, the mapping handler will receive an `ethereum.Call` as an argument with the typed inputs to and outputs from the call. Calls made at any depth in a transaction's call chain will trigger the mapping, allowing activity with the data source contract through proxy contracts to be captured. + +Call handlers will only trigger in one of two cases: when the function specified is called by an account other than the contract itself or when it is marked as external in Solidity and called as part of another function in the same contract. + +> **Note:** Call handlers are not supported on Rinkeby, Goerli or Ganache. Call handlers currently depend on the Parity tracing API and these networks do not support it. + +### Defining a Call Handler + +To define a call handler in your manifest simply add a `callHandlers` array under the data source you would like to subscribe to. + +```yaml +dataSources: + - kind: ethereum/contract + name: Gravity + network: mainnet + source: + address: '0x731a10897d267e19b34503ad902d0a29173ba4b1' + abi: Gravity + mapping: + kind: ethereum/events + apiVersion: 0.0.6 + language: wasm/assemblyscript + entities: + - Gravatar + - Transaction + abis: + - name: Gravity + file: ./abis/Gravity.json + callHandlers: + - function: createGravatar(string,string) + handler: handleCreateGravatar +``` + +The `function` is the normalized function signature to filter calls by. The `handler` property is the name of the function in your mapping you would like to execute when the target function is called in the data source contract. + +### Mapping Function + +Each call handler takes a single parameter that has a type corresponding to the name of the called function. In the example subgraph above, the mapping contains a handler for when the `createGravatar` function is called and receives a `CreateGravatarCall` parameter as an argument: + +```typescript +import { CreateGravatarCall } from '../generated/Gravity/Gravity' +import { Transaction } from '../generated/schema' + +export function handleCreateGravatar(call: CreateGravatarCall): void { + let id = call.transaction.hash.toHex() + let transaction = new Transaction(id) + transaction.displayName = call.inputs._displayName + transaction.imageUrl = call.inputs._imageUrl + transaction.save() +} +``` + +The `handleCreateGravatar` function takes a new `CreateGravatarCall` which is a subclass of `ethereum.Call`, provided by `@graphprotocol/graph-ts`, that includes the typed inputs and outputs of the call. The `CreateGravatarCall` type is generated for you when you run `graph codegen`. + +## Block Handlers + +In addition to subscribing to contract events or function calls, a subgraph may want to update its data as new blocks are appended to the chain. To achieve this a subgraph can run a function after every block or after blocks that match a predefined filter. + +### Supported Filters + +```yaml +filter: + kind: call +``` + +_The defined handler will be called once for every block which contains a call to the contract (data source) the handler is defined under._ + +The absense of a filter for a block handler will ensure that the handler is called every block. A data source can only contain one block handler for each filter type. + +```yaml +dataSources: + - kind: ethereum/contract + name: Gravity + network: dev + source: + address: '0x731a10897d267e19b34503ad902d0a29173ba4b1' + abi: Gravity + mapping: + kind: ethereum/events + apiVersion: 0.0.6 + language: wasm/assemblyscript + entities: + - Gravatar + - Transaction + abis: + - name: Gravity + file: ./abis/Gravity.json + blockHandlers: + - handler: handleBlock + - handler: handleBlockWithCallToContract + filter: + kind: call +``` + +### Mapping Function + +The mapping function will receive an `ethereum.Block` as its only argument. Like mapping functions for events, this function can access existing subgraph entities in the store, call smart contracts and create or update entities. + +```typescript +import { ethereum } from '@graphprotocol/graph-ts' + +export function handleBlock(block: ethereum.Block): void { + let id = block.hash.toHex() + let entity = new Block(id) + entity.save() +} +``` + +## Anonymous Events + +If you need to process anonymous events in Solidity, that can be achieved by providing the topic 0 of the event, as in the example: + +```yaml +eventHandlers: + - event: LogNote(bytes4,address,bytes32,bytes32,uint256,bytes) + topic0: '0xbaa8529c00000000000000000000000000000000000000000000000000000000' + handler: handleGive +``` + +An event will only be triggered when both the signature and topic 0 match. By default, `topic0` is equal to the hash of the event signature. + +## Experimental features + +Starting from `specVersion` `0.0.4`, subgraph features must be explicitly declared in the `features` section at the top level of the manifest file, using their `camelCase` name, as listed in the table below: + +| Feature | Name | +| --------------------------------------------------------- | ------------------------- | +| [Non-fatal errors](#non-fatal-errors) | `nonFatalErrors` | +| [Full-text Search](#defining-fulltext-search-fields) | `fullTextSearch` | +| [Grafting](#grafting-onto-existing-subgraphs) | `grafting` | +| [IPFS on Ethereum Contracts](#ipfs-on-ethereum-contracts) | `ipfsOnEthereumContracts` | + +For instance, if a subgraph uses the **Full-Text Search** and the **Non-fatal Errors** features, the `features` field in the manifest should be: + +```yaml +specVersion: 0.0.4 +description: Gravatar for Ethereum +features: + - fullTextSearch + - nonFatalErrors +dataSources: ... +``` + +Note that using a feature without declaring it will incur in a **validation error** during subgraph deployment, but no errors will occur if a feature is declared but not used. + +### IPFS on Ethereum Contracts + +A common use case for combining IPFS with Ethereum is to store data on IPFS that would be too expensive to maintain on chain, and reference the IPFS hash in Ethereum contracts. + +Given such IPFS hashes, subgraphs can read the corresponding files from IPFS using `ipfs.cat` and `ipfs.map`. To do this reliably, however, it is required that these files are pinned on the IPFS node that the Graph Node indexing the subgraph connects to. In the case of the [hosted service](https://thegraph.com/hosted-service), this is [https://api.thegraph.com/ipfs/](https://api.thegraph.com/ipfs/). + +> **Note:** The Graph Network does not yet support `ipfs.cat` and `ipfs.map`, and developers should not deploy subgraphs using that functionality to the network via the Studio. + +In order to make this easy for subgraph developers, The Graph team wrote a tool for transfering files from one IPFS node to another, called [ipfs-sync](https://github.com/graphprotocol/ipfs-sync). + +> **[Feature Management](#experimental-features):** `ipfsOnEthereumContracts` must be declared under `features` in the subgraph manifest. + +### Non-fatal errors + +Indexing errors on already synced subgraphs will, by default, cause the subgraph to fail and stop syncing. Subgraphs can alternatively be configured to continue syncing in the presence of errors, by ignoring the changes made by the handler which provoked the error. This gives subgraph authors time to correct their subgraphs while queries continue to be served against the latest block, though the results will possibly be inconsistent due to the bug that caused the error. Note that some errors are still always fatal, to be non-fatal the error must be known to be deterministic. + +> **Note:** The Graph Network does not yet support non-fatal errors, and developers should not deploy subgraphs using that functionality to the network via the Studio. + +Enabling non-fatal errors requires setting the following feature flag on the subgraph manifest: + +```yaml +specVersion: 0.0.4 +description: Gravatar for Ethereum +features: + - fullTextSearch + ... +``` + +The query must also opt-in to querying data with potential inconsistencies through the `subgraphError` argument. It is also recommended to query `_meta` to check if the subgraph has skipped over errors, as in the example: + +```graphql +foos(first: 100, subgraphError: allow) { + id +} + +_meta { + hasIndexingErrors +} +``` + +If the subgraph encounters an error that query will return both the data and a graphql error with the message `"indexing_error"`, as in this example response: + +```graphql +"data": { + "foos": [ + { + "id": "fooId" + } + ], + "_meta": { + "hasIndexingErrors": true + } +}, +"errors": [ + { + "message": "indexing_error" + } +] +``` + +### Grafting onto Existing Subgraphs + +When a subgraph is first deployed, it starts indexing events at the genesis block of the corresponding chain (or at the `startBlock` defined with each data source) In some circumstances, it is beneficial to reuse the data from an existing subgraph and start indexing at a much later block. This mode of indexing is called _Grafting_. Grafting is, for example, useful during development to get past simple errors in the mappings quickly, or to temporarily get an existing subgraph working again after it has failed. + +> **Note:** Grafting requires that the Indexer has indexed the base subgraph. It is not recommended on The Graph Network at this time, and developers should not deploy subgraphs using that functionality to the network via the Studio. + +A subgraph is grafted onto a base subgraph when the subgraph manifest in `subgraph.yaml` contains a `graft` block at the toplevel: + +```yaml +description: ... +graft: + base: Qm... # Subgraph ID of base subgraph + block: 7345624 # Block number +``` + +When a subgraph whose manifest contains a `graft` block is deployed, Graph Node will copy the data of the `base` subgraph up to and including the given `block` and then continue indexing the new subgraph from that block on. The base subgraph must exist on the target Graph Node instance and must have indexed up to at least the given block. Because of this restriction, grafting should only be used during development or during an emergency to speed up producing an equivalent non-grafted subgraph. + +Because grafting copies rather than indexes base data it is much quicker in getting the subgraph to the desired block than indexing from scratch, though the initial data copy can still take several hours for very large subgraphs. While the grafted subgraph is being initialized, the Graph Node will log information about the entity types that have already been copied. + +The grafted subgraph can use a GraphQL schema that is not identical to the one of the base subgraph, but merely compatible with it. It has to be a valid subgraph schema in its own right but may deviate from the base subgraph's schema in the following ways: + +- It adds or removes entity types +- It removes attributes from entity types +- It adds nullable attributes to entity types +- It turns non-nullable attributes into nullable attributes +- It adds values to enums +- It adds or removes interfaces +- It changes for which entity types an interface is implemented + +> **[Feature Management](#experimental-features):** `grafting` must be declared under `features` in the subgraph manifest. diff --git a/pages/vi/developer/define-subgraph-hosted.mdx b/pages/vi/developer/define-subgraph-hosted.mdx new file mode 100644 index 000000000000..92bf5bd8cd2f --- /dev/null +++ b/pages/vi/developer/define-subgraph-hosted.mdx @@ -0,0 +1,35 @@ +--- +title: Define a Subgraph +--- + +A subgraph defines which data The Graph will index from Ethereum, and how it will store it. Once deployed, it will form a part of a global graph of blockchain data. + +![Define a Subgraph](/img/define-subgraph.png) + +The subgraph definition consists of a few files: + +- `subgraph.yaml`: a YAML file containing the subgraph manifest + +- `schema.graphql`: a GraphQL schema that defines what data is stored for your subgraph, and how to query it via GraphQL + +- `AssemblyScript Mappings`: [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) code that translates from the event data to the entities defined in your schema (e.g. `mapping.ts` in this tutorial) + +Before you go into detail about the contents of the manifest file, you need to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) which you will need to build and deploy a subgraph. + +## Install the Graph CLI + +The Graph CLI is written in JavaScript, and you will need to install either `yarn` or `npm` to use it; it is assumed that you have yarn in what follows. + +Once you have `yarn`, install the Graph CLI by running + +**Install with yarn:** + +```bash +yarn global add @graphprotocol/graph-cli +``` + +**Install with npm:** + +```bash +npm install -g @graphprotocol/graph-cli +``` diff --git a/pages/vi/developer/deprecating-a-subgraph.mdx b/pages/vi/developer/deprecating-a-subgraph.mdx new file mode 100644 index 000000000000..f8966e025c13 --- /dev/null +++ b/pages/vi/developer/deprecating-a-subgraph.mdx @@ -0,0 +1,17 @@ +--- +title: Deprecating a Subgraph +--- + +So you'd like to deprecate your subgraph on The Graph Explorer. You've come to the right place! Follow the steps below: + +1. Visit the contract address [here](https://etherscan.io/address/0xadca0dd4729c8ba3acf3e99f3a9f471ef37b6825#writeProxyContract) +2. Call 'deprecateSubgraph' with your own address as the first parameter +3. In the 'subgraphNumber' field, list 0 if it's the first subgraph you're publishing, 1 if it's your second, 2 if it's your third, etc. +4. Inputs for #2 and #3 can be found in your `` which is composed of the `{graphAccount}-{subgraphNumber}`. For example, the [Sushi Subgraph's](https://thegraph.com/explorer/subgraph?id=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0&version=0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0-0&view=Overview) ID is `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0>`, which is a combination of `graphAccount` = `<0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0>` and `subgraphNumber` = `<0>` +5. Voila! Your subgraph will no longer show up on searches on The Graph Explorer. Please note the following: + +- Curators will not be able to signal on the subgraph anymore +- Curators that already signaled on the subgraph will be able to withdraw their signal at an average share price +- Deprecated subgraphs will be indicated with an error message. + +If you interacted with the now deprecated subgraph, you'll be able to find it in your user profile under the "Subgraphs", "Indexing", or "Curating" tab respectively. diff --git a/pages/vi/developer/developer-faq.mdx b/pages/vi/developer/developer-faq.mdx new file mode 100644 index 000000000000..41449c60e5ab --- /dev/null +++ b/pages/vi/developer/developer-faq.mdx @@ -0,0 +1,172 @@ +--- +title: Developer FAQs +--- + +### 1. Can I delete my subgraph? + +It is not possible to delete subgraphs once they are created. + +### 2. Can I change my subgraph name? + +No. Once a subgraph is created, the name cannot be changed. Make sure to think of this carefully before you create your subgraph so it is easily searchable and identifiable by other dapps. + +### 3. Can I change the GitHub account associated with my subgraph? + +No. Once a subgraph is created, the associated GitHub account cannot be changed. Make sure to think of this carefully before you create your subgraph. + +### 4. Am I still able to create a subgraph if my smart contracts don't have events? + +It is highly recommended that you structure your smart contracts to have events associated with data you are interested in querying. Event handlers in the subgraph are triggered by contract events, and are by far the fastest way to retrieve useful data. + +If the contracts you are working with do not contain events, your subgraph can use call and block handlers to trigger indexing. Although this is not recommended as performance will be significantly slower. + +### 5. Is it possible to deploy one subgraph with the same name for multiple networks? + +You will need separate names for multiple networks. While you can't have different subgraphs under the same name, there are convenient ways of having a single codebase for multiple networks. Find more on this in our documentation: [Redeploying a Subgraph](/hosted-service/deploy-subgraph-hosted#redeploying-a-subgraph) + +### 6. How are templates different from data sources? + +Templates allow you to create data sources on the fly, while your subgraph is indexing. It might be the case that your contract will spawn new contracts as people interact with it, and since you know the shape of those contracts (ABI, events, etc) up front you can define how you want to index them in a template and when they are spawned your subgraph will create a dynamic data source by supplying the contract address. + +Check out the "Instantiating a data source template" section on: [Data Source Templates](/developer/create-subgraph-hosted#data-source-templates). + +### 7. How do I make sure I'm using the latest version of graph-node for my local deployments? + +You can run the following command: + +```sh +docker pull graphprotocol/graph-node:latest +``` + +**NOTE:** docker / docker-compose will always use whatever graph-node version was pulled the first time you ran it, so it is important to do this to make sure you are up to date with the latest version of graph-node. + +### 8. How do I call a contract function or access a public state variable from my subgraph mappings? + +Take a look at `Access to smart contract` state inside the section [AssemblyScript API](/developer/assemblyscript-api). + +### 9. Is it possible to set up a subgraph using `graph init` from `graph-cli` with two contracts? Or should I manually add another datasource in `subgraph.yaml` after running `graph init`? + +Unfortunately this is currently not possible. `graph init` is intended as a basic starting point, from which you can then add more data sources manually. + +### 10. I want to contribute or add a GitHub issue, where can I find the open source repositories? + +- [graph-node](https://github.com/graphprotocol/graph-node) +- [graph-cli](https://github.com/graphprotocol/graph-cli) +- [graph-ts](https://github.com/graphprotocol/graph-ts) + +### 11. What is the recommended way to build "autogenerated" ids for an entity when handling events? + +If only one entity is created during the event and if there's nothing better available, then the transaction hash + log index would be unique. You can obfuscate these by converting that to Bytes and then piping it through `crypto.keccak256` but this won't make it more unique. + +### 12. When listening to multiple contracts, is it possible to select the contract order to listen to events? + +Within a subgraph, the events are always processed in the order they appear in the blocks, regardless of whether that is across multiple contracts or not. + +### 13. Is it possible to differentiate between networks (mainnet, Kovan, Ropsten, local) from within event handlers? + +Yes. You can do this by importing `graph-ts` as per the example below: + +```javascript +import { dataSource } from '@graphprotocol/graph-ts' + +dataSource.network() +dataSource.address() +``` + +### 14. Do you support block and call handlers on Rinkeby? + +On Rinkeby we support block handlers, but without `filter: call`. Call handlers are not supported for the time being. + +### 15. Can I import ethers.js or other JS libraries into my subgraph mappings? + +Not currently, as mappings are written in AssemblyScript. One possible alternative solution to this is to store raw data in entities and perform logic that requires JS libraries on the client. + +### 16. Is it possible to specifying what block to start indexing on? + +Yes. `dataSources.source.startBlock` in the `subgraph.yaml` file specifies the number of the block that the data source starts indexing from. In most cases we suggest using the block in which the contract was created: Start blocks + +### 17. Are there some tips to increase performance of indexing? My subgraph is taking a very long time to sync. + +Yes, you should take a look at the optional start block feature to start indexing from the block that the contract was deployed: [Start blocks](/developer/create-subgraph-hosted#start-blocks) + +### 18. Is there a way to query the subgraph directly to determine what the latest block number it has indexed? + +Yes! Try the following command, substituting "organization/subgraphName" with the organization under it is published and the name of your subgraph: + +```sh +curl -X POST -d '{ "query": "{indexingStatusForCurrentVersion(subgraphName: \"organization/subgraphName\") { chains { latestBlock { hash number }}}}"}' https://api.thegraph.com/index-node/graphql +``` + +### 19. What networks are supported by The Graph? + +The graph-node supports any EVM-compatible JSON RPC API chain. + +The Graph Network supports subgraphs indexing mainnet Ethereum: + +- `mainnet` + +In the Hosted Service, the following networks are supported: + +- Ethereum mainnet +- Kovan +- Rinkeby +- Ropsten +- Goerli +- PoA-Core +- PoA-Sokol +- xDAI +- NEAR +- NEAR testnet +- Matic +- Mumbai +- Fantom +- Binance Smart Chain +- Clover +- Avalanche +- Fuji +- Celo +- Celo-Alfajores +- Fuse +- Moonbeam +- Arbitrum One +- Arbitrum Testnet (on Rinkeby) +- Optimism +- Optimism Testnet (on Kovan) + +There is work in progress towards integrating other blockchains, you can read more in our repo: [RFC-0003: Multi-Blockchain Support](https://github.com/graphprotocol/rfcs/pull/8/files). + +### 20. Is it possible to duplicate a subgraph to another account or endpoint without redeploying? + +You have to redeploy the subgraph, but if the subgraph ID (IPFS hash) doesn't change, it won't have to sync from the beginning. + +### 21. Is this possible to use Apollo Federation on top of graph-node? + +Federation is not supported yet, although we do want to support it in the future. At the moment, something you can do is use schema stitching, either on the client or via a proxy service. + +### 22. Is there a limit to how many objects The Graph can return per query? + +By default query responses are limited to 100 items per collection. If you want to receive more, you can go up to 1000 items per collection and beyond that you can paginate with: + +```graphql +someCollection(first: 1000, skip: ) { ... } +``` + +### 23. If my dapp frontend uses The Graph for querying, do I need to write my query key into the frontend directly? What if we pay query fees for users – will malicious users cause our query fees to be very high? + +Currently, the recommended approach for a dapp is to add the key to the frontend and expose it to end users. That said, you can limit that key to a host name, like _yourdapp.io_ and subgraph. The gateway is currently being run by Edge & Node. Part of the responsibility of a gateway is to monitor for abusive behavior and block traffic from malicious clients. + +### 24. Where do I go to find my current subgraph on the Hosted Service? + +Head over to the Hosted Service in order to find subgraphs that you or others deployed to the Hosted Service. You can find it [here.](https://thegraph.com/hosted-service) + +### 25. Will the Hosted Service start charging query fees? + +The Graph will never charge for the Hosted Service. The Graph is a decentralized protocol, and charging for a centralized service is not aligned with The Graph’s values. The Hosted Service was always a temporary step to help get to the decentralized network. Developers will have a sufficient amount of time to migrate to the decentralized network as they are comfortable. + +### 26. When will the Hosted Service be shut down? + +If and when there are plans to do this, the community will be notified well ahead of time with considerations made for any subgraphs built on the Hosted Service. + +### 27. How do I upgrade a subgraph on mainnet? + +If you’re a subgraph developer, you can upgrade a new version of your subgraph to the Studio using the CLI. It’ll be private at that point but if you’re happy with it, you can publish to the decentralized Graph Explorer. This will create a new version of your subgraph that Curators can start signaling on. diff --git a/pages/vi/developer/distributed-systems.mdx b/pages/vi/developer/distributed-systems.mdx new file mode 100644 index 000000000000..894fcbe2e18b --- /dev/null +++ b/pages/vi/developer/distributed-systems.mdx @@ -0,0 +1,132 @@ +--- +title: Distributed Systems +--- + +The Graph is a protocol implemented as a distributed system. + +Connections fail. Requests arrive out of order. Different computers with out-of-sync clocks and states process related requests. Servers restart. Re-orgs happen between requests. These problems are inherent to all distributed systems but are exacerbated in systems operating at a global scale. + +Consider this example of what may occur if a client polls an Indexer for the latest data during a re-org. + +1. Indexer ingests block 8 +2. Request served to the client for block 8 +3. Indexer ingests block 9 +4. Indexer ingests block 10A +5. Request served to the client for block 10A +6. Indexer detects reorg to 10B and rolls back 10A +7. Request served to the client for block 9 +8. Indexer ingests block 10B +9. Indexer ingests block 11 +10. Request served to the client for block 11 + +From the point of view of the Indexer, things are progressing forward logically. Time is moving forward, though we did have to roll back an uncle block and play the block under consensus forward on top of it. Along the way, the Indexer serves requests using the latest state it knows about at that time. + +From the point of view of the client, however, things appear chaotic. The client observes that the responses were for blocks 8, 10, 9, and 11 in that order. We call this the "block wobble" problem. When a client experiences block wobble, data may appear to contradict itself over time. The situation worsens when we consider that Indexers do not all ingest the latest blocks simultaneously, and your requests may be routed to multiple Indexers. + +It is the responsibility of the client and server to work together to provide consistent data to the user. Different approaches must be used depending on the desired consistency as there is no one right program for every problem. + +Reasoning through the implications of distributed systems is hard, but the fix may not be! We've established APIs and patterns to help you navigate some common use-cases. The following examples illustrate those patterns but still elide details required by production code (like error handling and cancellation) to not obfuscate the main ideas. + +## Polling for updated data + +The Graph provides the `block: { number_gte: $minBlock }` API, which ensures that the response is for a single block equal or higher to `$minBlock`. If the request is made to a `graph-node` instance and the min block is not yet synced, `graph-node` will return an error. If `graph-node` has synced min block, it will run the response for the latest block. If the request is made to an Edge & Node Gateway, the Gateway will filter out any Indexers that have not yet synced min block and make the request for the latest block the Indexer has synced. + +We can use `number_gte` to ensure that time never travels backward when polling for data in a loop. Here is an example: + +```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 = ` + { + protocol(block: { number_gte: ${minBlock} } id: "0") { + paused + } + _meta { + block { + number + } + } + }` + + const response = await graphql(query) + 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 + } +} +``` + +## Fetching a set of related items + +Another use-case is retrieving a large set or, more generally, retrieving related items across multiple requests. Unlike the polling case (where the desired consistency was to move forward in time), the desired consistency is for a single point in time. + +Here we will use the `block: { hash: $blockHash }` argument to pin all of our results to the same block. + +```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. + let query = ` + { + domains(first: ${perPage}) { + name + id + } + _meta { + block { + hash + } + } + }` + + let data = await graphql(query) + let result = data.domains.map((d) => d.name) + let blockHash = data._meta.block.hash + + // 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 = ` + { + domains(first: ${perPage}, where: { id_gt: "${lastID}" }, block: { hash: "${blockHash}" }) { + name + id + } + }` + + data = await graphql(query) + + // Accumulate domain names into the result + for (domain of data.domains) { + result.push(domain.name) + } + } + return result +} +``` + +Note that in case of a re-org, the client will need to retry from the first request to update the block hash to a non-uncle block. diff --git a/pages/vi/developer/graphql-api.mdx b/pages/vi/developer/graphql-api.mdx new file mode 100644 index 000000000000..f9cb6214fcd9 --- /dev/null +++ b/pages/vi/developer/graphql-api.mdx @@ -0,0 +1,267 @@ +--- +title: GraphQL API +--- + +This guide explains the GraphQL Query API that is used for the Graph Protocol. + +## Queries + +In your subgraph schema you define types called `Entities`. For each `Entity` type, an `entity` and `entities` field will be generated on the top-level `Query` type. Note that `query` does not need to be included at the top of the `graphql` query when using The Graph. + +#### Examples + +Query for a single `Token` entity defined in your schema: + +```graphql +{ + token(id: "1") { + id + owner + } +} +``` + +**Note:** When querying for a single entity, the `id` field is required and it must be a string. + +Query all `Token` entities: + +```graphql +{ + tokens { + id + owner + } +} +``` + +### Sorting + +When querying a collection, the `orderBy` parameter may be used to sort by a specific attribute. Additionally, the `orderDirection` can be used to specify the sort direction, `asc` for ascending or `desc` for descending. + +#### Example + +```graphql +{ + tokens(orderBy: price, orderDirection: asc) { + id + owner + } +} +``` + +### Pagination + +When querying a collection, the `first` parameter can be used to paginate from the beginning of the collection. It is worth noting that the default sort order is by ID in ascending alphanumeric order, not by creation time. + +Further, the `skip` parameter can be used to skip entities and paginate. e.g. `first:100` shows the first 100 entities and `first:100, skip:100` shows the next 100 entities. + +Queries should avoid using very large `skip` values since they generally perform poorly. For retrieving a large number of items, it is much better to page through entities based on an attribute as shown in the last example. + +#### Example + +Query the first 10 tokens: + +```graphql +{ + tokens(first: 10) { + id + owner + } +} +``` + +To query for groups of entities in the middle of a collection, the `skip` parameter may be used in conjunction with the `first` parameter to skip a specified number of entities starting at the beginning of the collection. + +#### Example + +Query 10 `Token` entities, offset by 10 places from the beginning of the collection: + +```graphql +{ + tokens(first: 10, skip: 10) { + id + owner + } +} +``` + +#### Example + +If a client needs to retrieve a large number of entities, it is much more performant to base queries on an attribute and filter by that attribute. For example, a client would retrieve a large number of tokens using this query: + +```graphql +{ + query manyTokens($lastID: String) { + tokens(first: 1000, where: { id_gt: $lastID }) { + id + owner + } + } +} +``` + +The first time, it would send the query with `lastID = ""`, and for subsequent requests would set `lastID` to the `id` attribute of the last entity in the previous request. This approach will perform significantly better than using increasing `skip` values. + +### Filtering + +You can use the `where` parameter in your queries to filter for different properties. You can filter on mulltiple values within the `where` parameter. + +#### Example + +Query challenges with `failed` outcome: + +```graphql +{ + challenges(where: { outcome: "failed" }) { + challenger + outcome + application { + id + } + } +} +``` + +You can use suffixes like `_gt`, `_lte` for value comparison: + +#### Example + +```graphql +{ + applications(where: { deposit_gt: "10000000000" }) { + id + whitelisted + deposit + } +} +``` + +Full list of parameter suffixes: + +```graphql +_not +_gt +_lt +_gte +_lte +_in +_not_in +_contains +_not_contains +_starts_with +_ends_with +_not_starts_with +_not_ends_with +``` + +Please note that some suffixes are only supported for specific types. For example, `Boolean` only supports `_not`, `_in`, and `_not_in`. + +### Time-travel queries + +You can query the state of your entities not just for the latest block, which is the by default, but also for an arbitrary block in the past. The block at which a query should happen can be specified either by its block number or its block hash by including a `block` argument in the toplevel fields of queries. + +The result of such a query will not change over time, i.e., querying at a certain past block will return the same result no matter when it is executed, with the exception that if you query at a block very close to the head of the Ethereum chain, the result might change if that block turns out to not be on the main chain and the chain gets reorganized. Once a block can be considered final, the result of the query will not change. + +Note that the current implementation is still subject to certain limitations that might violate these gurantees. The implementation can not always tell that a given block hash is not on the main chain at all, or that the result of a query by block hash for a block that can not be considered final yet might be influenced by a block reorganization running concurrently with the query. They do not affect the results of queries by block hash when the block is final and known to be on the main chain. [This issue](https://github.com/graphprotocol/graph-node/issues/1405) explains what these limitations are in detail. + +#### Example + +```graphql +{ + challenges(block: { number: 8000000 }) { + challenger + outcome + application { + id + } + } +} +``` + +This query will return `Challenge` entities, and their associated `Application` entities, as they existed directly after processing block number 8,000,000. + +#### Example + +```graphql +{ + challenges(block: { hash: "0x5a0b54d5dc17e0aadc383d2db43b0a0d3e029c4c" }) { + challenger + outcome + application { + id + } + } +} +``` + +This query will return `Challenge` entities, and their associated `Application` entities, as they existed directly after processing the block with the given hash. + +### Fulltext Search Queries + +Fulltext search query fields provide an expressive text search API that can be added to the subgraph schema and customized. Refer to [Defining Fulltext Search Fields](/developer/create-subgraph-hosted#defining-fulltext-search-fields) to add fulltext search to your subgraph. + +Fulltext search queries have one required field, `text`, for supplying search terms. Several special fulltext operators are available to be used in this `text` search field. + +Fulltext search operators: + +| Symbol | Operator | Description | +| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | +| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | +| `<->` | `Follow by` | Specify the distance between two words. | +| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | + +#### Examples + +Using the `or` operator, this query will filter to blog entities with variations of either "anarchism" or "crumpet" in their fulltext fields. + +```graphql +{ + blogSearch(text: "anarchism | crumpets") { + id + title + body + author + } +} +``` + +The `follow by` operator specifies a words a specific distance apart in the fulltext documents. The following query will return all blogs with variations of "decentralize" followed by "philosophy" + +```graphql +{ + blogSearch(text: "decentralized <-> philosophy") { + id + title + body + author + } +} +``` + +Combine fulltext operators to make more complex filters. With a pretext search operator combined with a follow by this example query will match all blog entities with words that start with "lou" followed by "music". + +```graphql +{ + blogSearch(text: "lou:* <-> music") { + id + title + body + author + } +} +``` + +## Schema + +The schema of your data source--that is, the entity types, values, and relationships that are available to query--are defined through the [GraphQL Interface Definition Langauge (IDL)](https://facebook.github.io/graphql/draft/#sec-Type-System). + +GraphQL schemas generally define root types for `queries`, `subscriptions` and `mutations`. The Graph only supports `queries`. The root `Query` type for your subgraph is automatically generated from the GraphQL schema that's included in your subgraph manifest. + +> **Note:** Our API does not expose mutations because developers are expected to issue transactions directly against the underlying blockchain from their applications. + +### Entities + +All GraphQL types with `@entity` directives in your schema will be treated as entities and must have an `ID` field. + +> **Note:** Currently, all types in your schema must have an `@entity` directive. In the future, we will treat types without an `@entity` directive as value objects, but this is not yet supported. diff --git a/pages/vi/developer/matchstick.mdx b/pages/vi/developer/matchstick.mdx new file mode 100644 index 000000000000..3cf1ec761bb9 --- /dev/null +++ b/pages/vi/developer/matchstick.mdx @@ -0,0 +1,267 @@ +--- +title: Unit Testing Framework +--- + +Matchstick is a unit testing framework, developed by [LimeChain](https://limechain.tech/), that enables subgraph developers to test their mapping logic in a sandboxed environment and deploy their subgraphs with confidence! + +Follow the [Matchstick installation guide](https://github.com/LimeChain/matchstick/blob/main/README.md#quick-start-) to install. Now, you can move on to writing your first unit test. + +## 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). + +Assuming we have the following handler function (along with two helper functions to make our life easier): + +```javascript +export function handleNewGravatar(event: NewGravatar): void { + let gravatar = new Gravatar(event.params.id.toHex()) + gravatar.owner = event.params.owner + gravatar.displayName = event.params.displayName + gravatar.imageUrl = event.params.imageUrl + gravatar.save() +} + +export function handleNewGravatars(events: NewGravatar[]): void { + events.forEach((event) => { + handleNewGravatar(event) + }) +} + +export function createNewGravatarEvent( + id: i32, + ownerAddress: string, + displayName: string, + imageUrl: string +): NewGravatar { + let mockEvent = newMockEvent() + let newGravatarEvent = new NewGravatar( + mockEvent.address, + mockEvent.logIndex, + mockEvent.transactionLogIndex, + mockEvent.logType, + mockEvent.block, + mockEvent.transaction, + mockEvent.parameters + ) + newGravatarEvent.parameters = new Array() + let idParam = new ethereum.EventParam('id', ethereum.Value.fromI32(id)) + let addressParam = new ethereum.EventParam( + 'ownderAddress', + ethereum.Value.fromAddress(Address.fromString(ownerAddress)) + ) + let displayNameParam = new ethereum.EventParam('displayName', ethereum.Value.fromString(displayName)) + let imageUrlParam = new ethereum.EventParam('imageUrl', ethereum.Value.fromString(imageUrl)) + + newGravatarEvent.parameters.push(idParam) + newGravatarEvent.parameters.push(addressParam) + newGravatarEvent.parameters.push(displayNameParam) + newGravatarEvent.parameters.push(imageUrlParam) + + return newGravatarEvent +} +``` + +We first have to create a test file in our project. We have chosen the name `gravity.test.ts`. In the newly created file we need to define a function named `runTests()`. It is important that the function has that exact name. This is an example of how our tests might look like: + +```typescript +import { clearStore, test, assert } from 'matchstick-as/assembly/index' +import { Gravatar } from '../../generated/schema' +import { NewGravatar } from '../../generated/Gravity/Gravity' +import { createNewGravatarEvent, handleNewGravatars } from '../mappings/gravity' + +export function runTests(): void { + test('Can call mappings with custom events', () => { + // Initialise + let gravatar = new Gravatar('gravatarId0') + gravatar.save() + + // Call mappings + let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') + + let anotherGravatarEvent = createNewGravatarEvent(3546, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') + + handleNewGravatars([newGravatarEvent, anotherGravatarEvent]) + + assert.fieldEquals('Gravatar', 'gravatarId0', 'id', 'gravatarId0') + assert.fieldEquals('Gravatar', '12345', 'owner', '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7') + assert.fieldEquals('Gravatar', '3546', 'displayName', 'cap') + + clearStore() + }) + + 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: + +- We're setting up our initial state and adding one custom Gravatar entity; +- We define two `NewGravatar` event objects along with their data, using the `createNewGravatarEvent()` function; +- We're calling out handler methods for those events - `handleNewGravatars()` and passing in the list of our custom events; +- We assert the state of the store. How does that work? - We're passing a unique combination of Entity type and id. Then we check a specific field on that Entity and assert that it has the value we expect it to have. We're doing this both for the initial Gravatar Entity we added to the store, as well as the two Gravatar entities that gets added when the handler function is called; +- And lastly - we're cleaning the store using `clearStore()` so that our next test can start with a fresh and empty store object. We can define as many test blocks as we want. + +There we go - we've created our first test! 👏 + +❗ **IMPORTANT:** _In order for the tests to work, we need to export the `runTests()` function in our mappings file. It won't be used there, but the export statement has to be there so that it can get picked up by Rust later when running the tests._ + +You can export the tests wrapper function in your mappings file like this: + +``` +export { runTests } from "../tests/gravity.test.ts"; +``` + +❗ **IMPORTANT:** _Currently there's an issue with using Matchstick when deploying your subgraph. Please only use Matchstick for local testing, and remove/comment out this line (`export { runTests } from "../tests/gravity.test.ts"`) once you're done. We expect to resolve this issue shortly, sorry for the inconvenience!_ + +_If you don't remove that line, you will get the following error message when attempting to deploy your subgraph:_ + +``` +/... +Mapping terminated before handling trigger: oneshot canceled +.../ +``` + +Now in order to run our tests you simply need to run the following in your subgraph root folder: + +`graph test Gravity` + +And if all goes well you should be greeted with the following: + +![Matchstick saying “All tests passed!”](/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: + +```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' +import { NewGravatar } from '../../generated/Gravity/Gravity' +import { handleNewGravatars, createNewGravatarEvent } from './mapping' + +let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') + +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' +import { store } from 'matchstick-as/assembly/store' +import { handleNewGravatars, createNewGravatarEvent } from './mapping' + +let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') + +let anotherGravatarEvent = createNewGravatarEvent(3546, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') + +handleNewGravatars([newGravatarEvent, anotherGravatarEvent]) +``` + +``` +export function handleNewGravatars(events: NewGravatar[]): void { + events.forEach(event => { + handleNewGravatar(event); + }); +} +``` + +### Mocking contract calls + +Users can mock contract calls: + +```typescript +import { addMetadata, assert, createMockedFunction, clearStore, test } from 'matchstick-as/assembly/index' +import { Gravity } from '../../generated/Gravity/Gravity' +import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts' + +let contractAddress = Address.fromString('0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7') +let expectedResult = Address.fromString('0x90cBa2Bbb19ecc291A12066Fd8329D65FA1f1947') +let bigIntParam = BigInt.fromString('1234') +createMockedFunction(contractAddress, 'gravatarToOwner', 'gravatarToOwner(uint256):(address)') + .withArgs([ethereum.Value.fromSignedBigInt(bigIntParam)]) + .returns([ethereum.Value.fromAddress(Address.fromString('0x90cBa2Bbb19ecc291A12066Fd8329D65FA1f1947'))]) + +let gravity = Gravity.bind(contractAddress) +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') +createMockedFunction(contractAddress, 'getGravatar', 'getGravatar(address):(string,string)') + .withArgs([ethereum.Value.fromAddress(contractAddress)]) + .reverts() +``` + +### 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: + +```typescript +import { assert } from 'matchstick-as/assembly/index' +import { Gravatar } from '../generated/schema' + +let gravatar = new Gravatar('gravatarId0') +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. + +### 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: + +```typescript +// Read +let logType = newGravatarEvent.logType + +// Write +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: + +```typescript +assert.notInStore('Gravatar', '23') +``` + +### Test run time duration in the log output + +The log output includes the test run duration. Here's an example: + +`Jul 09 14:54:42.420 INFO Program execution time: 10.06022ms` + +## 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. diff --git a/pages/vi/developer/publish-subgraph.mdx b/pages/vi/developer/publish-subgraph.mdx new file mode 100644 index 000000000000..2f35f5eb1bae --- /dev/null +++ b/pages/vi/developer/publish-subgraph.mdx @@ -0,0 +1,27 @@ +--- +title: Publish a Subgraph to the Decentralized Network +--- + +Once your subgraph has been [deployed to the Subgraph Studio](/studio/deploy-subgraph-studio), you have tested it out, and are ready to put it into production, you can then publish it to the decentralized network. + +Publishing a Subgraph to the decentralized network makes it available for [curators](/curating) to begin curating on it, and [indexers](/indexing) to begin indexing it. + +For a walkthrough of how to publish a subgraph to the decentralized network, see [this video](https://youtu.be/HfDgC2oNnwo?t=580). + +### Networks + +The decentralized network currently supports both Rinkeby and Ethereum Mainnet. + +### Publishing a subgraph + +Subgraphs can be published to the decentralized network directly from the Subgraph Studio dashboard by clicking on the **Publish** button. Once a subgraph is published, it will be available to view in the [Graph Explorer](https://thegraph.com/explorer/). + +- Subgraphs published to Rinkeby can index and query data from either the Rinkeby network or Ethereum Mainnet. + +- Subgraphs published to Ethereum Mainnet can only index and query data from Ethereum Mainnet, meaning that you cannot publish subgraphs to the main decentralized network that index and query testnet data. + +- When publishing a new version for an existing subgraph the same rules apply as above. + +### Updating metadata for a published subgraph + +Once your subgraph has been published to the decentralized network, you can modify the metadata at any time by making the update in the Subgraph Studio dashboard of the subgraph. After saving the changes and publishing your updates to the network, they will be reflected in the Graph Explorer. This won’t create a new version, as your deployment hasn’t changed. diff --git a/pages/vi/developer/query-the-graph.mdx b/pages/vi/developer/query-the-graph.mdx new file mode 100644 index 000000000000..ae480b1e6883 --- /dev/null +++ b/pages/vi/developer/query-the-graph.mdx @@ -0,0 +1,32 @@ +--- +title: Query The Graph +--- + +With the subgraph deployed, visit the [Graph Explorer](https://thegraph.com/explorer) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. + +An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. + +#### Example + +This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: + +```graphql +{ + counters { + id + value + } +} +``` + +## Using The Graph Explorer + +Each subgraph published to the decentralized Graph Explorer has a unique query URL that you can find by navigating to the subgraph details page and clicking on the "Query" button on the top right corner. This will open a side pane that will give you the unique query URL of the subgraph as well as some instructions about how to query it. + +![Query Subgraph Pane](/img/query-subgraph-pane.png) + +As you can notice, this query URL must use a unique API key. You can create and manage your API keys in the [Subgraph Studio](https://thegraph.com/studio) in the "API Keys" section. Learn more about how to use Subgraph Studio [here](/studio/subgraph-studio). + +Querying subgraphs using your API keys will generate query fees that will be paid in GRT. You can learn more about billing [here](/studio/billing). + +You can also use the GraphQL playground in the "Playground" tab to query a subgraph within The Graph Explorer. diff --git a/pages/vi/developer/querying-from-your-app.mdx b/pages/vi/developer/querying-from-your-app.mdx new file mode 100644 index 000000000000..3c7f001e4bf6 --- /dev/null +++ b/pages/vi/developer/querying-from-your-app.mdx @@ -0,0 +1,136 @@ +--- +title: Querying from an Application +--- + +Once a subgraph is deployed to the Subgraph Studio or to the Graph Explorer, you will be given the endpoint for your GraphQL API that should look something like this: + +**Subgraph Studio (testing endpoint)** + +```sh +Queries (HTTP) +https://api.studio.thegraph.com/query/// +``` + +**Trình khám phá Graph** + +```sh +Queries (HTTP) +https://gateway.thegraph.com/api//subgraphs/id/ +``` + +Using the GraphQL endpoint, you can use various GraphQL Client libraries to query the subgraph and populate your app with the data indexed by the subgraph. + +Here are a couple of the more popular GraphQL clients in the ecosystem and how to use them: + +### Apollo client + +[Apollo client](https://www.apollographql.com/docs/) supports web projects including frameworks like React and Vue, as well as mobile clients like iOS, Android, and React Native. + +Let's look at how fetch data from a subgraph with Apollo client in a web project. + +First, install `@apollo/client` and `graphql`: + +```sh +npm install @apollo/client graphql +``` + +Then you can query the API with the following code: + +```javascript +import { ApolloClient, InMemoryCache, gql } from '@apollo/client' + +const APIURL = 'https://api.studio.thegraph.com/query///' + +const tokensQuery = ` + query { + tokens { + id + tokenID + contentURI + metadataURI + } + } +` + +const client = new ApolloClient({ + uri: APIURL, + cache: new InMemoryCache(), +}) + +client + .query({ + query: gql(tokensQuery), + }) + .then((data) => console.log('Subgraph data: ', data)) + .catch((err) => { + console.log('Error fetching data: ', err) + }) +``` + +To use variables, you can pass in a `variables` argument to the query: + +```javascript +const tokensQuery = ` + query($first: Int, $orderBy: BigInt, $orderDirection: String) { + tokens( + first: $first, orderBy: $orderBy, orderDirection: $orderDirection + ) { + id + tokenID + contentURI + metadataURI + } + } +` + +client + .query({ + query: gql(tokensQuery), + variables: { + first: 10, + orderBy: 'createdAtTimestamp', + orderDirection: 'desc', + }, + }) + .then((data) => console.log('Subgraph data: ', data)) + .catch((err) => { + console.log('Error fetching data: ', err) + }) +``` + +### URQL + +Another option is [URQL](https://formidable.com/open-source/urql/), a somewhat lighter weight GraphQL client library. + +Let's look at how fetch data from a subgraph with URQL in a web project. + +First, install `urql` and `graphql`: + +```sh +npm install urql graphql +``` + +Then you can query the API with the following code: + +```javascript +import { createClient } from 'urql' + +const APIURL = 'https://api.thegraph.com/subgraphs/name/username/subgraphname' + +const tokensQuery = ` + query { + tokens { + id + tokenID + contentURI + metadataURI + } + } +` + +const client = createClient({ + url: APIURL, +}) + +const data = await client.query(tokensQuery).toPromise() +``` diff --git a/pages/vi/developer/quick-start.mdx b/pages/vi/developer/quick-start.mdx new file mode 100644 index 000000000000..6893d424ddc2 --- /dev/null +++ b/pages/vi/developer/quick-start.mdx @@ -0,0 +1,227 @@ +--- +title: Quick Start +--- + +This guide will quickly take you through how to initialize, create, and deploy your subgraph on: + +- **Subgraph Studio** - used only for subgraphs that index **Ethereum mainnet** +- **Hosted Service** - used for subgraphs that index **other networks** outside of Ethereum mainnnet (e.g. Binance, Matic, etc) + +## Subgraph Studio + +### 1. Install the Graph CLI + +The Graph CLI is written in JavaScript and you will need to have either `npm` or `yarn` installed to use it. + +```sh +# NPM +$ npm install -g @graphprotocol/graph-cli + +# Yarn +$ yarn global add @graphprotocol/graph-cli +``` + +### 2. Initialize your Subgraph + +- Initialize your subgraph from an existing contract. + +```sh +graph init --studio +``` + +- Your subgraph slug is an identifier for your subgraph. The CLI tool will walk you through the steps for creating a subgraph, such as contract address, network, etc as you can see in the screenshot below. + +![Subgraph command](/img/Subgraph-Slug.png) + +### 3. Write your Subgraph + +The previous commands creates a scaffold subgraph that you can use as a starting point for building your subgraph. When making changes to the subgraph, you will mainly work with three files: + +- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraphs will index. +- Schema (schema.graphql) - The GraphQL schema defines what data you wish to retreive from the subgraph. +- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema. + +For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). + +### 4. Deploy to the Subgraph Studio + +- Go to the Subgraph Studio [https://thegraph.com/studio/](https://thegraph.com/studio/) and connect your wallet. +- Click "Create" and enter the subgraph slug you used in step 2. +- Run these commands in the subgraph folder + +```sh +$ graph codegen +$ graph build +``` + +- Authenticate and deploy your subgraph. The deploy key can be found on the Subgraph page in Subgraph Studio. + +```sh +$ graph auth --studio +$ graph deploy --studio +``` + +- You will be asked for a version label. It's strongly recommended to use the following conventions for naming your versions. Example: `0.0.1`, `v1`, `version1` + +### 5. Check your logs + +The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: + +```sh +{ + indexingStatuses(subgraphs: ["Qm..."]) { + node + synced + health + fatalError { + message + block { + number + hash + } + handler + } + nonFatalErrors { + message + block { + number + hash + } + handler + } + chains { + network + chainHeadBlock { + number + } + earliestBlock { + number + } + latestBlock { + number + } + lastHealthyBlock { + number + } + } + entityCount + } +} +``` + +### 6. Query your Subgraph + +You can now query your subgraph by following [these instructions](/developer/query-the-graph). You can query from your dapp if you don't have your API key via the free, rate limited temporary query URL that can be used for development and staging. You can read the additional instructions for how to query a subgraph from a frontend application [here](/developer/querying-from-your-app). + +## Hosted Service + +### 1. Install the Graph CLI + +"The Graph CLI is an npm package and you will need `npm` or `yarn` installed to use it. + +```sh +# NPM +$ npm install -g @graphprotocol/graph-cli + +# Yarn +$ yarn global add @graphprotocol/graph-cli +``` + +### 2. Initialize your Subgraph + +- Initialize your subgraph from an existing contract. + +```sh +$ graph init --product hosted-service --from-contract
+``` + +- You will be asked for a subgraph name. The format is `/`. Ex: `graphprotocol/examplesubgraph` + +- If you'd like to initialize from an example, run the command below: + +```sh +$ graph init --product hosted-service --from-example +``` + +- In the case of the example, the subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. + +### 3. Write your Subgraph + +The previous command will have created a scaffold from where you can build your subgraph. When making changes to the subgraph, you will mainly work with three files: + +- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraph will index +- Schema (schema.graphql) - The GraphQL schema define what data you wish to retrieve from the subgraph +- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema + +For more information on how to write your subgraph, see [Create a Subgraph](/developer/create-subgraph-hosted). + +### 4. Deploy your Subgraph + +- Sign into the [Hosted Service](https://thegraph.com/hosted-service/) using your github account +- Click Add Subgraph and fill out the required information. Use the same subgraph name as in step 2. +- Run codegen in the subgraph folder + +```sh + # NPM +$ npm run codegen + +# Yarn +$ yarn codegen +``` + +- Add your Access token and deploy your subgraph. The access token is found on your dashboard in the Hosted Service. + +```sh +$ graph auth --product hosted-service +$ graph deploy --product hosted-service / +``` + +### 5. Check your logs + +The logs should tell you if there are any errors. If your subgraph is failing, you can query the subgraph health by using the [GraphiQL Playground](https://graphiql-online.com/). Use [this endpoint](https://api.thegraph.com/index-node/graphql). Note that you can leverage the query below and input your deployment ID for your subgraph. In this case, `Qm...` is the deployment ID (which can be located on the Subgraph page under **Details**). The query below will tell you when a subgraph fails so you can debug accordingly: + +```sh +{ + indexingStatuses(subgraphs: ["Qm..."]) { + node + synced + health + fatalError { + message + block { + number + hash + } + handler + } + nonFatalErrors { + message + block { + number + hash + } + handler + } + chains { + network + chainHeadBlock { + number + } + earliestBlock { + number + } + latestBlock { + number + } + lastHealthyBlock { + number + } + } + entityCount + } +} +``` + +### 6. Query your Subgraph + +Follow [these instructions](/hosted-service/query-hosted-service) to query your subgraph on the Hosted Service. diff --git a/pages/vi/explorer.mdx b/pages/vi/explorer.mdx new file mode 100644 index 000000000000..f66163c2def8 --- /dev/null +++ b/pages/vi/explorer.mdx @@ -0,0 +1,212 @@ +--- +title: The Graph Explorer +--- + +Chào mừng bạn đến với Graph Explorer, hay như chúng tôi thường gọi, cổng thông tin phi tập trung của bạn vào thế giới subgraphs và dữ liệu mạng. 👩🏽‍🚀 Graph Explorer bao gồm nhiều phần để bạn có thể tương tác với các nhà phát triển subgraph khác, nhà phát triển dapp, Curators, Indexers, và Delegators. Để biết tổng quan chung về Graph Explorer, hãy xem video bên dưới (hoặc tiếp tục đọc bên dưới): + +
+ +
+ +## Subgraphs + +Điều đầu tiên, nếu bạn vừa hoàn thành việc triển khai và xuất bản subgraph của mình trong Subgraph Studio, thì tab Subgraphs ở trên cùng của thanh điều hướng là nơi để xem các subgraph đã hoàn thành của riêng bạn (và các subgraph của những người khác) trên mạng phi tập trung. Tại đây, bạn sẽ có thể tìm thấy chính xác subgraph mà bạn đang tìm kiếm dựa trên ngày tạo, lượng tín hiệu hoặc tên. + +![Explorer Image 1 +](/img/Subgraphs-Explorer-Landing.png) + +Khi bạn nhấp vào một subgraph, bạn sẽ có thể thử các truy vấn trong playground và có thể tận dụng chi tiết mạng để đưa ra quyết định sáng suốt. Bạn cũng sẽ có thể báo hiệu GRT trên subgraph của riêng bạn hoặc các subgraph của người khác để làm cho các indexer nhận thức được tầm quan trọng và chất lượng của nó. Điều này rất quan trọng vì việc báo hiệu trên một subgraph khuyến khích nó được lập chỉ mục, có nghĩa là nó sẽ xuất hiện trên mạng để cuối cùng phục vụ các truy vấn. + +![Explorer Image 2](/img/Subgraph-Details.png) + +Trên trang chuyên dụng của mỗi subgraph, một số chi tiết được hiển thị. Bao gồm: + +- Báo hiệu / Hủy báo hiệu trên subgraph +- Xem thêm chi tiết như biểu đồ, ID triển khai hiện tại và siêu dữ liệu khác +- Chuyển đổi giữa các phiên bản để khám phá các lần bản trước đây của subgraph +- Truy vấn subgraph qua GraphQL +- Thử subgraph trong playground +- Xem các Indexers đang lập chỉ mục trên một subgraph nhất định +- Thống kê Subgraph (phân bổ, Curators, v.v.) +- Xem pháp nhân đã xuất bản subgraph + +![Explorer Image 3](/img/Explorer-Signal-Unsignal.png) + +## Những người tham gia + +Trong tab này, bạn sẽ có được cái nhìn tổng thể về tất cả những người đang tham gia vào các hoạt động mạng, chẳng hạn như Indexers, Delegators, và Curators. Dưới đây, chúng tôi sẽ đi vào đánh giá sâu về ý nghĩa của mỗi tab đối với bạn. + +### 1. Indexers + +![Explorer Image 4](/img/Indexer-Pane.png) + +Hãy bắt đầu với Indexers (Người lập chỉ mục). Các Indexers là xương sống của giao thức, là những người đóng góp vào các subgraph, lập chỉ mục chúng và phục vụ các truy vấn cho bất kỳ ai sử dụng subgraph. Trong bảng Indexers, bạn sẽ có thể thấy các thông số ủy quyền của Indexer, lượng stake của họ, số lượng họ đã stake cho mỗi subgraph và doanh thu mà họ đã kiếm được từ phí truy vấn và phần thưởng indexing. Đi sâu hơn: + +- Phần Cắt Phí Truy vấn - là % hoàn phí truy vấn mà Indexer giữ lại khi ăn chia với Delegators +- Phần Cắt Thưởng Hiệu quả - phần thưởng indexing được áp dụng cho nhóm ủy quyền (delegation pool). Nếu là âm, điều đó có nghĩa là Indexer đang cho đi một phần phần thưởng của họ. Nếu là dương, điều đó có nghĩa là Indexer đang giữ lại một số phần thưởng của họ +- Cooldown Remaining (Thời gian chờ còn lại) - thời gian còn lại cho đến khi Indexer có thể thay đổi các thông số ủy quyền ở trên. Thời gian chờ Cooldown được Indexers thiết lập khi họ cập nhật thông số ủy quyền của mình +- Được sở hữu - Đây là tiền stake Indexer đã nạp vào, có thể bị phạt cắt giảm (slashed) nếu có hành vi độc hại hoặc không chính xác +- Được ủy quyền - Lượng stake từ các Delegator có thể được Indexer phân bổ, nhưng không thể bị phạt cắt giảm +- Được phân bổ - phần stake mà Indexers đang tích cực phân bổ cho các subgraph mà họ đang lập chỉ mục +- Năng lực Ủy quyền khả dụng - số token stake được ủy quyền mà Indexers vẫn có thể nhận được trước khi họ trở nên ủy quyền quá mức (overdelegated) +- Max Delegation Capacity (Năng lực Ủy quyền Tối đa) - số tiền token stake được ủy quyền tối đa mà Indexer có thể chấp nhận một cách hiệu quả. Số tiền stake được ủy quyền vượt quá con số này sẽ không thể được sử dụng để phân bổ hoặc tính toán phần thưởng. +- Phí Truy vấn - đây là tổng số phí mà người dùng cuối đã trả cho các truy vấn từ Indexer đến hiện tại +- Thưởng Indexer - đây là tổng phần thưởng indexer mà Indexer và các Delegator của họ kiếm được cho đến hiện tại. Phần thưởng Indexer được trả thông qua việc phát hành GRT. + +Indexers có thể kiếm được cả phí truy vấn và phần thưởng indexing. Về mặt chức năng, điều này xảy ra khi những người tham gia mạng ủy quyền GRT cho Indexer. Điều này cho phép Indexers nhận phí truy vấn và phần thưởng tùy thuộc vào thông số Indexer của họ. Các thông số Indexing được cài đặt bằng cách nhấp vào phía bên phải của bảng hoặc bằng cách truy cập hồ sơ của Indexer và nhấp vào nút “Ủy quyền”. + +Để tìm hiểu thêm về cách trở thành một Indexer, bạn có thể xem qua [tài liệu chính thức](/indexing) hoặc [Hướng dẫn về Indexer của Học viện The Graph.](https://thegraph.academy/delegators/choosing-indexers/) + +![Indexing details pane](/img/Indexing-Details-Pane.png) + +### 2. Curators + +Curators (Người Giám tuyển) phân tích các subgraph để xác định subgraph nào có chất lượng cao nhất. Một khi Curator tìm thấy một subgraph có khả năng hấp dẫn, họ có thể curate nó bằng cách báo hiệu trên đường cong liên kết (bonding curve) của nó. Khi làm như vậy, Curator sẽ cho Indexer biết những subgraph nào có chất lượng cao và nên được lập chỉ mục. + +Curators có thể là các thành viên cộng đồng, người tiêu dùng dữ liệu hoặc thậm chí là nhà phát triển subgraph, những người báo hiệu trên subgraph của chính họ bằng cách nạp token GRT vào một đường cong liên kết. Bằng cách nạp GRT, Curator đúc ra cổ phần curation của một subgraph. Kết quả là, Curators có đủ điều kiện để kiếm một phần phí truy vấn mà subgraph mà họ đã báo hiệu tạo ra. Đường cong liên kết khuyến khích Curators quản lý các nguồn dữ liệu chất lượng cao nhất. Bảng Curator trong phần này sẽ cho phép bạn xem: + +- Ngày Curator bắt đầu curate +- Số GRT đã được nạp +- Số cổ phần một Curator sở hữu + +![Explorer Image 6](/img/Curation-Overview.png) + +Nếu muốn tìm hiểu thêm về vai trò Curator, bạn có thể thực hiện việc này bằng cách truy cập các liên kết sau của [Học viện The Graph](https://thegraph.academy/curators/) hoặc [tài liệu chính thức.](/curating) + +### 3. Delegators + +Delegators (Người Ủy quyền) đóng một vai trò quan trọng trong việc duy trì tính bảo mật và phân quyền của Mạng The Graph. Họ tham gia vào mạng bằng cách ủy quyền (tức là "staking") token GRT cho một hoặc nhiều indexer. Không có những Delegator, các Indexer ít có khả năng kiếm được phần thưởng và phí đáng kể. Do đó, Indexer tìm cách thu hút Delegator bằng cách cung cấp cho họ một phần của phần thưởng lập chỉ mục và phí truy vấn mà họ kiếm được. + +Delegator, đổi lại, chọn Indexer dựa trên một số biến số khác nhau, chẳng hạn như hiệu suất trong quá khứ, tỷ lệ phần thưởng lập chỉ mục và phần cắt phí truy vấn. Danh tiếng trong cộng đồng cũng có thể đóng vai trò quan trọng trong việc này! Bạn nên kết nối với những các indexer đã chọn qua[Discord của The Graph](https://thegraph.com/discord) hoặc [Forum The Graph](https://forum.thegraph.com/)! + +![Explorer Image 7](/img/Delegation-Overview.png) + +Bảng Delegators sẽ cho phép bạn xem các Delegator đang hoạt động trong cộng đồng, cũng như các chỉ số như: + +- Số lượng Indexers mà một Delegator đang ủy quyền cho +- Ủy quyền ban đầu của Delegator +- Phần thưởng họ đã tích lũy nhưng chưa rút khỏi giao thức +- Phần thưởng đã ghi nhận ra mà họ rút khỏi giao thức +- Tổng lượng GRT mà họ hiện có trong giao thức +- Ngày họ ủy quyền lần cuối cùng + +Nếu bạn muốn tìm hiểu thêm về cách trở thành một Delegator, đừng tìm đâu xa! Tất cả những gì bạn phải làm là đi đến [tài liệu chính thức](/delegating) hoặc [Học viện The Graph](https://docs.thegraph.academy/network/delegators). + +## Mạng lưới + +Trong phần Mạng lưới, bạn sẽ thấy các KPI toàn cầu cũng như khả năng chuyển sang cơ sở từng epoch và phân tích các chỉ số mạng chi tiết hơn. Những chi tiết này sẽ cho bạn biết mạng hoạt động như thế nào theo thời gian. + +### Hoạt động + +Phần hoạt động có tất cả các chỉ số mạng hiện tại cũng như một số chỉ số tích lũy theo thời gian. Ở đây bạn có thể thấy những thứ như: + +- Tổng stake mạng hiện tại +- Phần chia stake giữa Indexer và các Delegator của họ +- Tổng cung GRT, lượng được đúc và đốt kể từ khi mạng lưới thành lập +- Tổng phần thưởng Indexing kể từ khi bắt đầu giao thức +- Các thông số giao thức như phần thưởng curation, tỷ lệ lạm phát,... +- Phần thưởng và phí của epoch hiện tại + +Một vài chi tiết quan trọng đáng được đề cập: + +- **Phí truy vấn đại diện cho phí do người tiêu dùng tạo ra**, và chúng có thể được Indexer yêu cầu (hoặc không) sau một khoảng thời gian ít nhất 7 epochs (xem bên dưới) sau khi việc phân bổ của họ cho các subgraph đã được đóng lại và dữ liệu mà chúng cung cấp đã được người tiêu dùng xác thực. +- **Phần thưởng Indexing đại diện cho số phần thưởng mà Indexer đã yêu cầu được từ việc phát hành mạng trong epoch đó.** Mặc dù việc phát hành giao thức đã được cố định, nhưng phần thưởng chỉ nhận được sau khi Indexer đóng phân bổ của họ cho các subgraph mà họ đã lập chỉ mục. Do đó, số lượng phần thưởng theo từng epoch khác nhau (nghĩa là trong một số epoch, Indexer có thể đã đóng chung các phân bổ đã mở trong nhiều ngày). + +![Explorer Image 8](/img/Network-Stats.png) + +### Epochs + +Trong phần Epochs, bạn có thể phân tích trên cơ sở từng epoch, các chỉ số như: + +- Khối bắt đầu hoặc kết thúc của Epoch +- Phí truy vấn được tạo và phần thưởng indexing được thu thập trong một epoch cụ thể +- Trạng thái Epoch, đề cập đến việc thu và phân phối phí truy vấn và có thể có các trạng thái khác nhau: + - Epoch đang hoạt động là epoch mà Indexer hiện đang phân bổ cổ phần và thu phí truy vấn + - Epoch đang giải quyết là những epoch mà các kênh trạng thái đang được giải quyết. Điều này có nghĩa là Indexers có thể bị phạt cắt giảm nếu người tiêu dùng công khai tranh chấp chống lại họ. + - Epoch đang phân phối là epoch trong đó các kênh trạng thái cho các epoch đang được giải quyết và Indexer có thể yêu cầu hoàn phí truy vấn của họ. + - Epoch được hoàn tất là những epoch không còn khoản hoàn phí truy vấn nào để Indexer yêu cầu, do đó sẽ được hoàn thiện. + +![Explorer Image 9](/img/Epoch-Stats.png) + +## Hồ sơ Người dùng của bạn + +Nãy giờ chúng ta đã nói về các thống kê mạng, hãy chuyển sang hồ sơ cá nhân của bạn. Hồ sơ người dùng cá nhân của bạn là nơi để bạn xem hoạt động mạng của mình, bất kể bạn đang tham gia mạng như thế nào. Ví Ethereum của bạn sẽ hoạt động như hồ sơ người dùng của bạn và với Trang Tổng quan Người dùng, bạn sẽ có thể thấy: + +### Tổng quan Hồ sơ + +Đây là nơi bạn có thể xem bất kỳ hành động hiện tại nào bạn đã thực hiện. Đây cũng là nơi bạn có thể tìm thấy thông tin hồ sơ, mô tả và trang web của mình (nếu bạn đã thêm). + +![Explorer Image 10](/img/Profile-Overview.png) + +### Tab Subgraphs + +Nếu bạn nhấp vào tab Subgraphs, bạn sẽ thấy các subgraph đã xuất bản của mình. Điều này sẽ không bao gồm bất kỳ subgraph nào được triển khai với CLI cho mục đích thử nghiệm - các subgraph sẽ chỉ hiển thị khi chúng được xuất bản lên mạng phi tập trung. + +![Explorer Image 11](/img/Subgraphs-Overview.png) + +### Tab Indexing + +Nếu bạn nhấp vào tab Indexing, bạn sẽ tìm thấy một bảng với tất cả các phân bổ hiện hoạt và lịch sử cho các subgraph, cũng như các biểu đồ mà bạn có thể phân tích và xem hiệu suất trước đây của mình với tư cách là Indexer. + +Phần này cũng sẽ bao gồm thông tin chi tiết về phần thưởng Indexer ròng của bạn và phí truy vấn ròng. Bạn sẽ thấy các số liệu sau: + +- Stake được ủy quyền - phần stake từ Delegator có thể được bạn phân bổ nhưng không thể bị phạt cắt giảm (slashed) +- Tổng Phí Truy vấn - tổng phí mà người dùng đã trả cho các truy vấn do bạn phục vụ theo thời gian +- Phần thưởng Indexer - tổng số phần thưởng Indexer bạn đã nhận được, tính bằng GRT +- Phần Cắt Phí - lượng % hoàn phí phí truy vấn mà bạn sẽ giữ lại khi ăn chia với Delegator +- Phần Cắt Thưởng - lượng % phần thưởng Indexer mà bạn sẽ giữ lại khi ăn chia với Delegator +- Được sở hữu - số stake đã nạp của bạn, có thể bị phạt cắt giảm (slashed) vì hành vi độc hại hoặc không chính xác + +![Explorer Image 12](/img/Indexer-Stats.png) + +### Tab Delegating + +Delegator rất quan trọng đối với Mạng The Graph. Một Delegator phải sử dụng kiến thức của họ để chọn một Indexer sẽ mang lại lợi nhuận lành mạnh từ các phần thưởng. Tại đây, bạn có thể tìm thấy thông tin chi tiết về các ủy quyền đang hoạt động và trong lịch sử của mình, cùng với các chỉ số của Indexer mà bạn đã ủy quyền. + +Trong nửa đầu của trang, bạn có thể thấy biểu đồ ủy quyền của mình, cũng như biểu đồ chỉ có phần thưởng. Ở bên trái, bạn có thể thấy các KPI phản ánh các chỉ số ủy quyền hiện tại của bạn. + +Các chỉ số Delegator mà bạn sẽ thấy ở đây trong tab này bao gồm: + +- Tổng pphần thưởng ủy quyền +- Tổng số phần thưởng chưa ghi nhận +- Tổng số phần thưởng đã ghi được + +Trong nửa sau của trang, bạn có bảng ủy quyền. Tại đây, bạn có thể thấy các Indexer mà bạn đã ủy quyền, cũng như thông tin chi tiết của chúng (chẳng hạn như phần cắt thưởng, thời gian chờ, v.v.). + +Với các nút ở bên phải của bảng, bạn có thể quản lý ủy quyền của mình - ủy quyền nhiều hơn, hủy bỏ hoặc rút lại ủy quyền của bạn sau khoảng thời gian rã đông (thawing period). + +Lưu ý rằng biểu đồ này có thể cuộn theo chiều ngang, vì vậy nếu bạn cuộn hết cỡ sang bên phải, bạn cũng có thể thấy trạng thái ủy quyền của mình (ủy quyền, hủy ủy quyền, có thể rút lại). + +![Explorer Image 13](/img/Delegation-Stats.png) + +### Tab Curating + +Trong tab Curation, bạn sẽ tìm thấy tất cả các subgraph mà bạn đang báo hiệu (do đó cho phép bạn nhận phí truy vấn). Báo hiệu cho phép Curator đánh dấu cho Indexer biết những subgraph nào có giá trị và đáng tin cậy, do đó báo hiệu rằng chúng cần được lập chỉ mục. + +Trong tab này, bạn sẽ tìm thấy tổng quan về: + +- Tất cả các subgraph bạn đang quản lý với các chi tiết về tín hiệu +- Tổng cổ phần trên mỗi subgraph +- Phần thưởng truy vấn cho mỗi subgraph +- Chi tiết ngày được cập nhật + +![Explorer Image 14](/img/Curation-Stats.png) + +## Cài đặt Hồ sơ của bạn + +Trong hồ sơ người dùng của mình, bạn sẽ có thể quản lý chi tiết hồ sơ cá nhân của mình (như thiết lập tên ENS). Nếu bạn là Indexer, bạn thậm chí có nhiều quyền truy cập hơn vào các cài đặt trong tầm tay của mình. Trong hồ sơ người dùng của mình, bạn sẽ có thể thiết lập các tham số ủy quyền và operator của mình. + +- Operators (Người vận hành) thực hiện các hành động được hạn chế trong giao thức thay mặt cho Indexer, chẳng hạn như mở và đóng phân bổ. Operators thường là các địa chỉ Ethereum khác, tách biệt với ví đặt staking của họ, với quyền truy cập được kiểm soát vào mạng mà Indexer có thể cài đặt cá nhân +- Tham số ủy quyền cho phép bạn kiểm soát việc phân phối GRT giữa bạn và các Delegator của bạn. + +![Explorer Image 15](/img/Profile-Settings.png) + +Là cổng thông tin chính thức của bạn vào thế giới dữ liệu phi tập trung, Graph Explorer cho phép bạn thực hiện nhiều hành động khác nhau, bất kể vai trò của bạn trong mạng. Bạn có thể truy cập cài đặt hồ sơ của mình bằng cách mở menu thả xuống bên cạnh địa chỉ của bạn, sau đó nhấp vào nút Cài đặt. + +
![Wallet details](/img/Wallet-Details.png)
diff --git a/pages/vi/hosted-service/deploy-subgraph-hosted.mdx b/pages/vi/hosted-service/deploy-subgraph-hosted.mdx new file mode 100644 index 000000000000..bdc532e205e4 --- /dev/null +++ b/pages/vi/hosted-service/deploy-subgraph-hosted.mdx @@ -0,0 +1,160 @@ +--- +title: Deploy a Subgraph to the Hosted Service +--- + +If you have not checked out already, check out how to write the files that make up a [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) and how to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) to generate code for your subgraph. Now, it's time to deploy your subgraph to the Hosted Service, also known as the Hosted Service. + +## Create a Hosted Service account + +Before using the Hosted Service, create an account in our Hosted Service. You will need a [Github](https://github.com/) account for that; if you don't have one, you need to create that first. Then, navigate to the [Hosted Service](https://thegraph.com/hosted-service/), click on the _'Sign up with Github'_ button and complete Github's authorization flow. + +## Store the Access Token + +After creating an account, navigate to your [dashboard](https://thegraph.com/hosted-service/dashboard). Copy the access token displayed on the dashboard and run `graph auth --product hosted-service `. This will store the access token on your computer. You only need to do this once, or if you ever regenerate the access token. + +## Create a Subgraph on the Hosted Service + +Before deploying the subgraph, you need to create it in The Graph Explorer. Go to the [dashboard](https://thegraph.com/hosted-service/dashboard) and click on the _'Add Subgraph'_ button and fill in the information below as appropriate: + +**Image** - Select an image to be used as a preview image and thumbnail for the subgraph. + +**Subgraph Name** - Together with the account name that the subgraph is created under, this will also define the `account-name/subgraph-name`-style name used for deployments and GraphQL endpoints. _This field cannot be changed later._ + +**Account** - The account that the subgraph is created under. This can be the account of an individual or organization. _Subgraphs cannot be moved between accounts later._ + +**Subtitle** - Text that will appear in subgraph cards. + +**Description** - Description of the subgraph, visible on the subgraph details page. + +**GitHub URL** - Link to the subgraph repository on GitHub. + +**Hide** - Switching this on hides the subgraph in the Graph Explorer. + +After saving the new subgraph, you are shown a screen with help on how to install the Graph CLI, how to generate the scaffolding for a new subgraph, and how to deploy your subgraph. The first two steps were covered in the [Define a Subgraph section](/developer/define-subgraph-hosted). + +## Deploy a Subgraph on the Hosted Service + +Deploying your subgraph will upload the subgraph files that you've built with `yarn build` to IPFS and tell the Graph Explorer to start indexing your subgraph using these files. + +You deploy the subgraph by running `yarn deploy` + +After deploying the subgraph, the Graph Explorer will switch to showing the synchronization status of your subgraph. Depending on the amount of data and the number of events that need to be extracted from historical Ethereum blocks, starting with the genesis block, syncing can take from a few minutes to several hours. The subgraph status switches to `Synced` once the Graph Node has extracted all data from historical blocks. The Graph Node will continue inspecting Ethereum blocks for your subgraph as these blocks are mined. + +## Redeploying a Subgraph + +When making changes to your subgraph definition, for example to fix a problem in the entity mappings, run the `yarn deploy` command above again to deploy the updated version of your subgraph. Any update of a subgraph requires that Graph Node reindexes your entire subgraph, again starting with the genesis block. + +If your previously deployed subgraph is still in status `Syncing`, it will be immediately replaced with the newly deployed version. If the previously deployed subgraph is already fully synced, Graph Node will mark the newly deployed version as the `Pending Version`, sync it in the background, and only replace the currently deployed version with the new one once syncing the new version has finished. This ensures that you have a subgraph to work with while the new version is syncing. + +### Deploying the subgraph to multiple Ethereum networks + +In some cases, you will want to deploy the same subgraph to multiple Ethereum networks without duplicating all of its code. The main challenge that comes with this is that the contract addresses on these networks are different. One solution that allows to parameterize aspects like contract addresses is to generate parts of it using a templating system like [Mustache](https://mustache.github.io/) or [Handlebars](https://handlebarsjs.com/). + +To illustrate this approach, let's assume a subgraph should be deployed to mainnet and Ropsten using different contract addresses. You could then define two config files providing the addresses for each network: + +```json +{ + "network": "mainnet", + "address": "0x123..." +} +``` + +and + +```json +{ + "network": "ropsten", + "address": "0xabc..." +} +``` + +Along with that, you would substitute the network name and addresses in the manifest with variable placeholders `{{network}}` and `{{address}}` and rename the manifest to e.g. `subgraph.template.yaml`: + +```yaml +# ... +dataSources: + - kind: ethereum/contract + name: Gravity + network: mainnet + network: {{network}} + source: + address: '0x2E645469f354BB4F5c8a05B3b30A929361cf77eC' + address: '{{address}}' + abi: Gravity + mapping: + kind: ethereum/events +``` + +In order generate a manifest to either network, you could add two additional commands to `package.json` along with a dependency on `mustache`: + +```json +{ + ... + "scripts": { + ... + "prepare:mainnet": "mustache config/mainnet.json subgraph.template.yaml > subgraph.yaml", + "prepare:ropsten": "mustache config/ropsten.json subgraph.template.yaml > subgraph.yaml" + }, + "devDependencies": { + ... + "mustache": "^3.1.0" + } +} +``` + +To deploy this subgraph for mainnet or Ropsten you would now simply run one of the two following commands: + +```sh +# Mainnet: +yarn prepare:mainnet && yarn deploy + +# Ropsten: +yarn prepare:ropsten && yarn deploy +``` + +A working example of this can be found [here](https://github.com/graphprotocol/example-subgraph/tree/371232cf68e6d814facf5e5413ad0fef65144759). + +**Note:** This approach can also be applied more complex situations, where it is necessary to substitute more than contract addresses and network names or where generating mappings or ABIs from templates as well. + +## Checking subgraph health + +If a subgraph syncs successfully, that is a good sign that it will continue to run well forever. However, new triggers on the chain might cause your subgraph to hit an untested error condition or it may start to fall behind due to performance issues or issues with the node operators. + +Graph Node exposes a graphql endpoint which you can query to check the status of your subgraph. On the Hosted Service, it is available at `https://api.thegraph.com/index-node/graphql`. On a local node it is available on port `8030/graphql` by default. The full schema for this endpoint can be found [here](https://github.com/graphprotocol/graph-node/blob/master/server/index-node/src/schema.graphql). Here is an example query that checks the status of the current version of a subgraph: + +```graphql +{ + indexingStatusForCurrentVersion(subgraphName: "org/subgraph") { + synced + health + fatalError { + message + block { + number + hash + } + handler + } + chains { + chainHeadBlock { + number + } + latestBlock { + number + } + } + } +} +``` + +This will give you the `chainHeadBlock` which you can compare with the `latestBlock` on your subgraph to check if it is running behind. `synced` informs if the subgraph has ever caught up to the chain. `health` can currently take the values of `healthy` if no errors ocurred, or `failed` if there was an error which halted the progress of the subgraph. In this case you can check the `fatalError` field for details on this error. + +## Subgraph archive policy + +The Hosted Service is a free Graph Node indexer. Developers can deploy subgraphs indexing a range of networks, which will be indexed, and made available to query via graphQL. + +To improve the performance of the service for active subgraphs, the Hosted Service will archive subgraphs which are inactive. + +**A subgraph is defined as "inactive" if it was deployed to the Hosted Service more than 45 days ago, and if it has received 0 queries in the last 30 days.** + +Developers will be notified by email if one of their subgraphs has been marked as inactive 7 days before it is removed. If they wish to "activate" their subgraph, they can do so by making a query in their subgraph's Hosted Service graphQL playground. Developers can always redeploy an archived subgraph if it is required again. diff --git a/pages/vi/hosted-service/migrating-subgraph.mdx b/pages/vi/hosted-service/migrating-subgraph.mdx new file mode 100644 index 000000000000..85f72f053b30 --- /dev/null +++ b/pages/vi/hosted-service/migrating-subgraph.mdx @@ -0,0 +1,151 @@ +--- +title: Migrating an Existing Subgraph to The Graph Network +--- + +## Introduction + +This is a guide for the migration of subgraphs from the Hosted Service (also known as 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. + +This will tell you everything you need to know about how to migrate to the decentralized network and manage your subgraphs moving forward. The process is quick and your subgraphs will forever benefit from the reliability and performance that you can only get on The Graph Network. + +### Migrating An Existing Subgraph to The Graph Network + +1. Get the latest version of the graph-cli installed: + +```sh +npm install -g @graphprotocol/graph-cli +``` + +```sh +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](/studio/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: + +```sh +graph auth --studio +``` + +4. Generate files and build the subgraph: + +```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. + +```sh + 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): + +```sh +{ + users(first: 5) { + id + liquidityPositions { + id + } + } + bundles(first: 5) { + id + ethPrice + } +} +``` + +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. + +- 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. + +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). + +### Upgrading a Subgraph on the Network + +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. + +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): + +```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). + +### Owner Upgrade Fee: 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](/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. The example below is only the case if your subgraph is being actively curated on. If there is no curation activity, you will have to pay a minimum of 100 GRT in order to signal yourself on your own subgraph. + +- 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. + +_While this mechanism is currently live on the network, the community is currently discussing ways to reduce the cost of upgrades for subgraph developers._ + +### Maintaining a Stable Version of a Subgraph + +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/8tgJ7rKW) on Discord to let Indexers know when you're versioning your subgraphs. + +Subgraphs are open API 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. + +### Updating the Metadata of a Subgraph + +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. + +Make sure **Update Subgraph Details in Explorer** is checked and click on **Save**. If this is checked, an 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. + +## Best Practices for Deploying a Subgraph to The Graph Network + +1. Leveraging an ENS name for Subgraph Development + +- 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). + +The more filled out your profiles are, the better the chances for your subgraphs to be indexed and curated. + +## Deprecating a Subgraph on The Graph Network + +Follow the steps [here](/developer/deprecating-a-subgraph) to deprecate your subgraph and remove it from The Graph Network. + +## Querying a Subgraph + Billing on The Graph Network + +The Hosted Service was set up to allow developers to deploy their subgraphs without any restrictions. + +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](/studio/billing). + +### Estimate Query Fees on the Network + +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 divide it by your expected query volume. + +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 of that, 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. + +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 in 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. + +![QueryFee](/img/QueryFee.png) + +## Additional Resources + +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: + +
+ +
+ +- [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 + - Address - `0x8fe00a685bcb3b2cc296ff6ffeab10aca4ce1538` +- [Subgraph Studio documentation](/studio/subgraph-studio) diff --git a/pages/vi/hosted-service/query-hosted-service.mdx b/pages/vi/hosted-service/query-hosted-service.mdx new file mode 100644 index 000000000000..731e3a3120b2 --- /dev/null +++ b/pages/vi/hosted-service/query-hosted-service.mdx @@ -0,0 +1,28 @@ +--- +title: Query the Hosted Service +--- + +With the subgraph deployed, visit the [Hosted Service](https://thegraph.com/hosted-service/) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. + +An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. + +#### Example + +This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: + +```graphql +{ + counters { + id + value + } +} +``` + +## Using The Hosted Service + +The Graph Explorer and its GraphQL playground is a useful way to explore and query deployed subgraphs on the Hosted Service. + +Some of the main features are detailed below: + +![Explorer Playground](/img/explorer-playground.png) diff --git a/pages/vi/hosted-service/what-is-hosted-service.mdx b/pages/vi/hosted-service/what-is-hosted-service.mdx new file mode 100644 index 000000000000..7f604c8dc31a --- /dev/null +++ b/pages/vi/hosted-service/what-is-hosted-service.mdx @@ -0,0 +1,77 @@ +--- +title: What is the Hosted Service? +--- + +This section will walk you through deploying a subgraph to the Hosted Service, otherwise known as the [Hosted Service.](https://thegraph.com/hosted-service/) As a reminder, the Hosted Service will not be shut down soon. We will gradually sunset the Hosted Service once we reach feature parity with the decentralized network. Your subgraphs deployed on the Hosted Service are still available [here.](https://thegraph.com/hosted-service/) + +If you don't have an account on the Hosted Service, you can signup with your Github account. Once you authenticate, you can start creating subgraphs through the UI and deploying them from your terminal. Graph Node supports a number of Ethereum testnets (Rinkeby, Ropsten, Kovan) in addition to mainnet. + +## Create a Subgraph + +First follow the instructions [here](/developer/define-subgraph-hosted) to install the Graph CLI. Create a subgraph by passing in `graph init --product hosted service` + +### From an Existing Contract + +If you already have a smart contract deployed to Ethereum mainnet or one of the testnets, bootstrapping a new subgraph from this contract can be a good way to get started on the Hosted Service. + +You can use this command to create a subgraph that indexes all events from an existing contract. This will attempt to fetch the contract ABI from [Etherscan](https://etherscan.io/). + +```sh +graph init \ + --product hosted-service + --from-contract \ + / [] +``` + +Additionally, you can use the following optional arguments. If the ABI cannot be fetched from Etherscan, it falls back to requesting a local file path. If any optional arguments are missing from the command, it takes you through an interactive form. + +```sh +--network \ +--abi \ +``` + +The `` in this case is your github user or organization name, `` is the name for your subgraph, and `` is the optional name of the directory where graph init will put the example subgraph manifest. The `` is the address of your existing contract. `` is the name of the Ethereum network that the contract lives on. `` is a local path to a contract ABI file. **Both --network and --abi are optional.** + +### From an Example Subgraph + +The second mode `graph init` supports is creating a new project from an example subgraph. The following command does this: + +``` +graph init --from-example --product hosted-service / [] +``` + +The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. Continue on to the [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) to better understand which events from your smart contracts to pay attention to, mappings, and more. + +## Supported Networks on the Hosted Service + +Please note that the following networks are supported on the Hosted Service. Networks outside of Ethereum mainnet ('mainnet') are not currently supported on [The Graph Explorer.](https://thegraph.com/explorer) + +- `mainnet` +- `kovan` +- `rinkeby` +- `ropsten` +- `goerli` +- `poa-core` +- `poa-sokol` +- `xdai` +- `near-mainnet` +- `near-testnet` +- `matic` +- `mumbai` +- `fantom` +- `bsc` +- `chapel` +- `clover` +- `avalanche` +- `fuji` +- `celo` +- `celo-alfajores` +- `fuse` +- `moonriver` +- `mbase` +- `arbitrum-one` +- `arbitrum-rinkeby` +- `optimism` +- `optimism-kovan` +- `aurora` +- `aurora-testnet` diff --git a/pages/vi/indexing.mdx b/pages/vi/indexing.mdx new file mode 100644 index 000000000000..b543436f0049 --- /dev/null +++ b/pages/vi/indexing.mdx @@ -0,0 +1,873 @@ +--- +title: Indexer +--- + +import { Difficulty } from '@/components' + +Indexer là những người vận hành node (node operator) trong Mạng The Graph có stake Graph Token (GRT) để cung cấp các dịch vụ indexing và xử lý truy vấn. Indexers kiếm được phí truy vấn và phần thưởng indexing cho các dịch vụ của họ. Họ cũng kiếm được tiền từ Rebate Pool (Pool Hoàn phí) được chia sẻ với tất cả những người đóng góp trong mạng tỷ lệ thuận với công việc của họ, tuân theo Chức năng Rebate Cobbs-Douglas. + +GRT được stake trong giao thức sẽ phải trải qua một khoảng thời gian chờ "tan băng" (thawing period) và có thể bị cắt nếu Indexer có ác ý và cung cấp dữ liệu không chính xác cho các ứng dụng hoặc nếu họ index không chính xác. Indexer cũng có thể được ủy quyền stake từ Delegator, để đóng góp vào mạng. + +Indexer chọn các subgraph để index dựa trên tín hiệu curation của subgraph, trong đó Curator stake GRT để chỉ ra subgraph nào có chất lượng cao và cần được ưu tiên. Bên tiêu dùng (ví dụ: ứng dụng) cũng có thể đặt các tham số (parameter) mà Indexer xử lý các truy vấn cho các subgraph của họ và đặt các tùy chọn cho việc định giá phí truy vấn. + + + +## CÂU HỎI THƯỜNG GẶP + +### Lượng stake tối thiểu cần thiết để trở thành một indexer trên mạng là bao nhiêu? + +Lượng stake tối thiểu cho một indexer hiện được đặt là 100K GRT. + +### Các nguồn doanh thu cho indexer là gì? + +**Hoàn phí truy vấn** - Thanh toán cho việc phục vụ các truy vấn trên mạng. Các khoản thanh toán này được dàn xếp thông qua các state channel giữa indexer và cổng. Mỗi yêu cầu truy vấn từ một cổng chứa một khoản thanh toán và phản hồi tương ứng là bằng chứng về tính hợp lệ của kết quả truy vấn. + +**Phần thưởng Indexing** - Được tạo ra thông qua lạm phát trên toàn giao thức hàng năm 3%, phần thưởng indexing được phân phối cho các indexer đang lập chỉ mục các triển khai subgraph cho mạng lưới. + +### Phần thưởng được phân phối như thế nào? + +Phần thưởng Indexing đến từ lạm phát giao thức được đặt thành 3% phát hành hàng năm. Chúng được phân phối trên các subgraph dựa trên tỷ lệ của tất cả các tín hiệu curation trên mỗi subgraph, sau đó được phân phối theo tỷ lệ cho các indexers dựa trên số stake được phân bổ của họ trên subgraph đó. **Việc phân bổ phải được kết thúc với bằng chứng lập chỉ mục (proof of indexing - POI) hợp lệ đáp ứng các tiêu chuẩn do điều lệ trọng tài đặt ra để đủ điều kiện nhận phần thưởng** + +Nhiều công cụ đã được cộng đồng tạo ra để tính toán phần thưởng; bạn sẽ tìm thấy một bộ sưu tập của chúng được sắp xếp trong [Bộ sưu tập Hướng dẫn cộng đồng](https://www.notion.so/Community-Guides-abbb10f4dba040d5ba81648ca093e70c). Bạn cũng có thể tìm thấy danh sách cập nhật mới nhất các công cụ trong các kênh #delegators và #indexers trên [server Discord](https://discord.gg/vtvv7FP). + +### Bằng chứng lập chỉ mục (proof of indexing - POI) là gì? + +POI được sử dụng trong mạng để xác minh rằng một indexer đang lập chỉ mục các subgraph mà họ đã phân bổ. POI cho khối đầu tiên của epoch hiện tại phải được gửi khi kết thúc phân bổ cho phân bổ đó để đủ điều kiện nhận phần thưởng indexing. POI cho một khối là một thông báo cho tất cả các giao dịch lưu trữ thực thể để triển khai một subgraph cụ thể lên đến và bao gồm khối đó. + +### Khi nào Phần thưởng indexing được phân phối? + +Việc phân bổ liên tục tích lũy phần thưởng khi chúng đang hoạt động. Phần thưởng được thu thập bởi các indexer và phân phối bất cứ khi nào việc phân bổ của họ bị đóng lại. Điều đó xảy ra theo cách thủ công, bất cứ khi nào indexer muốn buộc đóng chúng hoặc sau 28 epoch, delegator có thể đóng phân bổ cho indexer, nhưng điều này dẫn đến không có phần thưởng nào được tạo ra. 28 epoch là thời gian tồn tại của phân bổ tối đa (hiện tại, một epoch kéo dài trong ~ 24 giờ). + +### Có thể giám sát phần thưởng indexer đang chờ xử lý không? + +Hợp đồng RewardsManager có có một chức năng [getRewards](https://github.com/graphprotocol/contracts/blob/master/contracts/rewards/RewardsManager.sol#L317) chỉ đọc có thể được sử dụng để kiểm tra phần thưởng đang chờ để phân bổ cụ thể. + +Nhiều trang tổng quan (dashboard) do cộng đồng tạo bao gồm các giá trị phần thưởng đang chờ xử lý và bạn có thể dễ dàng kiểm tra chúng theo cách thủ công bằng cách làm theo các bước sau: + +1. Truy vấn [mainnet subgraph](https://thegraph.com/hosted-service/subgraph/graphprotocol/graph-network-mainnet) để nhận ID cho tất cả phần phân bổ đang hoạt động: + +```graphql +query indexerAllocations { + indexer(id: "") { + allocations { + activeForIndexer { + allocations { + id + } + } + } + } +} +``` + +Sử dụng Etherscan để gọi `getRewards()`: + +- Điều hướng đến [giao diện Etherscan đến hợp đồng Rewards](https://etherscan.io/address/0x9Ac758AB77733b4150A901ebd659cbF8cB93ED66#readProxyContract) + +* Để gọi `getRewards()`: + - Mở rộng **10. getRewards** thả xuống. + - Nhập **allocationID** trong đầu vào. + - Nhấn **Nút** Truy vấn. + +### Tranh chấp là gì và tôi có thể xem chúng ở đâu? + +Các truy vấn và phần phân bổ của Indexer đều có thể bị tranh chấp trên The Graph trong thời gian tranh chấp. Thời hạn tranh chấp khác nhau, tùy thuộc vào loại tranh chấp. Truy vấn / chứng thực có cửa sổ tranh chấp 7 epoch (kỷ nguyên), trong khi phần phân bổ có 56 epoch. Sau khi các giai đoạn này trôi qua, không thể mở các tranh chấp đối với phần phân bổ hoặc truy vấn. Khi một tranh chấp được mở ra, các Fisherman yêu cầu một khoản stake tối thiểu là 10.000 GRT, sẽ bị khóa cho đến khi tranh chấp được hoàn tất và giải pháp đã được đưa ra. Fisherman là bất kỳ người tham gia mạng nào mà đã mở ra tranh chấp. + +Tranh chấp có **ba** kết quả có thể xảy ra, phần tiền gửi của Fisherman cũng vậy. + +- Nếu tranh chấp bị từ chối, GRT do Fisherman gửi sẽ bị đốt, và Indexer tranh chấp sẽ không bị phạt cắt giảm (slashed). +- Nếu tranh chấp được giải quyết dưới dạng hòa, tiền gửi của Fisherman sẽ được trả lại, và Indexer bị tranh chấp sẽ không bị phạt cắt giảm (slashed). +- Nếu tranh chấp được chấp nhận, lượng GRT do Fisherman đã gửi sẽ được trả lại, Indexer bị tranh chấp sẽ bị cắt và Fisherman sẽ kiếm được 50% GRT đã bị phạt cắt giảm (slashed). + +Tranh chấp có thể được xem trong giao diện người dùng trong trang hồ sơ của Indexer trong mục `Tranh chấp`. + +### Các khoản hoàn phí truy vấn là gì và chúng được phân phối khi nào? + +Phí truy vấn được cổng thu thập bất cứ khi nào một phần phân bổ được đóng và được tích lũy trong pool hoàn phí truy vấn của subgraph. Pool hoàn phí được thiết kế để khuyến khích Indexer phân bổ stake theo tỷ lệ thô với số phí truy vấn mà họ kiếm được cho mạng. Phần phí truy vấn trong pool được phân bổ cho một indexer cụ thể được tính bằng cách sử dụng Hàm Sản xuất Cobbs-Douglas; số tiền được phân phối cho mỗi indexer là một chức năng của phần đóng góp của họ cho pool và việc phân bổ stake của họ trên subgraph. + +Khi một phần phân bổ đã được đóng và thời gian tranh chấp đã qua, indexer sẽ có thể nhận các khoản hoàn phí. Khi yêu cầu, các khoản hoàn phí truy vấn được phân phối cho indexer và delegator của họ dựa trên mức cắt giảm phí truy vấn và tỷ lệ pool ủy quyền (delegation). + +### Cắt giảm phí truy vấn và cắt giảm phần thưởng indexing là gì? + +Giá trị `queryFeeCut` và `indexingRewardCut` là các tham số delegation mà Indexer có thể đặt cùng với cooldownBlocks để kiểm soát việc phân phối GRT giữa indexer và delegator của họ. Xem các bước cuối cùng trong [Staking trong Giao thức](/indexing#stake-in-the-protocol) để được hướng dẫn về cách thiết lập các tham số delegation. + +- **queryFeeCut** - % hoàn phí truy vấn được tích lũy trên một subgraph sẽ được phân phối cho indexer. Nếu thông số này được đặt là 95%, indexer sẽ nhận được 95% của pool hoàn phí truy vấn khi một phần phân bổ được yêu cầu với 5% còn lại sẽ được chuyển cho delegator. + +- **indexingRewardCut** - % phần thưởng indexing được tích lũy trên một subgraph sẽ được phân phối cho indexer. Nếu thông số này được đặt là 95%, indexer sẽ nhận được 95% của pool phần thưởng indexing khi một phần phân bổ được đóng và các delegator sẽ chia 5% còn lại. + +### Làm thế nào để indexer biết những subgraph nào cần index? + +Indexer có thể tự phân biệt bản thân bằng cách áp dụng các kỹ thuật nâng cao để đưa ra quyết định index subgraph nhưng để đưa ra ý tưởng chung, chúng ta sẽ thảo luận một số số liệu chính được sử dụng để đánh giá các subgraph trong mạng: + +- **Tín hiệu curation** - Tỷ lệ tín hiệu curation mạng được áp dụng cho một subgraph cụ thể là một chỉ báo tốt về mức độ quan tâm đến subgraph đó, đặc biệt là trong giai đoạn khởi động khi khối lượng truy vấn đang tăng lên. + +- **Phí truy vấn đã thu** - Dữ liệu lịch sử về khối lượng phí truy vấn được thu thập cho một subgraph cụ thể là một chỉ báo tốt về nhu cầu trong tương lai. + +- **Số tiền được stake** - Việc theo dõi hành vi của những indexer khác hoặc xem xét tỷ lệ tổng stake được phân bổ cho subgraph cụ thể có thể cho phép indexer giám sát phía nguồn cung cho các truy vấn subgraph để xác định các subgraph mà mạng đang thể hiện sự tin cậy hoặc các subgraph có thể cho thấy nhu cầu nguồn cung nhiều hơn. + +- **Subgraph không có phần thưởng indexing** - Một số subgraph không tạo ra phần thưởng indexing chủ yếu vì chúng đang sử dụng các tính năng không được hỗ trợ như IPFS hoặc vì chúng đang truy vấn một mạng khác bên ngoài mainnet. Bạn sẽ thấy một thông báo trên một subgraph nếu nó không tạo ra phần thưởng indexing. + +### Có các yêu cầu gì về phần cứng (hardware)? + +
    +
  • + Nhỏ - Đủ để bắt đầu index một số subgraph, có thể sẽ cần được mở rộng. +
  • +
  • + Tiêu chuẩn - Thiết lập mặc định, đây là những gì được sử dụng trong bản kê khai (manifest) triển khai mẫu + k8s/terraform. +
  • +
  • + Trung bình - Công cụ indexing production hỗ trợ 100 đồ subgraph và 200-500 yêu cầu mỗi giây. +
  • +
  • + Lớn - Được chuẩn bị để index tất cả các subgraph hiện đang được sử dụng và phục vụ các yêu cầu cho lưu lượng + truy cập liên quan. +
  • +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Thiết lập +
Postgres
+
(CPUs)
+
+
Postgres
+
(bộ nhớ tính bằng GB)
+
+
Postgres
+
(đĩa tính bằng TBs)
+
+
VMs
+
(CPUs)
+
+
VMs
+
(bộ nhớ tính bằng GB)
+
Nhỏ481416
Tiêu chuẩn83011248
Trung bình166423264
Lớn724683,548184
+
+ +### Một số biện pháp phòng ngừa bảo mật cơ bản mà indexer nên thực hiện là gì? + +- **Ví Operator** - Thiết lập ví của operator là một biện pháp phòng ngừa quan trọng vì nó cho phép indexer duy trì sự tách biệt giữa các khóa kiểm soát stake của họ và những khóa kiểm soát hoạt động hàng ngày. Xem [Stake trong Giao thức](/indexing#stake-in-the-protocol) để được hướng dẫn. + +- **Tường lửa** - Chỉ dịch vụ indexer cần được hiển thị công khai và cần đặc biệt chú ý đến việc khóa các cổng quản trị và quyền truy cập cơ sở dữ liệu: điểm cuối The Graph Node JSON-RPC (cổng mặc định: 8030), điểm cuối API quản lý indexer (cổng mặc định: 18000), và điểm cuối cơ sở dữ liệu Postgres (cổng mặc định: 5432) không được để lộ. + +## Cơ sở hạ tầng + +Tại trung tâm của cơ sở hạ tầng của indexer là Graph Node theo dõi Ethereum, trích xuất và tải dữ liệu theo định nghĩa subgraph và phục vụ nó như một [GraphQL API](/about/introduction#how-the-graph-works). Graph Node cần được kết nối với điểm cuối node Ethereum EVM và node IPFS để tìm nguồn cung cấp dữ liệu; một cơ sở dữ liệu PostgreSQL cho kho lưu trữ của nó; và các thành phần indexer tạo điều kiện cho các tương tác của nó với mạng. + +- **Cơ sở dữ liệu PostgreSQLPostgreSQL** - Kho lưu trữ chính cho Graph Node, đây là nơi lưu trữ dữ liệu subgraph. Dịch vụ indexer và đại lý cũng sử dụng cơ sở dữ liệu để lưu trữ dữ liệu kênh trạng thái (state channel), mô hình chi phí và quy tắc indexing. + +- **Điểm cuối Ethereum** - Một điểm cuối cho thấy API Ethereum JSON-RPC. Điều này có thể ở dạng một ứng dụng khách Ethereum duy nhất hoặc nó có thể là một thiết lập phức tạp hơn để tải số dư trên nhiều máy khách. Điều quan trọng cần lưu ý là các subgraph nhất định sẽ yêu cầu các khả năng cụ thể của ứng dụng khách Ethereum như chế độ lưu trữ và API truy tìm. + +- **IPFS node (phiên bản nhỏ hơn 5)** - Siêu dữ liệu triển khai subgraph được lưu trữ trên mạng IPFS. Node The Graph chủ yếu truy cập vào node IPFS trong quá trình triển khai subgraph để tìm nạp tệp kê khai (manifest) subgraph và tất cả các tệp được liên kết. Indexers mạng lưới không cần lưu trữ node IPFS của riêng họ, một node IPFS cho mạng lưới được lưu trữ tại https://ipfs.network.thegraph.com. + +- **Dịch vụ Indexer** - Xử lý tất cả các giao tiếp bên ngoài được yêu cầu với mạng. Chia sẻ các mô hình chi phí và trạng thái indexing, chuyển các yêu cầu truy vấn từ các cổng đến Node The Graph và quản lý các khoản thanh toán truy vấn qua các kênh trạng thái với cổng. + +- **Đại lý Indexer ** - Tạo điều kiện thuận lợi cho các tương tác của Indexer trên blockchain bao gồm những việc như đăng ký trên mạng lưới, quản lý triển khai subgraph đối với Node The Graph của nó và quản lý phân bổ. Máy chủ số liệu Prometheus - Các thành phần Node The Graph và Indexer ghi các số liệu của chúng vào máy chủ số liệu. + +Lưu ý: Để hỗ trợ mở rộng quy mô nhanh, bạn nên tách các mối quan tâm về truy vấn và indexing giữa các nhóm node khác nhau: node truy vấn và node index. + +### Tổng quan về các cổng + +> **Quan trọng**: Hãy cẩn thận về việc để lộ các cổng 1 cách công khai - **cổng quản lý** nên được giữ kín. Điều này bao gồm JSON-RPC Node The Graph và các điểm cuối quản lý indexer được trình bày chi tiết bên dưới. + +#### Graph Node + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CổngMục đíchTuyếnĐối số CLI + Biến
Môi trường +
8000 + GraphQL HTTP server
+ (dành cho các truy vấn subgraph) +
+ /subgraphs/id/... +
+
+ /subgraphs/name/.../... +
--http-port-
8001 + GraphQL WS
(Dành cho đăng ký subgraph) +
+ /subgraphs/id/... +
+
+ /subgraphs/name/.../... +
--ws-port-
8020 + JSON-RPC
+ (để quản lý triển khai) +
/--admin-port-
8030API trạng thái indexing subgraph/graphql--index-node-port-
8040Số liệu Prometheus/metrics-metrics-port-
+
+ +#### Dịch vụ Indexer + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
CổngMục đíchTuyếnĐối số CLIBiến Môi trường
7600 + GraphQL HTTP server
(Dành cho các truy vấn subgraph có trả phí) +
+ /subgraphs/id/... +
+ /status +
+ /channel-messages-inbox +
--portINDEXER_SERVICE_PORT
7300Số liệu Prometheus/metrics--metrics-port-
+
+ +#### Đại lý Indexer + +
+ + + + + + + + + + + + + + + + + + + +
CổngMục đíchTuyếnĐối số CLIBiến Môi trường
8000API quản lý Indexer/--indexer-management-portINDEXER_AGENT_INDEXER_MANAGEMENT_PORT
+
+ +### Thiết lập cơ sở hạ tầng máy chủ bằng Terraform trên Google Cloud + +#### Cài đặt điều kiện tiên quyết + +- Google Cloud SDK +- Công cụ dòng lệnh Kubectl +- Terraform + +#### Tạo một dự án Google Cloud + +- Sao chép hoặc điều hướng đến kho lưu trữ (repository) của indexer. + +- Điều hướng đến thư mục ./terraform, đây là nơi tất cả các lệnh sẽ được thực thi. + +```sh +cd địa hình +``` + +- Xác thực với Google Cloud và tạo một dự án mới. + +```sh +gcloud auth login +project= +gcloud projects create --enable-cloud-apis $project +``` + +- Sử dụng \[billing page\](billing page) của Google Cloud Consolde để cho phép thanh toán cho dự án mới. + +- Tạo một cấu hình Google Cloud. + +```sh +proj_id=$(gcloud projects list --format='get(project_id)' --filter="name=$project") +gcloud config configurations create $project +gcloud config set project "$proj_id" +gcloud config set compute/region us-central1 +gcloud config set compute/zone us-central1-a +``` + +- Bật các API Google Cloud được yêu cầu. + +```sh +gcloud services enable compute.googleapis.com +gcloud services enable container.googleapis.com +gcloud services enable servicenetworking.googleapis.com +gcloud services enable sqladmin.googleapis.com +``` + +- Tạo một tài khoản dịch vụ. + +```sh +svc_name= +gcloud iam service-accounts create $svc_name \ + --description="Service account for Terraform" \ + --display-name="$svc_name" +gcloud iam service-accounts list +# Get the email of the service account from the list +svc=$(gcloud iam service-accounts list --format='get(email)' +--filter="displayName=$svc_name") +gcloud iam service-accounts keys create .gcloud-credentials.json \ + --iam-account="$svc" +gcloud projects add-iam-policy-binding $proj_id \ + --member serviceAccount:$svc \ + --role roles/editor +``` + +- Bật tính năng ngang hàng (peering) giữa cơ sở dữ liệu và cụm Kubernetes sẽ được tạo trong bước tiếp theo. + +```sh +gcloud compute addresses create google-managed-services-default \ + --prefix-length=20 \ + --purpose=VPC_PEERING \ + --network default \ + --global \ + --description 'IP Range for peer networks.' +gcloud services vpc-peerings connect \ + --network=default \ + --ranges=google-managed-services-default +``` + +- Tạo tệp cấu hình terraform tối thiểu (cập nhật nếu cần). + +```sh +indexer= +cat > terraform.tfvars < \ + -f Dockerfile.indexer-service \ + -t indexer-service:latest \ +# Đại lý Indexer +docker build \ + --build-arg NPM_TOKEN= \ + -f Dockerfile.indexer-agent \ + -t indexer-agent:latest \ +``` + +- Chạy các thành phần + +```sh +docker run -p 7600:7600 -it indexer-service:latest ... +docker run -p 18000:8000 -it indexer-agent:latest ... +``` + +**LƯU Ý**: Sau khi khởi động vùng chứa, dịch vụ indexer sẽ có thể truy cập được tại [http://localhost:7600](http://localhost:7600) và đại lý indexer sẽ hiển thị API quản lý indexer tại [http://localhost:18000/](http://localhost:18000/). + +#### Sử dụng K8s and Terraform + +Xem phần [Thiết lập Cơ sở Hạ tầng Máy chủ bằng Terraform trên Google Cloud](/indexing#setup-server-infrastructure-using-terraform-on-google-cloud) + +#### Sử dụng + +> **LƯU Ý**: Tất cả các biến cấu hình thời gian chạy có thể được áp dụng dưới dạng tham số cho lệnh khi khởi động hoặc sử dụng các biến môi trường của định dạng `COMPONENT_NAME_VARIABLE_NAME`(ex. `INDEXER_AGENT_ETHEREUM`). + +#### Đại lý Indexer + +```sh +graph-indexer-agent start \ + --ethereum \ + --ethereum-network mainnet \ + --mnemonic \ + --indexer-address \ + --graph-node-query-endpoint http://localhost:8000/ \ + --graph-node-status-endpoint http://localhost:8030/graphql \ + --graph-node-admin-endpoint http://localhost:8020/ \ + --public-indexer-url http://localhost:7600/ \ + --indexer-geo-coordinates \ + --index-node-ids default \ + --indexer-management-port 18000 \ + --metrics-port 7040 \ + --network-subgraph-endpoint https://gateway.network.thegraph.com/network \ + --default-allocation-amount 100 \ + --register true \ + --inject-dai true \ + --postgres-host localhost \ + --postgres-port 5432 \ + --postgres-username \ + --postgres-password \ + --postgres-database indexer \ + | pino-pretty +``` + +#### Dịch vụ Indexer + +```sh +SERVER_HOST=localhost \ +SERVER_PORT=5432 \ +SERVER_DB_NAME=is_staging \ +SERVER_DB_USER= \ +SERVER_DB_PASSWORD= \ +graph-indexer-service start \ + --ethereum \ + --ethereum-network mainnet \ + --mnemonic \ + --indexer-address \ + --port 7600 \ + --metrics-port 7300 \ + --graph-node-query-endpoint http://localhost:8000/ \ + --graph-node-status-endpoint http://localhost:8030/graphql \ + --postgres-host localhost \ + --postgres-port 5432 \ + --postgres-username \ + --postgres-password \ + --postgres-database is_staging \ + --network-subgraph-endpoint https://gateway.network.thegraph.com/network \ + | pino-pretty +``` + +#### Indexer CLI + +Indexer CLI là một plugin dành cho [`@graphprotocol/graph-cli`](https://www.npmjs.com/package/@graphprotocol/graph-cli) có thể truy cập trong terminal tại `graph indexer`. + +```sh +graph indexer connect http://localhost:18000 +graph indexer status +``` + +#### Quản lý Indexer bằng cách sử dụng indexer CLI + +Đại lý indexer cần đầu vào từ một indexer để tự động tương tác với mạng thay mặt cho indexer. Cơ chế để xác định hành vi của đại lý indexer là **các quy tắc indexing**. Sử dụng **các quy tắc indexing** một indexer có thể áp dụng chiến lược cụ thể của họ để chọn các subgraph để lập chỉ mục và phục vụ các truy vấn. Các quy tắc được quản lý thông qua API GraphQL do đại lý phân phối và được gọi là API Quản lý Indexer. Công cụ được đề xuất để tương tác với **API Quản lý Indexer** là **Indexer CLI**, một extension cho **Graph CLI**. + +#### Sử dụng + +**Indexer CLI** kết nối với đại lý indexer, thường thông qua chuyển tiếp cổng (port-forwarding), vì vậy CLI không cần phải chạy trên cùng một máy chủ hoặc cụm. Để giúp bạn bắt đầu và cung cấp một số ngữ cảnh, CLI sẽ được mô tả ngắn gọn ở đây. + +- `graph indexer connect ` - Kết nối với API quản lý indexer. Thông thường, kết nối với máy chủ được mở thông qua chuyển tiếp cổng, vì vậy CLI có thể dễ dàng vận hành từ xa. (Ví dụ: `kubectl port-forward pod/ 8000:8000`) + +- `graph indexer rules get [options] ...]` - Lấy một hoặc nhiều quy tắc indexing bằng cách sử dụng `all` như là `` để lấy tất cả các quy tắc, hoặc `global` để lấy các giá trị mặc định chung. Một đối số bổ sung`--merged` có thể được sử dụng để chỉ định rằng các quy tắc triển khai cụ thể được hợp nhất với quy tắc chung. Đây là cách chúng được áp dụng trong đại lý indexer. + +- `graph indexer rules set [options] ...` - Đặt một hoặc nhiều quy tắc indexing. + +- `graph indexer rules start [options] ` - Bắt đầu indexing triển khai subgraph nếu có và đặt `decisionBasis` thành `always`, để đại lý indexer sẽ luôn chọn lập chỉ mục nó. Nếu quy tắc chung được đặt thành luôn thì tất cả các subgraph có sẵn trên mạng sẽ được lập chỉ mục. + +- `graph indexer rules stop [options] ` - Ngừng indexing triển khai và đặt `decisionBasis` không bao giờ, vì vậy nó sẽ bỏ qua triển khai này khi quyết định triển khai để lập chỉ mục. + +- `graph indexer rules maybe [options] ` — Đặt `thedecisionBasis` cho một triển khai thành `rules`, để đại lý indexer sẽ sử dụng các quy tắc indexing để quyết định có index việc triển khai này hay không. + +Tất cả các lệnh hiển thị quy tắc trong đầu ra có thể chọn giữa các định dạng đầu ra được hỗ trợ (`table`, `yaml`, and `json`) bằng việc sử dụng đối số `-output`. + +#### Các quy tắc indexing + +Các quy tắc Indexing có thể được áp dụng làm mặc định chung hoặc cho các triển khai subgraph cụ thể bằng cách sử dụng ID của chúng. Các trường `deployment` và `decisionBasis` là bắt buộc, trong khi tất cả các trường khác là tùy chọn. Khi quy tắc lập chỉ mục có `rules` như là `decisionBasis`, thì đại lý indexer sẽ so sánh các giá trị ngưỡng không null trên quy tắc đó với các giá trị được tìm nạp từ mạng để triển khai tương ứng. Nếu triển khai subgraph có các giá trị trên (hoặc thấp hơn) bất kỳ ngưỡng nào thì nó sẽ được chọn để index. + +Ví dụ: nếu quy tắc chung có `minStake` của **5** (GRT), bất kỳ triển khai subgraph nào có hơn 5 (GRT) stake được phân bổ cho nó sẽ được index. Các quy tắc ngưỡng bao gồm `maxAllocationPercentage`, `minSignal`, `maxSignal`, `minStake`, và `minAverageQueryFees`. + +Mô hình dữ liệu: + +```graphql +type IndexingRule { + deployment: string + allocationAmount: string | null + parallelAllocations: number | null + decisionBasis: IndexingDecisionBasis + maxAllocationPercentage: number | null + minSignal: string | null + maxSignal: string | null + minStake: string | null + minAverageQueryFees: string | null + custom: string | null +} + +IndexingDecisionBasis { + rules + never + always +} +``` + +#### Các mô hình chi phí + +Mô hình chi phí cung cấp định giá động cho các truy vấn dựa trên thuộc tính thị trường và truy vấn. Dịch vụ Indexer chia sẻ mô hình chi phí với các cổng cho mỗi subgraph mà chúng dự định phản hồi các truy vấn. Đến lượt mình, các cổng sử dụng mô hình chi phí để đưa ra quyết định lựa chọn indexer cho mỗi truy vấn và để thương lượng thanh toán với những indexer đã chọn. + +#### Agora + +Ngôn ngữ Agora cung cấp một định dạng linh hoạt để khai báo các mô hình chi phí cho các truy vấn. Mô hình giá Agora là một chuỗi các câu lệnh thực thi theo thứ tự cho mỗi truy vấn cấp cao nhất trong một truy vấn GraphQL. Đối với mỗi truy vấn cấp cao nhất, câu lệnh đầu tiên phù hợp với nó xác định giá cho truy vấn đó. + +Một câu lệnh bao gồm một vị từ (predicate), được sử dụng để đối sánh các truy vấn GraphQL và một biểu thức chi phí mà khi được đánh giá sẽ xuất ra chi phí ở dạng GRT thập phân. Các giá trị ở vị trí đối số được đặt tên của một truy vấn có thể được ghi lại trong vị từ và được sử dụng trong biểu thức. Các Globals có thể được đặt và thay thế cho các phần giữ chỗ trong một biểu thức. + +Mô hình chi phí mẫu: + +``` +# Câu lệnh này ghi lại giá trị bỏ qua (skip), +# sử dụng biểu thức boolean trong vị từ để khớp với các truy vấn cụ thể sử dụng `skip` +# và một biểu thức chi phí để tính toán chi phí dựa trên giá trị `skip` và SYSTEM_LOAD global +query { pairs(skip: $skip) { id } } when $skip > 2000 => 0.0001 * $skip * $SYSTEM_LOAD; + +# Mặc định này sẽ khớp với bất kỳ biểu thức GraphQL nào. +# Nó sử dụng một Global được thay thế vào biểu thức để tính toán chi phí +default => 0.1 * $SYSTEM_LOAD; +``` + +Ví dụ truy vấn chi phí bằng cách sử dụng mô hình trên: + +
+ + + + + + + + + + + + + + + + + + + + + +
Truy vấnGiá
{ pairs(skip: 5000) { id } }0.5 GRT
{ tokens { symbol } }0.1 GRT
{ pairs(skip: 5000) { id { tokens } symbol } }0.6 GRT
+
+ +#### Áp dụng mô hình chi phí + +Các mô hình chi phí được áp dụng thông qua Indexer CLI, chuyển chúng đến API Quản lý Indexer của đại lý indexer để lưu trữ trong cơ sở dữ liệu. Sau đó, Dịch vụ Indexer sẽ nhận chúng và cung cấp các mô hình chi phí tới các cổng bất cứ khi nào họ yêu cầu. + +```sh +indexer cost set variables '{ "SYSTEM_LOAD": 1.4 }' +indexer cost set model my_model.agora +``` + +## Tương tác với mạng + +### Stake trong giao thức + +Các bước đầu tiên để tham gia vào mạng với tư cách là Indexer là phê duyệt giao thức, stake tiền và (tùy chọn) thiết lập địa chỉ operator cho các tương tác giao thức hàng ngày. _ **Lưu ý**: Đối với các mục đích của các hướng dẫn này, Remix sẽ được sử dụng để tương tác hợp đồng, nhưng hãy thoải mái sử dụng công cụ bạn chọn ([OneClickDapp](https://oneclickdapp.com/), [ABItopic](https://abitopic.io/), và [MyCrypto](https://www.mycrypto.com/account) là một vài công cụ được biết đến khác)._ + +Khi một indexer đã stake GRT vào giao thức, [các thành phần indexer](/indexing#indexer-components) có thể được khởi động và bắt đầu tương tác của chúng với mạng. + +#### Phê duyệt các token + +1. Mở [Remix app](https://remix.ethereum.org/) trong một trình duyệt + +2. Trong `File Explorer` tạo một tệp tên **GraphToken.abi** với [token ABI](https://raw.githubusercontent.com/graphprotocol/contracts/mainnet-deploy-build/build/abis/GraphToken.json). + +3. Với `GraphToken.abi` đã chọn và mở trong trình chỉnh sửa, chuyển sang Deploy (Triển khai) và `Run Transactions` trong giao diện Remix. + +4. Trong môi trường (environment) chọn `Injected Web3` và trong `Account` chọn địa chỉ indexer của bạn. + +5. Đặt địa chỉ hợp đồng GraphToken - Dán địa chỉ hợp đồng GraphToken(`0xc944E90C64B2c07662A292be6244BDf05Cda44a7`) kế bên `At Address` và nhấp vào nút `At address` để áp dụng. + +6. Gọi chức năng `approve(spender, amount)` để phê duyệt hợp đồng Staking. Điền phần `spender` bằng địa chỉ hợp đồng Staking (`0xF55041E37E12cD407ad00CE2910B8269B01263b9`) và điền `amount` bằng số token để stake (tính bằng wei). + +#### Stake các token + +1. Mở [Remix app](https://remix.ethereum.org/) trong một trình duyệt + +2. Trong `File Explorer` tạo một tệp tene **Staking.abi** với Staking ABI. + +3. Với `Staking.abi` đã chọn và mở trong trình chỉnh sửa, chuyển sang `Deploy` và `Run Transactions` trong giao diện Remix. + +4. Trong môi trường (environment) chọn `Injected Web3` và trong `Account` chọn địa chỉ indexer của bạn. + +5. Đặt địa chỉ hợp đồng Staking - Dán địa chỉ hợp đồng Staking (`0xc944E90C64B2c07662A292be6244BDf05Cda44a7`) kế bên `At Address` và nhấp vào nút `At address` để áp dụng. + +6. Gọi lệnh `stake()` để stake GRT vào giao thức. + +7. (Tùy chọn) Indexer có thể chấp thuận một địa chỉ khác làm operator cho cơ sở hạ tầng indexer của họ để tách các khóa kiểm soát tiền khỏi những khóa đang thực hiện các hành động hàng ngày như phân bổ trên các subgraph và phục vụ các truy vấn (có trả tiền). Để đặt operator, hãy gọi lệnh `setOperator()` với địa chỉ operator. + +8. (Tùy chọn) Để kiểm soát việc phân phối phần thưởng và thu hút delegator một cách chiến lược, indexer có thể cập nhật thông số ủy quyền của họ bằng cách cập nhật indexingRewardCut (phần triệu), queryFeeCut (phần triệu) và cooldownBlocks (số khối). Để làm như vậy, hãy gọi `setDelegationParameters()`. Ví dụ sau đặt queryFeeCut phân phối 95% hoàn phí truy vấn cho indexer và 5% cho delegator, đặt indexingRewardCutto phân phối 60% phần thưởng indexing cho indexer và 40% cho delegator và đặt `thecooldownBlocks` chu kỳ đến 500 khối. + +``` +setDelegationParameters(950000, 600000, 500) +``` + +### Tuổi thọ của một phân bổ + +Sau khi được tạo bởi một indexer, một phân bổ lành mạnh sẽ trải qua bốn trạng thái. + +- **Đang hoạt động** - Sau khi phân bổ được tạo trên chain ([allocateFrom()](https://github.com/graphprotocol/contracts/blob/master/contracts/staking/Staking.sol#L873)) nó được xem là **đang hoạt động**. Một phần stake của chính indexer và/hoặc stake được ủy quyền được phân bổ cho việc triển khai subgraph, cho phép họ yêu cầu phần thưởng indexing và phục vụ các truy vấn cho việc triển khai subgraph đó. Đại lý indexer quản lý việc tạo phân bổ dựa trên các quy tắc của indexer. + +- **Đã đóng** - Một indexer có thể tự do đóng phân bổ sau khi 1 epoch ([closeAllocation()](https://github.com/graphprotocol/contracts/blob/master/contracts/staking/Staking.sol#L873)) hoặc đại lý indexer của họ sẽ tự động đóng phân bổ sau **maxAllocationEpochs** (hiện tại 28 ngày). Khi kết thúc phân bổ với bằng chứng hợp lệ về proof of indexing (POI), phần thưởng indexing của họ sẽ được phân phối cho indexer và những delegator của nó (xem "phần thưởng được phân phối như thế nào?" Bên dưới để tìm hiểu thêm). + +- **Hoàn thiện** - Sau khi phân bổ đã bị đóng, sẽ có một khoảng thời gian tranh chấp mà sau đó phân bổ được xem xét là **hoàn thiện** và nó có sẵn các khoản hoàn lại phí truy vấn khả dụng để được yêu cầu (claim()). Đại lý indexer giám sát mạng để phát hiện các phân bổ **hoàn thiện** yêu cầu chúng nếu chúng vượt quá ngưỡng có thể định cấu hình (và tùy chọn), **—-allocation-claim-threshold**. + +- **Đã yêu cầu** - Trạng thái cuối cùng của một phân bổ; nó đã chạy quá trình của nó dưới dạng phân bổ đang hoạt động, tất cả các phần thưởng đủ điều kiện đã được phân phối và các khoản bồi hoàn phí truy vấn của nó đã được yêu cầu. diff --git a/pages/vi/studio/billing.mdx b/pages/vi/studio/billing.mdx new file mode 100644 index 000000000000..588cd2ed2f40 --- /dev/null +++ b/pages/vi/studio/billing.mdx @@ -0,0 +1,68 @@ +--- +title: Billing on the Subgraph Studio +--- + +### Overview + +Invoices are statements of payment amounts owed by a customer and are typically generated on a weekly basis in the system. You’ll be required to pay fees based on the query fees you generate using your API keys. The billing contract lives on the [Polygon](https://polygon.technology/) network. It’ll allow you to: + +- Add and remove GRT +- Keep track of your balances based on how much GRT you have added to your account, how much you have removed, and your invoices +- Automatically clear payments based on query fees generated + +In order to add GRT to your account, you will need to go through the following steps: + +1. Purchase GRT and ETH on an exchange of your choice +2. Send the GRT and ETH to your wallet +3. Bridge GRT to Polygon using the UI + + a) You will receive 0.001 Matic in a few minutes after you send any amount of GRT to the Polygon bridge. You can track the transaction on [Polygonscan](https://polygonscan.com/) by inputting your address into the search bar. + +4. Add bridged GRT to the billing contract on Polygon. The billing contract address is: [0x10829DB618E6F520Fa3A01c75bC6dDf8722fA9fE](https://polygonscan.com/address/0x10829DB618E6F520Fa3A01c75bC6dDf8722fA9fE). + + a) In order to complete step #4, you'll need to switch your network in your wallet to Polygon. You can add Polygon's network by connecting your wallet and clicking on "Choose Matic (Polygon) Mainnet" [here.](https://chainlist.org/) Once you've added the network, switch it over in your wallet by navigating to the network pill on the top right hand side corner. In Metamask, the network is called **Matic Mainnnet.** + +At the end of each week, if you used your API keys, you will receive an invoice based on the query fees you have generated during this period. This invoice will be paid using GRT available in your balance. Query volume is evaluated by the API keys you own. Your balance will be updated after fees are withdrawn. + +#### Here’s how you go through the invoicing process: + +There are 4 states your invoice can be in: + +1. Created - your invoice has just been created and not been paid yet +2. Paid - your invoice has been successfully paid +3. Unpaid - there is not enough GRT in your balance on the billing contract +4. Error - there is an error processing the payment + +**See the diagram below for more information:** + +![Billing Flow](/img/billing-flow.png) + +For a quick demo of how billing works on the Subgraph Studio, check out the video below: + +
+ +
+ +### Multisig Users + +Multisigs are smart-contracts that can exist only on the network they have been created, so if you created one on Ethereum Mainnet - it will only exist on Mainnet. Since our billing uses Polygon, if you were to bridge GRT to the multisig address on Polygon the funds would be lost. + +To overcome this issue, we created [a dedicated tool](https://multisig-billing.thegraph.com/) that will help you deposit GRT on our billing contract (on behalf of the multisig) with a standard wallet / EOA (an account controlled by a private key). + +You can access our Multisig Billing Tool here: https://multisig-billing.thegraph.com/ + +This tool will guide you to go through the following steps: + +1. Connect your standard wallet / EOA (this wallet needs to own some ETH as well as the GRT you want to deposit) +2. Bridge GRT to Polygon. You will have to wait 7-8 minutes after the transaction is complete for the bridge transfer to be finalized. +3. Once your GRT is available on your Polygon balance you can deposit them to the billing contract while specifying the multisig address you are funding in the `Multisig Address` field. + +Once the deposit transaction has been confirmed you can go back to [Subgraph Studio](https://thegraph.com/studio/) and connect with your Gnosis Safe Multisig to create API keys and use them to generate queries. + +Those queries will generate invoices that will be paid automatically using the multisig’s billing balance. diff --git a/pages/vi/studio/deploy-subgraph-studio.mdx b/pages/vi/studio/deploy-subgraph-studio.mdx new file mode 100644 index 000000000000..2155d8fe8976 --- /dev/null +++ b/pages/vi/studio/deploy-subgraph-studio.mdx @@ -0,0 +1,68 @@ +--- +title: Deploy a Subgraph to the Subgraph Studio +--- + +Deploying a Subgraph to the Subgraph Studio is quite simple. This will take you through the steps to: + +- Install The Graph CLI (with both yarn and npm) +- Create your Subgraph in the Subgraph Studio +- Authenticate your account from the CLI +- Deploying a Subgraph to the Subgraph Studio + +## Installing Graph CLI + +We are using the same CLI to deploy subgraphs to our [hosted service](https://thegraph.com/hosted-service/) and to the [Subgraph Studio](https://thegraph.com/studio/). Here are the commands to install graph-cli. This can be done using npm or yarn. + +**Install with yarn:** + +```bash +yarn global add @graphprotocol/graph-cli +``` + +**Install with npm:** + +```bash +npm install -g @graphprotocol/graph-cli +``` + +## Create your Subgraph in Subgraph Studio + +Before deploying your actual subgraph you need to create a subgraph in [Subgraph Studio](https://thegraph.com/studio/). We recommend you read our [Studio documentation](/studio/subgraph-studio) to learn more about this. + +## Initialize your Subgraph + +Once your subgraph has been created in Subgraph Studio you can initialize the subgraph code using this command: + +```bash +graph init --studio +``` + +The `` value can be found on your subgraph details page in Subgraph Studio: + +![Subgraph Studio - Slug](/img/doc-subgraph-slug.png) + +After running `graph init`, you will be asked to input the contract address, network and abi that you want to query. Doing this will generate a new folder on your local machine with some basic code to start working on your subgraph. You can then finalize your subgraph to make sure it works as expected. + +## Graph Auth + +Before being able to deploy your subgraph to Subgraph Studio, you need to login to your account within the CLI. To do this, you will need your deploy key that you can find on your "My Subgraphs" page or on your subgraph details page. + +Here is the command that you need to use to authenticate from the CLI: + +```bash +graph auth --studio +``` + +## Deploying a Subgraph to Subgraph Studio + +Once you are ready, you can deploy your subgraph to Subgraph Studio. Doing this won't publish your subgraph to the decentralized network, it will only deploy it to your Studio account where you will be able to test it and update the metadata. + +Here is the CLI command that you need to use to deploy your subgraph. + +```bash +graph deploy --studio +``` + +After running this command, the CLI will ask for a version label, you can name it however you want, you can use labels such as `0.1` and `0.2` or use letters as well such as `uniswap-v2-0.1` . Those labels will be visible in Graph Explorer and can be used by curators to decide if they want to signal on this version or not, so choose them wisely. + +Once deployed, you can test your subgraph in Subgraph Studio using the playground, deploy another version if needed, update the metadata, and when you are ready, publish your subgraph to Graph Explorer. diff --git a/pages/vi/studio/multisig.mdx b/pages/vi/studio/multisig.mdx new file mode 100644 index 000000000000..164835bdb8a4 --- /dev/null +++ b/pages/vi/studio/multisig.mdx @@ -0,0 +1,82 @@ +--- +title: Using a Multisig Wallet +--- + +Subgraph Studio currently doesn't support signing with multisig wallets. Until then, you can follow this guide on how to publish your subgraph by invoking the [GNS contract](https://github.com/graphprotocol/contracts/blob/dev/contracts/discovery/GNS.sol) functions. + +### Create a Subgraph + +Similary to using a regular wallet, you can create a subgraph by connecting your non-multisig wallet in Subgraph Studio. Once you connect the wallet, simply create a new subgraph. Make sure you fill out all the details, such as subgraph name, description, image, website, and source code url if applicable. + +For initializing a starter subgraph, you can follow the commands shown in the UI, or simply run + +``` +graph init --studio +``` + +`SUBGRAPH_SLUG` is the name of your subgraph that you can copy from the UI, or from the URL in the browser. This command should create a folder in your file system with all the necessary files to start developing a subgraph. + +### Deploy a Subgraph + +Once your subgraph is ready to be deployed to the graph node, simply follow the commands shown in the UI, or run the following command: + +``` +graph deploy --studio +``` + +**Note**: Make sure that you are inside of the subgraph folder before running the command. + +### Publish a Subgraph or a Version + +You can either publish a new subgraph to the decentralized network or publish a new version of the previously published subgraph. + +#### Publish a New Subgraph + +There are a couple of ways to publish a subgraph using multisig wallets. Here we'll describe invoking the [`publishNewSubgraph`](https://github.com/graphprotocol/contracts/blob/dev/contracts/discovery/GNS.sol#L231) function in the [GNS contract](https://etherscan.io/address/0xaDcA0dd4729c8BA3aCf3E99F3A9f471EF37b6825) using Etherscan. + +Before we use that function, we need to generate input arguments for it. Access [this page](https://thegraph.com/studio/multisig) in Subgraph Studio and provide the following: + +- Ethereum address of your multisig wallet +- Subgraph that you want to publish +- Version that you want to publish + +After clicking on "Get Arguments", we'll generate all the contract arguments for you! + +There should be 4 arguments: + +- `graphAccount`: which is your multisig account address +- `subgraphDeploymentID`: the hex hash of the deployment ID for that subgraph +- `versionMetadata`: version metadata (label and description) that gets uploaded to IPFS. The hex hash value for that JSON file will be provided. +- `subgraphMetadata`: simlar to version metadata, subgraph metadata (name, image, description, website and source code url) gets uploaded to IPFS, and we provide the hex hash value for that JSON file + +With those 4 arguments, you should be able to: + +- Visit [our GraphProxy](https://etherscan.io/address/0xaDcA0dd4729c8BA3aCf3E99F3A9f471EF37b6825#writeProxyContract) contract on Etherscan +- Connect to Etherscan using WalletConnect via the WalletConnect Safe app of your multisig +- Call the `publishNewSubgraph` method with the paramaters that were generated by our tool + +#### Publish a New Version + +To publish a new version of an existing subgraph we first need to generate input arguments for it. Access [this page](https://thegraph.com/studio/multisig) in Subgraph Studio and provide: + +- Ethereum address of your multisig wallet +- Subgraph that you want to publish +- Version that you want to publish +- The ID of the subgraph you want to update in Graph Explorer + +After clicking on "Get Arguments" we'll generate all the contract arguments for you! + +On the right side of the UI under the `Publish New Version` title, there should be 4 arguments: + +- `graphAccount`: which is your Multisig account address +- `subgraphNumber`: is the number of your already published subgraph. It is a part of the subgraph id for a published subgraph queried through The Graph Network subgraph. +- `subgraphDeploymentID`: which is the hex hash of the deployment ID for that subgraph +- `versionMetadata`: version metadata (label and description) gets uploaded to IPFS, and we provide the hex hash value for that JSON file + +Now that we generated all the arguments you are ready to proceed and call the `publishNewVersion` method. In order to do so, you should: + +- Visit [the GraphProxy](https://etherscan.io/address/0xaDcA0dd4729c8BA3aCf3E99F3A9f471EF37b6825#writeProxyContract) contract on Etherscan +- Connect to Etherscan using WalletConnect via the WalletConnect Safe app of your Multisig +- Call the `publishNewVersion` method with the paramaters that were generated by our tool + +Once the transaction is successful, your subgraph should have a new version of your subgraph in Graph Explorer which means that curators can start signaling on it and indexers can start indexing it. diff --git a/pages/vi/studio/studio-faq.mdx b/pages/vi/studio/studio-faq.mdx new file mode 100644 index 000000000000..4db4d7ccddaa --- /dev/null +++ b/pages/vi/studio/studio-faq.mdx @@ -0,0 +1,21 @@ +--- +title: Subgraph Studio FAQs +--- + +### 1. How do I create an API Key? + +In the Subgraph Studio, you can create API Keys as needed and add security settings to each of them. + +### 2. Can I create multiple API Keys? + +A: Yes! You can create multiple API Keys to use in different projects. Check out the link [here](https://thegraph.com/studio/apikeys/). + +### 3. How do I restrict a domain for an API Key? + +After creating an API Key, in the Security section you can define the domains that can query a specific API Key. + +### 4. How do I find query URLs for subgraphs if I’m not the developer of the subgraph I want to use? + +You can find the query URL of each subgraph in the Subgraph Details section of The Graph Explorer. When you click on the “Query” button, you will be directed to a pane wherein you can view the query URL of the subgraph you’re interested in. You can then replace the `` placeholder with the API key you wish to leverage in the Subgraph Studio. + +Remember that you can create an API key and query any subgraph published to the network, even if you build a subgraph yourself. These queries via the new API key, are paid queries as any other on the network. diff --git a/pages/vi/studio/subgraph-studio.mdx b/pages/vi/studio/subgraph-studio.mdx new file mode 100644 index 000000000000..9af3926db3df --- /dev/null +++ b/pages/vi/studio/subgraph-studio.mdx @@ -0,0 +1,122 @@ +--- +title: How to Use the Subgraph Studio +--- + +Welcome to your new launchpad 👩🏽‍🚀 + +The Subgraph Studio is your place to build and create subgraphs, add metadata, and publish them to the new decentralized Explorer (more on that [here](/explorer)). + +What you can do in the Subgraph Studio: + +- Create a subgraph through the Studio UI +- Deploy a subgraph using the CLI +- Publish a subgraph with the Studio UI +- Test it in the playground +- Integrate it in staging using the query URL +- Create and manage your API keys for specific subgraphs + +Here in the Subgraph Studio, you have full control over your subgraphs. Not only can you test your subgraphs before you publish them, but you can also restrict your API keys to specific domains and only allow certain indexers to query from their API keys. + +Querying subgraphs generates query fees, used to reward [indexers](/indexing) on the Graph network. If you’re a dapp developer or subgraph developer, the Studio will empower you to build better subgraphs to power your or your community’s queries. The Studio is comprised of 5 main parts: + +- Your user account controls +- A list of subgraphs that you’ve created +- A section to manage, view details, and visualize the status of a specific subgraph +- A section to manage your API keys that you will need to query a subgraph +- A section to manage your billing + +## How to Create Your Account + +1. Sign in with your wallet - you can do this via MetaMask or WalletConnect +1. Once you sign in, you will see your unique deploy key in your account home page. This will allow you to either publish your subgraphs or manage your API keys + billing. You will have a unique deploy key that can be re-generated if you think it has been compromised. + +## How to Create your Subgraph in Subgraph Studio + +The best part! When you first create a subgraph, you’ll be directed to fill out: + +- Your Subgraph Name +- Image +- Description +- Categories +- Website + +## Subgraph Compatibility with The Graph Network + +The Graph Network is not yet able to support all of the data-sources & features available on the Hosted Service. In order to be supported by indexers on the network, subgraphs must: + +- Index mainnet Ethereum +- Must not use any of the following features: + - ipfs.cat & ipfs.map + - Non-fatal errors + - Grafting + +More features & networks will be added to The Graph Network incrementally. + +### Subgraph lifecycle flow + +![Subgraph Lifecycle](/img/subgraph-lifecycle.png) + +After you have created your subgraph, you will be able to deploy it using the [CLI](https://github.com/graphprotocol/graph-cli), or command line interface. Deploying a subgraph with the CLI will push the subgraph to the Studio where you’ll be able to test subgraphs using the playground. This will eventually allow you to publish to the Graph Network. For more information on CLI setup, [check this out](/developer/define-subgraph-hosted#install-the-graph-cli) (pst, make sure you have your deploy key on hand). Remember, deploying is **not the same as** publishing. When you deploy a subgraph, you just push it to the Studio where you’re able to test it. Versus, when you publish a subgraph, you are publishing it on-chain. + +## Testing your Subgraph in Subgraph Studio + +If you’d like to test your subgraph before publishing it to the network, you can do this in the Subgraph **Playground** or look at your logs. The Subgraph logs will tell you **where** your subgraph fails in the case that it does. + +## Publish your Subgraph in Subgraph Studio + +You’ve made it this far - congrats! Publishing your subgraph means that an IPFS hash was generated when you deployed the subgraph within the CLI and is stored in the network’s Ethereum smart contracts. In order to publish your subgraph successfully, you’ll need to go through the following steps outlined in this [blog](https://thegraph.com/blog/building-with-subgraph-studio). Check out the video overview below as well: + +
+ +
+ +Remember, while you’re going through your publishing flow, you’ll be able to push to either mainnet or Rinkeby, the testnet we support. If you’re a first time subgraph developer, we highly suggest you start with publishing to Rinkeby, which is free to do. This will allow you to see how the subgraph will work in The Graph Explorer and will allow you to test curation elements. + +You’ll only be able to index data from mainnet (even if your subgraph was published to a testnet) because only subgraphs that are indexing mainnet data can be published to the network. This is because indexers need to submit mandatory Proof of Indexing records as of a specific block hash. Because publishing a subgraph is an action taken on-chain, remember that the transaction can take up to a few minutes to go through. Any address you use to publish the contract will be the only one able to publish future versions. Choose wisely! + +Subgraphs with curation signal are shown to Indexers so that they can be indexed on the decentralized network. You can publish subgraphs and signal in one transaction, which allows you to mint the first curation signal on the subgraph and saves on gas costs. By adding your signal to the signal later provided by Curators, your subgraph will also have a higher chance of ultimately serving queries. + +**Now that you’ve published your subgraph, let’s get into how you’ll manage them on a regular basis.** Note that you cannot publish your subgraph to the network if it has failed syncing. This is usually because the subgraph has bugs - the logs will tell you where those issues exist! + +## Versioning your Subgraph with the CLI + +Developers might want to update their subgraph, for a variety of reasons. When this is the case, you can deploy a new version of your subgraph to the Studio using the CLI (it will only be private at this point) and if you are happy with it, you can publish this new deployment to The Graph Explorer. This will create a new version of your subgraph that curators can start signaling on and indexers will be able to index this new version. + +Up until recently, developers were forced to deploy and publish a new version of their subgraph to the Explorer to update the metadata of their subgraphs. Now, developers can update the metadata of their subgraphs **without having to publish a new version**. Developers can update their subgraph details in the Studio (under profile picture, name, description, etc) by checking an option called **Update Details** in The Graph Explorer. 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. + +Please note that there are costs associated with publishing a new version of a subgraph to the network. In addition to the transaction fees, developers must also fund a part of the curation tax on auto-migrating signal. You cannot publish a new version of your subgraph if curators have not signaled on it. For more information on the risks of curation, please read more [here](/curating). + +### Automatic Archiving of Subgraph Versions + +Whenever you deploy a new subgraph version in the Subgraph Studio, the previous version will be archived. Archived versions won't be indexed/synced and therefore cannot be queried. You can unarchive an archived version of your subgraph in the Studio UI. Please note that previous versions of non-published subgraphs deployed to the Studio will be automatically archived. + +![Subgraph Studio - Unarchive](/img/Unarchive.png) + +## Managing your API Keys + +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. + +The Studio will list out existing API keys, which will give you the ability to manage or delete them. + +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 **Manage Security Settings**, 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 + +## How to Manage your Subgraph + +API keys aside, you’ll have many tools at your disposal to manage your subgraphs. You can organize your subgraphs by their **status** and **category**. + +- The **Status** tag allows you to pick between a variety of tags including ``, ``, ``, ``, etc. +- Meanwhile, **Category** allows you to designate what category your subgraph falls into. Options include ``, ``, ``, etc. diff --git a/pages/vi/supported-networks/near.mdx b/pages/vi/supported-networks/near.mdx new file mode 100644 index 000000000000..288ac380494c --- /dev/null +++ b/pages/vi/supported-networks/near.mdx @@ -0,0 +1,265 @@ +--- +title: Building Subgraphs on NEAR +--- + +> NEAR support in Graph Node and on the Hosted Service is in beta: please contact near@thegraph.com with any questions about building NEAR subgraphs! + +This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). + +## What is NEAR? + +[NEAR](https://near.org/) is a smart contract platform for building decentralised applications. Visit the [official documentation](https://docs.near.org/docs/concepts/new-to-near) for more information. + +## What are NEAR subgraphs? + +The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. + +Subgraphs are event-based, which means that they listen for and then process on-chain events. There are currently two types of handlers supported for NEAR subgraphs: + +- Block handlers: these are run on every new block +- Receipt handlers: run every time a message is executed at a specified account + +[From the NEAR documentation](https://docs.near.org/docs/concepts/transaction#receipt): + +> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. + +## Building a NEAR Subgraph + +`@graphprotocol/graph-cli` is a command line tool for building and deploying subgraphs. + +`@graphprotocol/graph-ts` is a library of subgraph-specific types. + +NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. + +> Building a NEAR subgraph is very similar to building a subgraph which indexes Ethereum. + +There are three aspects of subgraph definition: + +**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. + +**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developer/create-subgraph-hosted#the-graphql-schema). + +**AssemblyScript Mappings:** [AssemblyScript code](/developer/assemblyscript-api) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types, and new JSON parsing functionality. + +During subgraph development there are two key commands: + +```bash +$ graph codegen # generates types from the schema file identified in the manifest +$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +``` + +### Subgraph Manifest Definition + +The subgraph manifest (`subgraph.yaml`) identifies the data sources for the subgraph, the triggers of interest, and the functions that should be run in response to those triggers. See below for an example subgraph manifest for a NEAR subgraph:: + +```yaml +specVersion: 0.0.2 +schema: + file: ./src/schema.graphql # link to the schema file +dataSources: + - kind: near + network: near-mainnet + source: + account: app.good-morning.near # This data source will monitor this account + startBlock: 10662188 # Required for NEAR + mapping: + apiVersion: 0.0.5 + language: wasm/assemblyscript + blockHandlers: + - handler: handleNewBlock # the function name in the mapping file + receiptHandlers: + - handler: handleReceipt # the function name in the mapping file + file: ./src/mapping.ts # link to the file with the Assemblyscript mappings +``` + +- NEAR subgraphs introduce a new `kind` of data source (`near`) +- The `network` should correspond to a network on the hosting Graph Node. On the Hosted Service, NEAR's mainnet is `near-mainnet`, and NEAR's testnet is `near-testnet` +- NEAR data sources introduce an optional `source.account` field, which is a human readable ID corresponding to a [NEAR account](https://docs.near.org/docs/concepts/account). This can be an account, or a sub account. + +NEAR data sources support two types of handlers: + +- `blockHandlers`: run on every new NEAR block. No `source.account` is required. +- `receiptHandlers`: run on every receipt where the data source's `source.account` is the recipient. Note that only exact matches are processed ([subaccounts](https://docs.near.org/docs/concepts/account#subaccounts) must be added as independent data sources). + +### Schema Definition + +Schema definition describes the structure of the resulting subgraph database, and the relationships between entities. This is agnostic of the original data source. There are more details on subgraph schema definition [here](/developer/create-subgraph-hosted#the-graphql-schema). + +### AssemblyScript Mappings + +The handlers for processing events are written in [AssemblyScript](https://www.assemblyscript.org/). + +NEAR indexing introduces NEAR-specific data types to the [AssemblyScript API](/developer/assemblyscript-api). + +```typescript + +class ExecutionOutcome { + gasBurnt: u64, + blockHash: Bytes, + id: Bytes, + logs: Array, + receiptIds: Array, + tokensBurnt: BigInt, + executorId: string, + } + +class ActionReceipt { + predecessorId: string, + receiverId: string, + id: CryptoHash, + signerId: string, + gasPrice: BigInt, + outputDataReceivers: Array, + inputDataIds: Array, + actions: Array, + } + +class BlockHeader { + height: u64, + prevHeight: u64,// Always zero when version < V3 + epochId: Bytes, + nextEpochId: Bytes, + chunksIncluded: u64, + hash: Bytes, + prevHash: Bytes, + timestampNanosec: u64, + randomValue: Bytes, + gasPrice: BigInt, + totalSupply: BigInt, + latestProtocolVersion: u32, + } + +class ChunkHeader { + gasUsed: u64, + gasLimit: u64, + shardId: u64, + chunkHash: Bytes, + prevBlockHash: Bytes, + balanceBurnt: BigInt, + } + +class Block { + author: string, + header: BlockHeader, + chunks: Array, + } + +class ReceiptWithOutcome { + outcome: ExecutionOutcome, + receipt: ActionReceipt, + block: Block, + } +``` + +These types are passed to block & receipt handlers: + +- Block handlers will receive a `Block` +- Receipt handlers will receive a `ReceiptWithOutcome` + +Otherwise the rest of the [AssemblyScript API](/developer/assemblyscript-api) is available to NEAR subgraph developers during mapping execution. + +This includes a new JSON parsing function - logs on NEAR are frequently emitted as stringified JSONs. A new `json.fromString(...)` function is available as part of the [JSON API](/developer/assemblyscript-api#json-api) to allow developers to easily process these logs. + +## Deploying a NEAR Subgraph + +Once you have a built subgraph, it is time to deploy it to Graph Node for indexing. NEAR subgraphs can be deployed to any Graph Node `>=v0.26.x` (this version has not yet been tagged & released). + +The Graph's Hosted Service currently supports indexing NEAR mainnet and testnet in beta, with the following network names: + +- `near-mainnet` +- `near-testnet` + +More information on creating and deploying subgraphs on the Hosted Service can be found [here](/hosted-service/deploy-subgraph-hosted). + +As a quick primer - the first step is to "create" your subgraph - this only needs to be done once. On the Hosted Service, this can be done from [your Dashboard](https://thegraph.com/hosted-service/dashboard): "Add Subgraph". + +Once your subgraph has been created, you can deploy your subgraph by using the `graph deploy` CLI command: + +``` +$ graph create --node subgraph/name # creates a subgraph on a local Graph Node (on the Hosted Service, this is done via the UI) +$ graph deploy --node --ipfs https://api.thegraph.com/ipfs/ # uploads the build files to a specified IPFS endpoint, and then deploys the subgraph to a specified Graph Node based on the manifest IPFS hash +``` + +The node configuration will depend where the subgraph is being deployed. + +#### Hosted Service: + +``` +graph deploy --node https://api.thegraph.com/deploy/ --ipfs https://api.thegraph.com/ipfs/ --access-token +``` + +#### Local Graph Node (based on default configuration): + +``` +graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 +``` + +Once your subgraph has been deployed, it will be indexed by Graph Node. You can check its progress by querying the subgraph itself: + +``` +{ + _meta { + block { number } + } +} +``` + +### Indexing NEAR with a Local Graph Node + +Running a Graph Node that indexes NEAR has the following operational requirements: + +- NEAR Indexer Framework with Firehose instrumentation +- NEAR Firehose Component(s) +- Graph Node with Firehose endpoint configured + +We will provide more information on running the above components soon. + +## Querying a NEAR Subgraph + +The GraphQL endpoint for NEAR subgraphs is determined by the schema definition, with the existing API interface. Please visit the [GraphQL API documentation](/developer/graphql-api) for more information. + +## Example Subgraphs + +Here are some example subgraphs for reference: + +[NEAR Blocks](https://github.com/graphprotocol/example-subgraph/tree/near-blocks-example) + +[NEAR Receipts](https://github.com/graphprotocol/example-subgraph/tree/near-receipts-example) + +## FAQ + +### How does the beta work? + +NEAR support is in beta, which means that there may be changes to the API as we continue to work on improving the integration. Please email near@thegraph.com so that we can support you in building NEAR subgraphs, and keep you up to date on the latest developments! + +### Can a subgraph index both NEAR and EVM chains? + +No, a subgraph can only support data sources from one chain / network. + +### Can subgraphs react to more specific triggers? + +Currently, only Block and Receipt triggers are supported. We are investigating triggers for function calls to a specified account. We are also interested in supporting event triggers, once NEAR has native event support. + +### Will receipt handlers trigger for accounts and their sub accounts? + +Receipt handlers will only be triggered for the exact-match of the named account. More flexibility may be added in future. + +### Can NEAR subgraphs make view calls to NEAR accounts during mappings? + +This is not supported. We are evaluating whether this functionality is required for indexing. + +### Can I use data source templates in my NEAR subgraph? + +This is not currently supported. We are evaluating whether this functionality is required for indexing. + +### Ethereum subgraphs support "pending" and "current" versions, how can I deploy a "pending" version of a NEAR subgraph? + +Pending functionality is not yet supported for NEAR subgraphs. In the interim, you can deploy a new version to a different "named" subgraph, and then when that is synced with the chain head, you can redeploy to your primary "named" subgraph, which will use the same underlying deployment ID, so the main subgraph will be instantly synced. + +### My question hasn't been answered, where can I get more help building NEAR subgraphs? + +If it is a general question about subgraph development, there is a lot more information in the rest of the [Developer documentation](/developer/quick-start). Otherwise please join [The Graph Protocol Discord](https://discord.gg/vtvv7FP) and ask in the #near channel, or email near@thegraph.com. + +## References + +- [NEAR developer documentation](https://docs.near.org/docs/develop/basics/getting-started) diff --git a/pages/zh/about/introduction.mdx b/pages/zh/about/introduction.mdx index 5f840c040400..e4833d5e34be 100644 --- a/pages/zh/about/introduction.mdx +++ b/pages/zh/about/introduction.mdx @@ -1,47 +1,49 @@ --- -title: Introduction +title: 介绍 --- -This page will explain what The Graph is and how you can get started. +本页将解释什么是 The Graph,以及你如何开始。 -## What The Graph Is +## 什么是 The Graph -The Graph is a decentralized protocol for indexing and querying data from blockchains, starting with Ethereum. It makes it possible to query data that is difficult to query directly. +The Graph 是一个去中心化的协议,用于索引和查询区块链的数据,首先是从以太坊开始的。 它使查询那些难以直接查询的数据成为可能。 -Projects with complex smart contracts like [Uniswap](https://uniswap.org/) and NFTs initiatives like [Bored Ape Yacht Club](https://boredapeyachtclub.com/) store data on the Ethereum blockchain, making it really difficult to read anything other than basic data directly from the blockchain. +像 [Uniswap](https://uniswap.org/)这样具有复杂智能合约的项目,以及像 [Bored Ape Yacht Club](https://boredapeyachtclub.com/) 这样的 NFTs 倡议,都在以太坊区块链上存储数据,因此,除了直接从区块链上读取基本数据外,真的很难。 -In the case of Bored Ape Yacht Club, we can perform basic read operations on [the contract](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code) like getting the owner of a certain Ape, getting the content URI of an Ape based on their ID, or the total supply, as these read operations are programmed directly into the smart contract, but more advanced real-world queries and operations like aggregation, search, relationships, and non-trivial filtering are not possible. For example, if we wanted to query for apes that are owned by a certain address, and filter by one of its characteristics, we would not be able to get that information by interacting directly with the contract itself. +在 Bored Ape Yacht Club 的案例中,我们可以对 [合约](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code)进行基本的读取操作,比如获得某个 Ape 的所有者,根据他们的 ID 获得某个 Ape 的内容 URI,或者总供应量,因为这些读取操作是直接编入智能合约的,但是更高级的现实世界的查询和操作,比如聚合、搜索、关系和非粗略的过滤是不可能的。 例如,如果我们想查询某个地址所拥有的 apes,并通过它的某个特征进行过滤,我们将无法通过直接与合约本身进行交互来获得该信息。 -To get this data, you would have to process every single [`transfer`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) event ever emitted, read the metadata from IPFS using the Token ID and IPFS hash, and then aggregate it. Even for these types of relatively simple questions, it would take **hours or even days** for a decentralized application (dapp) running in a browser to get an answer. +为了获得这些数据,你必须处理曾经发出的每一个 [`传输`](https://etherscan.io/address/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#code#L1746) 事件,使用 Token ID 和 IPFS 的哈希值从 IPFS 读取元数据,然后将其汇总。 即使是这些类型的相对简单的问题,在浏览器中运行的去中心化应用程序(dapp)也需要**几个小时甚至几天** 才能得到答案。 -You could also build out your own server, process the transactions there, save them to a database, and build an API endpoint on top of it all in order to query the data. However, this option is resource intensive, needs maintenance, presents a single point of failure, and breaks important security properties required for decentralization. +你也可以建立你自己的服务器,在那里处理交易,把它们保存到数据库,并在上面建立一个 API 终端,以便查询数据。 然而,这种选择是资源密集型的,需要维护,会出现单点故障,并破坏了去中心化化所需的重要安全属性。 -**Indexing blockchain data is really, really hard.** +**为区块链数据编制索引真的非常非常难。** -Blockchain properties like finality, chain reorganizations, or uncled blocks complicate this process further, and make it not just time consuming but conceptually hard to retrieve correct query results from blockchain data. +区块链的属性,如最终性、链重组或未封闭的区块,使这一过程进一步复杂化,并使从区块链数据中检索出正确的查询结果不仅耗时,而且在概念上也很难。 -The Graph solves this with a decentralized protocol that indexes and enables the performant and efficient querying of blockchain data. These APIs (indexed "subgraphs") can then be queried with a standard GraphQL API. Today, there is a hosted service as well as a decentralized protocol with the same capabilities. Both are backed by the open source implementation of [Graph Node](https://github.com/graphprotocol/graph-node). +The Graph 通过一个去中心化的协议解决了这一问题,该协议可以对区块链数据进行索引并实现高性能和高效率的查询。 这些 API(索引的 "子图")然后可以用标准的 GraphQL API 进行查询。 今天,有一个托管服务,也有一个具有相同功能的分去中心化协议。 两者都由 [](https://github.com/graphprotocol/graph-node)Graph Node -## How The Graph Works +的开放源码实现支持。 -The Graph learns what and how to index Ethereum data based on subgraph descriptions, known as the subgraph manifest. The subgraph description defines the smart contracts of interest for a subgraph, the events in those contracts to pay attention to, and how to map event data to data that The Graph will store in its database. +## The Graph 是如何工作的 -Once you have written a `subgraph manifest`, you use the Graph CLI to store the definition in IPFS and tell the indexer to start indexing data for that subgraph. +Graph 根据子图描述(称为子图清单)来学习什么以及如何为以太坊数据建立索引。 子图描述定义了子图所关注的智能合约,这些合约中需要关注的事件,以及如何将事件数据映射到 The Graph 将存储在其数据库中的数据。 -This diagram gives more detail about the flow of data once a subgraph manifest has been deployed, dealing with Ethereum transactions: +一旦你写好了 `子图清单 `,你就可以使用 Graph CLI 将该定义存储在 IPFS 中,并告诉索引人开始为该子图编制索引数据。 + +这张图更详细地介绍了一旦部署了子图清单,处理以太坊交易的数据流。 ![](/img/graph-dataflow.png) -The flow follows these steps: +流程遵循这些步骤: -1. A decentralized application adds data to Ethereum through a transaction on a smart contract. -2. The smart contract emits one or more events while processing the transaction. -3. Graph Node continually scans Ethereum for new blocks and the data for your subgraph they may contain. -4. Graph Node finds Ethereum events for your subgraph in these blocks and runs the mapping handlers you provided. The mapping is a WASM module that creates or updates the data entities that Graph Node stores in response to Ethereum events. -5. The decentralized application queries the Graph Node for data indexed from the blockchain, using the node's [GraphQL endpoint](https://graphql.org/learn/). The Graph Node in turn translates the GraphQL queries into queries for its underlying data store in order to fetch this data, making use of the store's indexing capabilities. The decentralized application displays this data in a rich UI for end-users, which they use to issue new transactions on Ethereum. The cycle repeats. +1. 一个去中心化的应用程序通过智能合约上的交易向以太坊添加数据。 +2. 智能合约在处理交易时,会发出一个或多个事件。 +3. Graph 节点不断扫描以太坊的新区块和它们可能包含的子图的数据。 +4. Graph 节点在这些区块中为你的子图找到 Ethereum 事件并运行你提供的映射处理程序。 映射是一个 WASM 模块,它创建或更新 Graph Node 存储的数据实体,以响应 Ethereum 事件。 +5. 去中心化的应用程序使用节点的[GraphQL 端点](https://graphql.org/learn/),从区块链的索引中查询 Graph 节点的数据。 Graph 节点反过来将 GraphQL 查询转化为对其底层数据存储的查询,以便利用存储的索引功能来获取这些数据。 去中心化的应用程序在一个丰富的用户界面中为终端用户显示这些数据,他们用这些数据在以太坊上发行新的交易。 就这样周而复始。 -## Next Steps +## 下一步 -In the following sections we will go into more detail on how to define subgraphs, how to deploy them, and how to query data from the indexes that Graph Node builds. +在下面的章节中,我们将更详细地介绍如何定义子图,如何部署它们,以及如何从 Graph 节点建立的索引中查询数据。 -Before you start writing your own subgraph, you might want to have a look at the Graph Explorer and explore some of the subgraphs that have already been deployed. The page for each subgraph contains a playground that lets you query that subgraph's data with GraphQL. +在你开始编写你自己的子图之前,你可能想看一下 Graph 浏览器,探索一些已经部署的子图。 每个子图的页面都包含一个操作面板,让你用 GraphQL 查询该子图的数据。 diff --git a/pages/zh/about/network.mdx b/pages/zh/about/network.mdx index b19f08d12bc7..7cdb059d6279 100644 --- a/pages/zh/about/network.mdx +++ b/pages/zh/about/network.mdx @@ -1,15 +1,15 @@ --- -title: Network Overview +title: 网络概述 --- -The Graph Network is a decentralized indexing protocol for organizing blockchain data. Applications use GraphQL to query open APIs called subgraphs, to retrieve data that is indexed on the network. With The Graph, developers can build serverless applications that run entirely on public infrastructure. +The Graph网络是一个去中心化的索引协议,用于组织区块链数据。 应用程序使用GraphQL查询称为子图的开放API,以检索网络上的索引数据。 通过The Graph,开发者可以建立完全在公共基础设施上运行的无服务器应用程序。 -> GRT Token Address: [0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) +> Grt合约地址:[0xc944e90c64b2c07662a292be6244bdf05cda44a7](https://etherscan.io/token/0xc944e90c64b2c07662a292be6244bdf05cda44a7) -## Overview +## 概述 -The Graph Network consists of Indexers, Curators and Delegators that provide services to the network, and serve data to Web3 applications. Consumers use the applications and consume the data. +The Graph网络由索引人、策展人和委托人组成,为网络提供服务,并为Web3应用程序提供数据。 消费者使用应用程序并消费数据。 -![Token Economics](/img/Network-roles@2x.png) +![代币经济学](/img/Network-roles@2x.png) -To ensure economic security of The Graph Network and the integrity of data being queried, participants stake and use Graph Tokens (GRT). GRT is a work token that is an ERC-20 on the Ethereum blockchain, used to allocate resources in the network. Active Indexers, Curators and Delegators can provide services and earn income from the network, proportional to the amount of work they perform and their GRT stake. +为了确保The Graph 网络的经济安全和被查询数据的完整性,参与者将Graph 令牌(GRT)质押并使用。 GRT是一种工作代币,是以太坊区块链上的ERC-20,用于分配网络中的资源。 活跃的索引人、策展人和委托人可以提供服务,并从网络中获得收入,与他们的工作量和他们的GRT委托量成正比。 diff --git a/pages/zh/curating.mdx b/pages/zh/curating.mdx index cc29f02f941c..66ed9fe2bd2a 100644 --- a/pages/zh/curating.mdx +++ b/pages/zh/curating.mdx @@ -8,7 +8,7 @@ title: 策展 Remember that curation is risky. 请做好你的工作,确保你在你信任的子图上进行策展。 请做好你的工作,确保你在你信任的子图上进行策展。 创建子图是没有权限的,所以人们可以创建子图,并称其为任何他们想要的名字。 关于策展风险的更多指导,请查看 [The Graph Academy 的策展指南。 ](https://thegraph.academy/curators/) -## 粘合曲线 101 +## 联合曲线 101 首先,我们退一步讲。 每个子图都有一条粘合曲线,当用户在曲线上 **添加**信号时,策展份额就在这条曲线上被铸造出来。 每个子图的粘合曲线都是独一无二的。 粘合曲线的结构是这样的:在一个子图上铸造一个策展份额的价格随着铸造的份额数量而线性增加。 @@ -16,7 +16,7 @@ Remember that curation is risky. 请做好你的工作,确保你在你信任 因此,价格是线性增长的,这意味着随着时间的推移,购买股票的成本会越来越高。 这里有一个例子说明我们的意思,请看下面的粘合曲线。 -![Bonding curve](/img/bonding-curve.png) +![联合曲线](/img/bonding-curve.png) 考虑到我们有两个策展人,他们为一个子图铸造了股份: @@ -49,7 +49,7 @@ Remember that curation is risky. 请做好你的工作,确保你在你信任 因此,如果索引人不得不猜测他们应该索引哪些子图,那么他们赚取强大的查询费用的机会就会很低,因为他们没有办法验证哪些子图是高质量的。 进入策展阶段。 -策展人使 The Graph 网络变得高效,信号是策展人用来让索引人知道一个子图是好的索引的过程,其中 GRT 被存入子图的粘合曲线。 索引人可以从本质上信任策展人的信号,因为一旦发出信号,策展人就会为该子图铸造一个策展份额,使他们有权获得该子图所带来的部分未来查询费用。 Curator signal is represented as ERC20 tokens called Graph Curation Shares (GCS). 想赚取更多查询费的策展人应该向他们预测会给网络带来大量费用的子图发出他们的 GRT 信号。 策展人不能因为不良行为而被砍掉,但有一个对策展人的存款税,以抑制可能损害网络完整性的不良决策。 如果策展人选择在一个低质量的子图上进行策展,他们也会赚取较少的查询费,因为有较少的查询需要处理,或者有较少的索引人处理这些查询。 请看下面的图! +策展人使 The Graph 网络变得高效,信号是策展人用来让索引人知道一个子图是好的索引的过程,其中 GRT 被存入子图的粘合曲线。 索引人可以从本质上信任策展人的信号,因为一旦发出信号,策展人就会为该子图铸造一个策展份额,使他们有权获得该子图所带来的部分未来查询费用。 策展人的信号以ERC20代币的形式表示,称为Graph Curation Shares(GCS)。 想赚取更多查询费的策展人应该向他们预测会给网络带来大量费用的子图发出他们的 GRT 信号。 策展人不能因为不良行为而被砍掉,但有一个对策展人的存款税,以抑制可能损害网络完整性的不良决策。 如果策展人选择在一个低质量的子图上进行策展,他们也会赚取较少的查询费,因为有较少的查询需要处理,或者有较少的索引人处理这些查询。 请看下面的图! ![Signaling diagram](/img/curator-signaling.png) @@ -64,7 +64,7 @@ Remember that curation is risky. 请做好你的工作,确保你在你信任 3. 当策展人烧掉他们的股份以提取 GRT 时,剩余股份的 GRT 估值将被降低。 请注意,在某些情况下,策展人可能决定 **一次性**烧掉他们的股份。 这种情况可能很常见,如果一个 dApp 开发者停止版本/改进和查询他们的子图,或者如果一个子图失败。 因此,剩下的策展人可能只能提取他们最初 GRT 的一小部分。 关于风险较低的网络角色,请看委托人 \[Delegators\](https://thegraph.com/docs/delegating). 4. 一个子图可能由于错误而失败。 一个失败的子图不会累积查询费用。 因此,你必须等待,直到开发人员修复错误并部署一个新的版本。 - 如果你订阅了一个子图的最新版本,你的股份将自动迁移到该新版本。 这将产生 0.5%的策展税。 - - 如果你已经在一个特定的子图版本上发出信号,但它失败了,你将不得不手动烧毁你的策展税。 请注意,你可能会收到比你最初存入策展曲线更多或更少的 GRT,这是作为策展人的相关风险。 You can then signal on the new subgraph version, thus incurring a 1% curation tax. + - 如果你已经在一个特定的子图版本上发出信号,但它失败了,你将不得不手动烧毁你的策展税。 请注意,你可能会收到比你最初存入策展曲线更多或更少的 GRT,这是作为策展人的相关风险。 然后你可以在新的子图版本上发出信号,从而产生1%的策展税。 ## 策展常见问题 @@ -79,11 +79,11 @@ Remember that curation is risky. 请做好你的工作,确保你在你信任 - 策展人可以利用他们的市场知识,尝试预测单个子图在未来可能产生更多或更少的查询量 - 策展人还应该了解通过 The Graph 浏览器提供的指标。 像过去的查询量和子图开发者是谁这样的指标可以帮助确定一个子图是否值得发出信号。 -### 3. What’s the cost of upgrading a subgraph? +### 3. 升级一个子图的成本是多少? 将你的策展份额迁移到一个新的子图版本会产生 1%的策展税。 策展人可以选择订阅子图的最新版本。 当策展人质押被自动迁移到一个新的版本时,策展人也将支付一半的策展税,即 0.5%,因为升级子图是一个链上动作,需要花费交易费。 -### 4. How often can I upgrade my subgraph? +### 4. 我多长时间可以升级我的子图? 建议你不要太频繁地升级你的子图。 更多细节请见上面的问题。 @@ -100,5 +100,5 @@ Remember that curation is risky. 请做好你的工作,确保你在你信任 title="YouTube video player" frameBorder="0" allowFullScreen - > +> diff --git a/pages/zh/delegating.mdx b/pages/zh/delegating.mdx index 903363025da7..8ba0e39c9035 100644 --- a/pages/zh/delegating.mdx +++ b/pages/zh/delegating.mdx @@ -2,11 +2,11 @@ title: 委托 --- -Delegators cannot be slashed for bad behavior, but there is a deposit tax on Delegators to disincentivize poor decision making that could harm the integrity of the network. +委托人不能因为不良行为而被取消,但对委托有存款税,以抑制可能损害网络完整性的不良决策。 ## 委托人指南 -This guide will explain how to be an effective delegator in the Graph Network. Delegators share earnings of the protocol alongside all indexers on their delegated stake. A Delegator must use their best judgement to choose Indexers based on multiple factors. Please note this guide will not go over steps such as setting up Metamask properly, as that information is widely available on the internet. There are three sections in this guide: +本指南将解释如何在Graph网络中成为一个有效的委托人。 委托人与所有索引人一起分享其委托股权的协议收益。 委托人必须根据多种因素,运用他们的最佳判断力来选择索引人。 请注意,本指南将不涉及正确设置Metamask等步骤,因为这些信息在互联网上广泛存在。 本指南有三个部分: - 在 The Graph 网络中委托代币的风险 - 如何计算作为委托人的预期回报 @@ -14,7 +14,7 @@ This guide will explain how to be an effective delegator in the Graph Network. D ## 委托风险 -Listed below are the main risks of being a delegator in the protocol. +下面列出了作为议定书中的委托人的主要风险。 ### 委托费用 @@ -28,7 +28,9 @@ Listed below are the main risks of being a delegator in the protocol. 还需要考虑的一件事是明智地选择索引人。 如果您选择了一个不值得信赖的 索引人,或者没有做好工作,您将想要取消委托,这意味着您将失去很多获得奖励的机会,这可能与燃烧 GRT 一样糟糕。 -
请注意委托用户界面中的0.5%费用,以及28天的解约期。
+
+ 请注意委托用户界面中的0.5%费用,以及28天的解约期。 +
### 选择一个为委托人提供公平的奖励分配的值得信赖的索引人 @@ -65,7 +67,7 @@ Listed below are the main risks of being a delegator in the protocol. 因此,委托人可以进行数学计算,以确定向委托人提供 20% 的索引人提供了更好的回报。 -A delegator can therefore do the math to determine that the Indexer offering 20% to delegators, is offering a better return. +因此,委托人可以进行数学计算,以确定向委托人提供 20% 的 索引人提供了更好的回报。 ### 考虑委托容量 @@ -86,5 +88,5 @@ A delegator can therefore do the math to determine that the Indexer offering 20% title="YouTube video player" frameBorder="0" allowFullScreen - > +> diff --git a/pages/zh/developer/assemblyscript-api.mdx b/pages/zh/developer/assemblyscript-api.mdx index 2b6aa855c4a3..b5066fab02f2 100644 --- a/pages/zh/developer/assemblyscript-api.mdx +++ b/pages/zh/developer/assemblyscript-api.mdx @@ -43,13 +43,13 @@ The `@graphprotocol/graph-ts` library provides the following APIs: The `apiVersion` in the subgraph manifest specifies the mapping API version which is run by Graph Node for a given subgraph. The current mapping API version is 0.0.6. -| Version | Release notes | -| :-: | --- | -| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | -| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | -| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | -| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | -| 0.0.2 | Added `input` field to the Ethereum Transaction object | +| Version | Release notes | +|:-------:| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0.0.6 | Added `nonce` field to the Ethereum Transaction object
Added `baseFeePerGas` to the Ethereum Block object | +| 0.0.5 | AssemblyScript upgraded to version 0.19.10 (this includes breaking changes, please see the [`Migration Guide`](/developer/assemblyscript-migration-guide))
`ethereum.transaction.gasUsed` renamed to `ethereum.transaction.gasLimit` | +| 0.0.4 | Added `functionSignature` field to the Ethereum SmartContractCall object | +| 0.0.3 | Added `from` field to the Ethereum Call object
`etherem.call.address` renamed to `ethereum.call.to` | +| 0.0.2 | Added `input` field to the Ethereum Transaction object | ### Built-in Types diff --git a/pages/zh/developer/assemblyscript-migration-guide.mdx b/pages/zh/developer/assemblyscript-migration-guide.mdx index c63a1af95d7b..2db90a608110 100644 --- a/pages/zh/developer/assemblyscript-migration-guide.mdx +++ b/pages/zh/developer/assemblyscript-migration-guide.mdx @@ -127,11 +127,8 @@ ERROR TS2451: Cannot redeclare block-scoped variable 'a' ~~~~~~~~~~~~~ in assembly/index.ts(4,3) ``` - You'll need to rename your duplicate variables if you had variable shadowing. - ### Null Comparisons - By doing the upgrade on your subgraph, sometimes you might get errors like these: ```typescript @@ -140,7 +137,6 @@ ERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/BigInt | null' i ~~~~ in src/mappings/file.ts(41,21) ``` - To solve you can simply change the `if` statement to something like this: ```typescript @@ -285,7 +281,6 @@ ERROR TS2322: Type '~lib/string/String | null' is not assignable to type '~lib/s let somethingOrElse: string = container.data ? container.data : "else"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` - To fix this issue, you can create a variable for that property access so that the compiler can do the nullability check magic: ```typescript diff --git a/pages/zh/developer/create-subgraph-hosted.mdx b/pages/zh/developer/create-subgraph-hosted.mdx index 3b05b2548456..6b235e379634 100644 --- a/pages/zh/developer/create-subgraph-hosted.mdx +++ b/pages/zh/developer/create-subgraph-hosted.mdx @@ -218,15 +218,15 @@ Each entity must have an `id` field, which is of type `ID!` (string). The `id` f We support the following scalars in our GraphQL API: -| Type | Description | -| --- | --- | -| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | -| `ID` | Stored as a `string`. | -| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | -| `Boolean` | Scalar for `boolean` values. | -| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | -| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | -| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | +| Type | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Bytes` | Byte array, represented as a hexadecimal string. Commonly used for Ethereum hashes and addresses. | +| `ID` | Stored as a `string`. | +| `String` | Scalar for `string` values. Null characters are not supported and are automatically removed. | +| `Boolean` | Scalar for `boolean` values. | +| `Int` | The GraphQL spec defines `Int` to have size of 32 bytes. | +| `BigInt` | Large integers. Used for Ethereum's `uint32`, `int64`, `uint64`, ..., `uint256` types. Note: Everything below `uint32`, such as `int32`, `uint24` or `int8` is represented as `i32`. | +| `BigDecimal` | `BigDecimal` High precision decimals represented as a signficand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits. | #### Enums @@ -627,7 +627,7 @@ export function handleNewExchange(event: NewExchange): void { ``` > **Note:** A new data source will only process the calls and events for the block in which it was created and all following blocks, but will not process historical data, i.e., data that is contained in prior blocks. -> +> > If prior blocks contain data relevant to the new data source, it is best to index that data by reading the current state of the contract and creating entities representing that state at the time the new data source is created. ### Data Source Context @@ -684,7 +684,7 @@ dataSources: ``` > **Note:** The contract creation block can be quickly looked up on Etherscan: -> +> > 1. Search for the contract by entering its address in the search bar. > 2. Click on the creation transaction hash in the `Contract Creator` section. > 3. Load the transaction details page where you'll find the start block for that contract. diff --git a/pages/zh/developer/define-subgraph-hosted.mdx b/pages/zh/developer/define-subgraph-hosted.mdx index 92bf5bd8cd2f..17484f0deb7a 100644 --- a/pages/zh/developer/define-subgraph-hosted.mdx +++ b/pages/zh/developer/define-subgraph-hosted.mdx @@ -1,34 +1,34 @@ --- -title: Define a Subgraph +title: 定义子图 --- -A subgraph defines which data The Graph will index from Ethereum, and how it will store it. Once deployed, it will form a part of a global graph of blockchain data. +子图定义了Graph从以太坊索引哪些数据,以及如何存储这些数据。 子图一旦部署,就成为区块链数据全局图的一部分。 -![Define a Subgraph](/img/define-subgraph.png) +![定义子图](/img/define-subgraph.png) -The subgraph definition consists of a few files: +子图定义由几个文件组成: -- `subgraph.yaml`: a YAML file containing the subgraph manifest +- `subgraph.yaml`: 包含子图清单的 YAML 文件 -- `schema.graphql`: a GraphQL schema that defines what data is stored for your subgraph, and how to query it via GraphQL +- `schema.graphql`: 一个 GraphQL 模式文件,它定义了为您的子图存储哪些数据,以及如何通过 GraphQL 查询这些数据 -- `AssemblyScript Mappings`: [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) code that translates from the event data to the entities defined in your schema (e.g. `mapping.ts` in this tutorial) +- `AssemblyScript映射`: 将事件数据转换为模式中定义的实体(例如本教程中的`mapping.ts`)的 [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) 代码 -Before you go into detail about the contents of the manifest file, you need to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) which you will need to build and deploy a subgraph. +在详细了解清单文件的内容之前,您需要安装[Graph CLI](https://github.com/graphprotocol/graph-cli),以构建和部署子图。 -## Install the Graph CLI +## 安装Graph CLI -The Graph CLI is written in JavaScript, and you will need to install either `yarn` or `npm` to use it; it is assumed that you have yarn in what follows. +Graph CLI是使用 JavaScript 编写的,您需要安装`yarn`或 `npm`才能使用它;以下教程中假设您已经安装了yarn。 -Once you have `yarn`, install the Graph CLI by running +一旦您安装了`yarn`,可以通过运行以下命令安装 Graph CLI -**Install with yarn:** +**使用yarn安装:** ```bash yarn global add @graphprotocol/graph-cli ``` -**Install with npm:** +**使用npm安装:** ```bash npm install -g @graphprotocol/graph-cli diff --git a/pages/zh/developer/graphql-api.mdx b/pages/zh/developer/graphql-api.mdx index 65928d8734e0..f9cb6214fcd9 100644 --- a/pages/zh/developer/graphql-api.mdx +++ b/pages/zh/developer/graphql-api.mdx @@ -204,12 +204,12 @@ Fulltext search queries have one required field, `text`, for supplying search te Fulltext search operators: -| Symbol | Operator | Description | -| --- | --- | --- | -| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | -| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | -| `<->` | `Follow by` | Specify the distance between two words. | -| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | +| Symbol | Operator | Description | +| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `&` | `And` | For combining multiple search terms into a filter for entities that include all of the provided terms | +| | | `Or` | Queries with multiple search terms separated by the or operator will return all entities with a match from any of the provided terms | +| `<->` | `Follow by` | Specify the distance between two words. | +| `:*` | `Prefix` | Use the prefix search term to find words whose prefix match (2 characters required.) | #### Examples diff --git a/pages/zh/developer/quick-start.mdx b/pages/zh/developer/quick-start.mdx index 6893d424ddc2..5c07399604fd 100644 --- a/pages/zh/developer/quick-start.mdx +++ b/pages/zh/developer/quick-start.mdx @@ -9,7 +9,7 @@ This guide will quickly take you through how to initialize, create, and deploy y ## Subgraph Studio -### 1. Install the Graph CLI +### 1. 安装Graph CLI The Graph CLI is written in JavaScript and you will need to have either `npm` or `yarn` installed to use it. @@ -115,7 +115,7 @@ You can now query your subgraph by following [these instructions](/developer/que ## Hosted Service -### 1. Install the Graph CLI +### 1. 安装Graph CLI "The Graph CLI is an npm package and you will need `npm` or `yarn` installed to use it. diff --git a/pages/zh/explorer.mdx b/pages/zh/explorer.mdx index 7e68053f4b44..85698d600f9e 100644 --- a/pages/zh/explorer.mdx +++ b/pages/zh/explorer.mdx @@ -11,7 +11,7 @@ title: 浏览器 title="YouTube video player" frameBorder="0" allowFullScreen - > +> ## 子图 @@ -76,7 +76,7 @@ title: 浏览器 ![Explorer Image 6](/img/Curation-Overview.png) -If you want to learn more about the Curator role, you can do so by visiting the following links of [The Graph Academy](https://thegraph.academy/curators/) or [official documentation.](/curating) +如果你想了解更多关于策展人角色的信息,你可以通过访问 [The Graph Academy](https://thegraph.academy/curators/) 的以下链接或[官方文档](/curating)来实现。 ### 3. 委托人 @@ -178,7 +178,7 @@ If you want to learn more about the Curator role, you can do so by visiting the 在页面的后半部分,您将看到委托标签。 在这里,您可以看到您委托给的索引人,以及它们的详细信息(例如奖励削减、冷却时间等)。 -With the buttons on the right side of the table, you can manage your delegation - delegate more, undelegate, or withdraw your delegation after the thawing period. +通过表格右侧的按钮,你可以管理你的委托--更多的委托,取消委托,或在解冻期后撤回你的委托。 使用表格右侧的按钮,您可以管理您的委托——在解冻期后增加委托、取消委托或撤回委托。 diff --git a/pages/zh/hosted-service/deploy-subgraph-hosted.mdx b/pages/zh/hosted-service/deploy-subgraph-hosted.mdx index bdc532e205e4..5fe5ccacae0e 100644 --- a/pages/zh/hosted-service/deploy-subgraph-hosted.mdx +++ b/pages/zh/hosted-service/deploy-subgraph-hosted.mdx @@ -1,56 +1,56 @@ --- -title: Deploy a Subgraph to the Hosted Service +title: 将子图部署到托管服务上 --- -If you have not checked out already, check out how to write the files that make up a [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) and how to install the [Graph CLI](https://github.com/graphprotocol/graph-cli) to generate code for your subgraph. Now, it's time to deploy your subgraph to the Hosted Service, also known as the Hosted Service. +如果您尚未查看,请先查看如何编写组成 [子图清单](/developer/create-subgraph-hosted#the-subgraph-manifest) 的文件以及如何安装 [Graph CLI](https://github.com/graphprotocol/graph-cli) 为您的子图生成代码。 现在,让我们将您的子图部署到托管服务上。 -## Create a Hosted Service account +## 创建托管服务帐户 -Before using the Hosted Service, create an account in our Hosted Service. You will need a [Github](https://github.com/) account for that; if you don't have one, you need to create that first. Then, navigate to the [Hosted Service](https://thegraph.com/hosted-service/), click on the _'Sign up with Github'_ button and complete Github's authorization flow. +在使用托管服务之前,请先在我们的托管服务中创建一个帐户。 为此,您将需要一个 [Github](https://github.com/) 帐户;如果您还没有,您需要先创建一个账户。 然后,导航到 [托管服务](https://thegraph.com/hosted-service/), 单击 _'使用 Github 注册'_ 按钮并完成 Github 的授权流程。 -## Store the Access Token +## 存储访问令牌 -After creating an account, navigate to your [dashboard](https://thegraph.com/hosted-service/dashboard). Copy the access token displayed on the dashboard and run `graph auth --product hosted-service `. This will store the access token on your computer. You only need to do this once, or if you ever regenerate the access token. +创建帐户后,导航到您的 [仪表板](https://thegraph.com/hosted-service/dashboard)。 复制仪表板上显示的访问令牌并运行 `graph auth --product hosted-service `。 这会将访问令牌存储在您的计算机上。 如果您不需要重新生成访问令牌,您就只需要这样做一次。 -## Create a Subgraph on the Hosted Service +## 在托管服务上创建子图 -Before deploying the subgraph, you need to create it in The Graph Explorer. Go to the [dashboard](https://thegraph.com/hosted-service/dashboard) and click on the _'Add Subgraph'_ button and fill in the information below as appropriate: +在部署子图之前,您需要在 The Graph Explorer 中创建它。 转到 [仪表板](https://thegraph.com/hosted-service/dashboard) ,单击 _'添加子图'_ 按钮,并根据需要填写以下信息: -**Image** - Select an image to be used as a preview image and thumbnail for the subgraph. +**图像** - 选择要用作子图的预览图和缩略图的图像。 -**Subgraph Name** - Together with the account name that the subgraph is created under, this will also define the `account-name/subgraph-name`-style name used for deployments and GraphQL endpoints. _This field cannot be changed later._ +**子图名称** - 子图名称连同下面将要创建的子图帐户名称,将定义用于部署和 GraphQL 端点的`account-name/subgraph-name`样式名称。 _此字段以后无法更改。_ -**Account** - The account that the subgraph is created under. This can be the account of an individual or organization. _Subgraphs cannot be moved between accounts later._ +**帐户** - 创建子图的帐户。 这可以是个人或组织的帐户。 _以后不能在帐户之间移动子图。_ -**Subtitle** - Text that will appear in subgraph cards. +**副标题** - 将出现在子图卡中的文本。 -**Description** - Description of the subgraph, visible on the subgraph details page. +**描述** - 子图的描述,在子图详细信息页面上可见。 -**GitHub URL** - Link to the subgraph repository on GitHub. +**GitHub URL** - 存储在GitHub 上的子图代码的链接。 -**Hide** - Switching this on hides the subgraph in the Graph Explorer. +**隐藏** - 打开此选项可隐藏Graph Explorer中的子图。 -After saving the new subgraph, you are shown a screen with help on how to install the Graph CLI, how to generate the scaffolding for a new subgraph, and how to deploy your subgraph. The first two steps were covered in the [Define a Subgraph section](/developer/define-subgraph-hosted). +保存新子图后,您会看到一个屏幕,其中包含有关如何安装 Graph CLI、如何为新子图生成脚手架以及如何部署子图的帮助信息。 前面两部分在[定义子图](/developer/define-subgraph-hosted)中进行了介绍。 -## Deploy a Subgraph on the Hosted Service +## 在托管服务上部署子图 -Deploying your subgraph will upload the subgraph files that you've built with `yarn build` to IPFS and tell the Graph Explorer to start indexing your subgraph using these files. +一旦部署您的子图,您使用`yarn build` 命令构建的子图文件将被上传到 IPFS,并告诉 Graph Explorer 开始使用这些文件索引您的子图。 -You deploy the subgraph by running `yarn deploy` +您可以通过运行 `yarn deploy`来部署子图。 -After deploying the subgraph, the Graph Explorer will switch to showing the synchronization status of your subgraph. Depending on the amount of data and the number of events that need to be extracted from historical Ethereum blocks, starting with the genesis block, syncing can take from a few minutes to several hours. The subgraph status switches to `Synced` once the Graph Node has extracted all data from historical blocks. The Graph Node will continue inspecting Ethereum blocks for your subgraph as these blocks are mined. +部署子图后,Graph Explorer将切换到显示子图的同步状态。 根据需要从历史以太坊区块中提取的数据量和事件数量的不同,从创世区块开始,同步操作可能需要几分钟到几个小时。 一旦 Graph节点从历史区块中提取了所有数据,子图状态就会切换到`Synced`。 当新的以太坊区块出现时,Graph节点将继续按照子图的要求检查这些区块的信息。 -## Redeploying a Subgraph +## 重新部署子图 -When making changes to your subgraph definition, for example to fix a problem in the entity mappings, run the `yarn deploy` command above again to deploy the updated version of your subgraph. Any update of a subgraph requires that Graph Node reindexes your entire subgraph, again starting with the genesis block. +更改子图定义后,例如:修复实体映射中的一个问题,再次运行上面的 `yarn deploy` 命令可以部署新版本的子图。 子图的任何更新都需要Graph节点再次从创世块开始重新索引您的整个子图。 -If your previously deployed subgraph is still in status `Syncing`, it will be immediately replaced with the newly deployed version. If the previously deployed subgraph is already fully synced, Graph Node will mark the newly deployed version as the `Pending Version`, sync it in the background, and only replace the currently deployed version with the new one once syncing the new version has finished. This ensures that you have a subgraph to work with while the new version is syncing. +如果您之前部署的子图仍处于`Syncing`状态,系统则会立即将其替换为新部署的版本。 如果之前部署的子图已经完全同步,Graph节点会将新部署的版本标记为`Pending Version`,在后台进行同步,只有在新版本同步完成后,才会用新的版本替换当前部署的版本。 这样做可以确保在新版本同步时您仍然有子图可以使用。 -### Deploying the subgraph to multiple Ethereum networks +### 将子图部署到多个以太坊网络 -In some cases, you will want to deploy the same subgraph to multiple Ethereum networks without duplicating all of its code. The main challenge that comes with this is that the contract addresses on these networks are different. One solution that allows to parameterize aspects like contract addresses is to generate parts of it using a templating system like [Mustache](https://mustache.github.io/) or [Handlebars](https://handlebarsjs.com/). +在某些情况下,您可能希望将相同的子图部署到多个以太坊网络,而无需复制其所有代码。 这样做的主要挑战是这些网络上的合约地址不同。 允许参数化合约地址等配置的一种解决方案是使用 [Mustache](https://mustache.github.io/)或 [Handlebars](https://handlebarsjs.com/)等模板系统。 -To illustrate this approach, let's assume a subgraph should be deployed to mainnet and Ropsten using different contract addresses. You could then define two config files providing the addresses for each network: +为了说明这种方法,我们假设使用不同的合约地址将子图部署到主网和 Ropsten上。 您可以定义两个配置文件,为每个网络提供相应的地址: ```json { @@ -59,7 +59,7 @@ To illustrate this approach, let's assume a subgraph should be deployed to mainn } ``` -and +和 ```json { @@ -68,7 +68,7 @@ and } ``` -Along with that, you would substitute the network name and addresses in the manifest with variable placeholders `{{network}}` and `{{address}}` and rename the manifest to e.g. `subgraph.template.yaml`: +除此之外,您可以用变量占位符 `{{network}}` 和 `{{address}}` 替换清单中的网络名称和地址,并将清单重命名为例如 `subgraph.template.yaml`: ```yaml # ... @@ -85,7 +85,7 @@ dataSources: kind: ethereum/events ``` -In order generate a manifest to either network, you could add two additional commands to `package.json` along with a dependency on `mustache`: +为了给每个网络生成清单,您可以向 `package.json` 添加两个附加命令,以及对 `mustache` 的依赖项: ```json { @@ -102,7 +102,7 @@ In order generate a manifest to either network, you could add two additional com } ``` -To deploy this subgraph for mainnet or Ropsten you would now simply run one of the two following commands: +要为主网或 Ropsten 部署此子图,您现在只需运行以下两个命令中的任意一个: ```sh # Mainnet: @@ -112,15 +112,15 @@ yarn prepare:mainnet && yarn deploy yarn prepare:ropsten && yarn deploy ``` -A working example of this can be found [here](https://github.com/graphprotocol/example-subgraph/tree/371232cf68e6d814facf5e5413ad0fef65144759). +您可以在[这里](https://github.com/graphprotocol/example-subgraph/tree/371232cf68e6d814facf5e5413ad0fef65144759)找到一个工作示例。 -**Note:** This approach can also be applied more complex situations, where it is necessary to substitute more than contract addresses and network names or where generating mappings or ABIs from templates as well. +**注意:** 这种方法也可以应用在更复杂的情况下,例如:需要替换的不仅仅是合约地址和网络名称,或者还需要从模板生成映射或 ABI。 -## Checking subgraph health +## 检查子图状态 -If a subgraph syncs successfully, that is a good sign that it will continue to run well forever. However, new triggers on the chain might cause your subgraph to hit an untested error condition or it may start to fall behind due to performance issues or issues with the node operators. +如果子图成功同步,这是表明它将运行良好的一个好的信号。 但是,链上的新事件可能会导致您的子图遇到未经测试的错误环境,或者由于性能或节点方面的问题而开始落后于链上数据。 -Graph Node exposes a graphql endpoint which you can query to check the status of your subgraph. On the Hosted Service, it is available at `https://api.thegraph.com/index-node/graphql`. On a local node it is available on port `8030/graphql` by default. The full schema for this endpoint can be found [here](https://github.com/graphprotocol/graph-node/blob/master/server/index-node/src/schema.graphql). Here is an example query that checks the status of the current version of a subgraph: +Graph 节点公开了一个 graphql 端点,您可以通过查询该端点来检查子图的状态。 在托管服务上,该端点的链接是 `https://api.thegraph.com/index-node/graphql`。 在本地节点上,默认情况下该端点在端口 `8030/graphql` 上可用。 该端点的完整数据模式可以在[此处](https://github.com/graphprotocol/graph-node/blob/master/server/index-node/src/schema.graphql)找到。 这是一个检查子图当前版本状态的示例查询: ```graphql { @@ -147,14 +147,14 @@ Graph Node exposes a graphql endpoint which you can query to check the status of } ``` -This will give you the `chainHeadBlock` which you can compare with the `latestBlock` on your subgraph to check if it is running behind. `synced` informs if the subgraph has ever caught up to the chain. `health` can currently take the values of `healthy` if no errors ocurred, or `failed` if there was an error which halted the progress of the subgraph. In this case you can check the `fatalError` field for details on this error. +这将为您提供 `chainHeadBlock`,您可以将其与子图上的 `latestBlock` 进行比较,以检查子图是否落后。 通过`synced`,可以了解子图是否与链上数据完全同步。 如果子图没有发生错误,`health` 将返回`healthy`,如果有一个错误导致子图的同步进度停止,那么 `health`将返回`failed` 。 在这种情况下,您可以检查 `fatalError` 字段以获取有关此错误的详细信息。 -## Subgraph archive policy +## 子图归档策略 -The Hosted Service is a free Graph Node indexer. Developers can deploy subgraphs indexing a range of networks, which will be indexed, and made available to query via graphQL. +托管服务是一个免费的Graph节点索引器。 开发人员可以部署索引一系列网络的子图,这些网络将被索引,并可以通过 graphQL 进行查询。 -To improve the performance of the service for active subgraphs, the Hosted Service will archive subgraphs which are inactive. +为了提高活跃子图的服务性能,托管服务将归档不活跃的子图。 -**A subgraph is defined as "inactive" if it was deployed to the Hosted Service more than 45 days ago, and if it has received 0 queries in the last 30 days.** +**如果一个子图在 45 天前部署到托管服务,并且在过去 30 天内收到 0 个查询,则将其定义为“不活跃”。** -Developers will be notified by email if one of their subgraphs has been marked as inactive 7 days before it is removed. If they wish to "activate" their subgraph, they can do so by making a query in their subgraph's Hosted Service graphQL playground. Developers can always redeploy an archived subgraph if it is required again. +如果开发人员的一个子图被标记为不活跃,并将 7 天后被删除,托管服务会通过电子邮件通知开发者。 如果他们希望“激活”他们的子图,他们可以通过在其子图的托管服务 graphQL playground中发起查询来实现。 如果再次需要使用这个子图,开发人员也可以随时重新部署存档的子图。 diff --git a/pages/zh/hosted-service/migrating-subgraph.mdx b/pages/zh/hosted-service/migrating-subgraph.mdx index 9d3c26f43caa..979d684faeed 100644 --- a/pages/zh/hosted-service/migrating-subgraph.mdx +++ b/pages/zh/hosted-service/migrating-subgraph.mdx @@ -2,7 +2,7 @@ title: Migrating an Existing Subgraph to The Graph Network --- -## Introduction +## 介绍 This is a guide for the migration of subgraphs from the Hosted Service (also known as 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. @@ -142,7 +142,7 @@ If you're still confused, fear not! Check out the following resources or watch o title="YouTube video player" frameBorder="0" allowFullScreen - > +> - [The Graph Network Contracts](https://github.com/graphprotocol/contracts) diff --git a/pages/zh/hosted-service/query-hosted-service.mdx b/pages/zh/hosted-service/query-hosted-service.mdx index 731e3a3120b2..ad41c4bede90 100644 --- a/pages/zh/hosted-service/query-hosted-service.mdx +++ b/pages/zh/hosted-service/query-hosted-service.mdx @@ -1,14 +1,14 @@ --- -title: Query the Hosted Service +title: 查询托管服务 --- -With the subgraph deployed, visit the [Hosted Service](https://thegraph.com/hosted-service/) to open up a [GraphiQL](https://github.com/graphql/graphiql) interface where you can explore the deployed GraphQL API for the subgraph by issuing queries and viewing the schema. +部署子图后,请访问[托管服务](https://thegraph.com/hosted-service/) 以打开 [GraphiQL](https://github.com/graphql/graphiql) 界面,您可以在其中通过发出查询和查看数据模式来探索已经部署的子图的 GraphQL API。 -An example is provided below, but please see the [Query API](/developer/graphql-api) for a complete reference on how to query the subgraph's entities. +下面提供了一个示例,但请参阅 [查询 API ](/developer/graphql-api) 以获取有关如何查询子图实体的完整参考。 -#### Example +#### 示例 -This query lists all the counters our mapping has created. Since we only create one, the result will only contain our one `default-counter`: +此查询列出了我们的映射创建的所有计数器。 由于我们只创建一个,结果将只包含我们的一个 `默认计数器`: ```graphql { @@ -19,10 +19,10 @@ This query lists all the counters our mapping has created. Since we only create } ``` -## Using The Hosted Service +## 使用托管服务 -The Graph Explorer and its GraphQL playground is a useful way to explore and query deployed subgraphs on the Hosted Service. +Graph Explorer 及其 GraphQL playground是探索和查询托管服务上部署的子图的有用方式。 -Some of the main features are detailed below: +下面详细介绍了一些主要功能: -![Explorer Playground](/img/explorer-playground.png) +![探索Playground](/img/explorer-playground.png) diff --git a/pages/zh/hosted-service/what-is-hosted-service.mdx b/pages/zh/hosted-service/what-is-hosted-service.mdx index 7f604c8dc31a..24d7068c1b44 100644 --- a/pages/zh/hosted-service/what-is-hosted-service.mdx +++ b/pages/zh/hosted-service/what-is-hosted-service.mdx @@ -1,8 +1,8 @@ --- -title: What is the Hosted Service? +title: 什么是托管服务? --- -This section will walk you through deploying a subgraph to the Hosted Service, otherwise known as the [Hosted Service.](https://thegraph.com/hosted-service/) As a reminder, the Hosted Service will not be shut down soon. We will gradually sunset the Hosted Service once we reach feature parity with the decentralized network. Your subgraphs deployed on the Hosted Service are still available [here.](https://thegraph.com/hosted-service/) +本节将引导您将子图部署到 [托管服务](https://thegraph.com/hosted-service/) 提醒一下,托管服务不会很快关闭。 一旦去中心化网络达到托管服务相当的功能,我们将逐步取消托管服务。 您在托管服务上部署的子图在[此处](https://thegraph.com/hosted-service/)仍然可用。 If you don't have an account on the Hosted Service, you can signup with your Github account. Once you authenticate, you can start creating subgraphs through the UI and deploying them from your terminal. Graph Node supports a number of Ethereum testnets (Rinkeby, Ropsten, Kovan) in addition to mainnet. @@ -42,9 +42,9 @@ graph init --from-example --product hosted-service / The example subgraph is based on the Gravity contract by Dani Grant that manages user avatars and emits `NewGravatar` or `UpdateGravatar` events whenever avatars are created or updated. The subgraph handles these events by writing `Gravatar` entities to the Graph Node store and ensuring these are updated according to the events. Continue on to the [subgraph manifest](/developer/create-subgraph-hosted#the-subgraph-manifest) to better understand which events from your smart contracts to pay attention to, mappings, and more. -## Supported Networks on the Hosted Service +## 托管服务支持的网络 -Please note that the following networks are supported on the Hosted Service. Networks outside of Ethereum mainnet ('mainnet') are not currently supported on [The Graph Explorer.](https://thegraph.com/explorer) +请注意托管服务支持以下网络。 [Graph Explorer](https://thegraph.com/explorer)目前不支持以太坊主网(“主网”)之外的网络。 - `mainnet` - `kovan` diff --git a/pages/zh/indexing.mdx b/pages/zh/indexing.mdx index a43cd6077f88..5a3f24a80d4e 100644 --- a/pages/zh/indexing.mdx +++ b/pages/zh/indexing.mdx @@ -26,7 +26,7 @@ import { Difficulty } from '@/components' ### 奖励如何分配? -索引奖励来自协议通胀,每年发行量设定为 3%。 它们根据每个子图上所有策展信号的比例分布在子图上,然后根据他们在该子图上分配的股份按比例分配给索引人。 **An allocation must be closed with a valid proof of indexing (POI) that meets the standards set by the arbitration charter in order to be eligible for rewards.** +索引奖励来自协议通胀,每年发行量设定为 3%。 它们根据每个子图上所有策展信号的比例分布在子图上,然后根据他们在该子图上分配的股份按比例分配给索引人。 **一项分配必须以符合仲裁章程规定的标准的有效索引证明(POI)来结束,才有资格获得奖励。** 社区创建了许多用于计算奖励的工具,您会在 [“社区指南”集合](https://www.notion.so/Community-Guides-abbb10f4dba040d5ba81648ca093e70c)中找到它们。 您还可以在 [Discord 服务器](https://discord.gg/vtvv7FP)上的 #delegators 和 #indexers 频道 ​​ 中找到最新的工具列表。 @@ -60,7 +60,7 @@ query indexerAllocations { } ``` -Use Etherscan to call `getRewards()`: +使用Etherscan调用 `getRewards()`: - 导航到[奖励合约的 Etherscan 界面](https://etherscan.io/address/0x9Ac758AB77733b4150A901ebd659cbF8cB93ED66#readProxyContract) @@ -79,7 +79,7 @@ Use Etherscan to call `getRewards()`: - 如果以平局方式解决争议,渔夫的押金将被退还,并且争议的索引人不会被削减。 - 如果争议被接受,渔夫存入的 GRT 将被退回,有争议的 索引人将被削减,渔夫将获得被削减的 GRT 的 50%。 -Disputes can be viewed in the UI in an Indexer's profile page under the `Disputes` tab. +争议可以在用户界面中的 `争议 `标签下的索引人档案页中查看。 ### 什么是查询费奖励? 何时发放? @@ -114,12 +114,12 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute - **中型** - 生产型索引人支持 100 个子图和每秒 200-500 个请求。 - **大型** -准备对当前使用的所有子图进行索引,并为相关流量的请求提供服务 -| Setup | (CPU 数量) | (内存 GB) | (硬盘 TB) | (CPU 数量) | (内存 GB) | -| ----- | :--------: | :-------: | :-------: | :--------: | :-------: | -| 小型 | 4 | 8 | 1 | 4 | 16 | -| 标准 | 8 | 30 | 1 | 12 | 48 | -| 中型 | 16 | 64 | 2 | 32 | 64 | -| 大型 | 72 | 468 | 3.5 | 48 | 184 | +| 类型 | (CPU 数量) | (内存 GB) | (硬盘 TB) | (CPU 数量) | (内存 GB) | +| -- |:--------:|:-------:|:-------:|:--------:|:-------:| +| 小型 | 4 | 8 | 1 | 4 | 16 | +| 标准 | 8 | 30 | 1 | 12 | 48 | +| 中型 | 16 | 64 | 2 | 32 | 64 | +| 大型 | 72 | 468 | 3.5 | 48 | 184 | ### 索引人应该采取哪些基本的安全防范措施? @@ -129,13 +129,13 @@ Disputes can be viewed in the UI in an Indexer's profile page under the `Dispute ## 基础设施 -At the center of an indexer's infrastructure is the Graph Node which monitors Ethereum, extracts and loads data per a subgraph definition and serves it as a [GraphQL API](/about/introduction#how-the-graph-works). The Graph Node needs to be connected to Ethereum EVM node endpoints, and IPFS node for sourcing data; a PostgreSQL database for its store; and indexer components which facilitate its interactions with the network. +索引人基础设施的中心是Graph节点,它监控以太坊,根据子图定义提取和加载数据,并将其作为[GraphQL API](/about/introduction#how-the-graph-works)提供。 The Graph节点需要连接到以太坊EVM节点端点,以及用于获取数据的IPFS节点;一个用于存储的PostgreSQL数据库;以及促进其与网络互动的索引人组件。 - **PostgreSQL 数据库** - Graph 节点的主要存储,这是存储子图数据的地方。 索引人服务和代理也使用数据库来存储状态通道数据、成本模型和索引规则。 - **Ethereum endpoint** -公开 Ethereum JSON-RPC API 的端点。 这可能采取单个 Ethereum 客户端的形式,也可能是一个更复杂的设置,在多个客户端之间进行负载平衡。 需要注意的是,某些子图将需要特定的 Ethereum 客户端功能,如存档模式和跟踪 API。 -- ** IPFS 节点(版本小于 5)** - 子图部署元数据存储在 IPFS 网络上。 The Graph Node primarily accesses the IPFS node during subgraph deployment to fetch the subgraph manifest and all linked files. Network indexers do not need to host their own IPFS node, an IPFS node for the network is hosted at https://ipfs.network.thegraph.com. +- ** IPFS 节点(版本小于 5)** - 子图部署元数据存储在 IPFS 网络上。 The Graph节点在子图部署期间主要访问IPFS节点,以获取子图清单和所有链接文件。 网络索引人不需要托管自己的IPFS节点,网络的IPFS节点是托管在https://ipfs.network.thegraph.com。 - **索引人服务** -处理与网络的所有必要的外部通信。 共享成本模型和索引状态,将来自网关的查询请求传递给一个 Graph 节点,并通过状态通道与网关管理查询支付。 @@ -149,26 +149,26 @@ At the center of an indexer's infrastructure is the Graph Node which monitors Et #### Graph 节点 -| 端口 | Purpose | 路径 | CLI Argument | 环境 变量 | -| --- | --- | --- | --- | --- | -| 8000 | GraphQL HTTP 服务
(用于子图查询) | /subgraphs/id/...

/subgraphs/name/.../... | --http-port | - | -| 8001 | GraphQL WS
(用于子图订阅) | /subgraphs/id/...

/subgraphs/name/.../... | --ws-port | - | -| 8020 | JSON-RPC
(用于管理部署) | / | --admin-port | - | -| 8030 | 子图索引状态 API | /graphql | --index-node-port | - | -| 8040 | Prometheus 指标 | /metrics | --metrics-port | - | +| 端口 | 用途 | 路径 | CLI参数 | 环境 变量 | +| ---- | ------------------------------------ | ------------------------------------------------------------------- | ----------------- | ----- | +| 8000 | GraphQL HTTP 服务
(用于子图查询) | /subgraphs/id/...

/subgraphs/name/.../... | --http-port | - | +| 8001 | GraphQL WS
(用于子图订阅) | /subgraphs/id/...

/subgraphs/name/.../... | --ws-port | - | +| 8020 | JSON-RPC
(用于管理部署) | / | --admin-port | - | +| 8030 | 子图索引状态 API | /graphql | --index-node-port | - | +| 8040 | Prometheus 指标 | /metrics | --metrics-port | - | #### 索引人服务 -| 端口 | Purpose | 路径 | CLI Argument | 环境 变量 | -| --- | --- | --- | --- | --- | -| 7600 | GraphQL HTTP 服务
(用于付费子图查询) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | -| 7300 | Prometheus 指标 | /metrics | --metrics-port | - | +| 端口 | 用途 | 路径 | CLI参数 | 环境 变量 | +| ---- | -------------------------------------- | --------------------------------------------------------------------------- | -------------- | ---------------------- | +| 7600 | GraphQL HTTP 服务
(用于付费子图查询) | /subgraphs/id/...
/status
/channel-messages-inbox | --port | `INDEXER_SERVICE_PORT` | +| 7300 | Prometheus 指标 | /metrics | --metrics-port | - | #### 索引人代理 -| 端口 | Purpose | 路径 | CLI Argument | 环境
变量 | -| ---- | -------------- | ---- | ------------------------- | --------------------------------------- | -| 8000 | 索引人管理 API | / | --indexer-management-port | `INDEXER_AGENT_INDEXER_MANAGEMENT_PORT` | +| 端口 | 用途 | 路径 | CLI参数 | 环境
变量 | +| ---- | --------- | -- | ------------------------- | --------------------------------------- | +| 8000 | 索引人管理 API | / | --indexer-management-port | `INDEXER_AGENT_INDEXER_MANAGEMENT_PORT` | ### Google Cloud 上使用 Terraform 建立基础架构 @@ -291,7 +291,7 @@ kubectl config use-context $(kubectl config get-contexts --output='name' - 读取`$dir`中的所有文件,并按照注释中的指示调整任何值。 -Deploy all resources with `kubectl apply -k $dir`. +用以下方法部署所有资源`kubectl apply -k $dir`. ### Graph 节点 @@ -313,7 +313,7 @@ Deploy all resources with `kubectl apply -k $dir`. sudo apt-get install -y clang libpg-dev libssl-dev pkg-config ``` -#### Setup +#### 类型 1. 启动 PostgreSQL 数据库服务器 @@ -340,7 +340,7 @@ cargo run -p graph-node --release -- \ - **Ethereum 节点** - 默认情况下,docker 编译设置将使用 mainnet:[http://host.docker.internal:8545](http://host.docker.internal:8545) 连接到主机上的 Ethereum 节点。 你可以通过更新 `docker-compose.yaml`来替换这个网络名和 url。 -#### Setup +#### 安装 1. 克隆 Graph 节点并导航到 Docker 目录。 @@ -373,7 +373,7 @@ docker-compose up #### 开始 -索引人代理和索引人服务应该与你的 Graph 节点基础架构共同定位。 有很多方法可以为你的索引人组件设置虚拟执行环境,这里我们将解释如何使用 NPM 包或源码在裸机上运行它们,或者通过谷歌云 Kubernetes 引擎上的 kubernetes 和 docker 运行。 If these setup examples do not translate well to your infrastructure there will likely be a community guide to reference, come say hi on [Discord](https://thegraph.com/discord)! Remember to [stake in the protocol](/indexing#stake-in-the-protocol) before starting up your indexer components! +索引人代理和索引人服务应该与你的 Graph 节点基础架构共同定位。 有很多方法可以为你的索引人组件设置虚拟执行环境,这里我们将解释如何使用 NPM 包或源码在裸机上运行它们,或者通过谷歌云 Kubernetes 引擎上的 kubernetes 和 docker 运行。 如果这些设置实例不能很好地转化为你的基础设施,很可能会有一个社区指南供参考,请到[Discord](https://thegraph.com/discord)上打招呼。 在启动你的索引人组件之前,请记住[在协议中签名](/indexing#stake-in-the-protocol)! #### 来自 NPM 包 @@ -391,24 +391,6 @@ graph-indexer-service start ... # Indexer agent graph-indexer-agent start ... -# Indexer CLI -#Forward the port of your agent pod if using Kubernetes -kubectl port-forward pod/POD_ID 18000:8000 -graph indexer connect http://localhost:18000/ -graph indexer ... - -# Indexer agent -graph-indexer-agent start ... - -# Indexer CLI -#Forward the port of your agent pod if using Kubernetes -kubectl port-forward pod/POD_ID 18000:8000 -graph indexer connect http://localhost:18000/ -graph indexer ... - -# Indexer agent -graph-indexer-agent start ... - # Indexer CLI #Forward the port of your agent pod if using Kubernetes kubectl port-forward pod/POD_ID 18000:8000 @@ -430,46 +412,6 @@ cd packages/indexer-service cd packages/indexer-agent ./bin/graph-indexer-service start ... -# From Repo root directory -yarn - -# Indexer Service -cd packages/indexer-service -./bin/graph-indexer-service start ... - -# Indexer agent -cd packages/indexer-agent -./bin/graph-indexer-service start ... - -# Indexer CLI -cd packages/indexer-cli -./bin/graph-indexer-cli indexer connect http://localhost:18000/ -./bin/graph-indexer-cli indexer ... - -# Indexer agent -cd packages/indexer-agent -./bin/graph-indexer-service start ... - -# From Repo root directory -yarn - -# Indexer Service -cd packages/indexer-service -./bin/graph-indexer-service start ... - -# Indexer agent -cd packages/indexer-agent -./bin/graph-indexer-service start ... - -# Indexer CLI -cd packages/indexer-cli -./bin/graph-indexer-cli indexer connect http://localhost:18000/ -./bin/graph-indexer-cli indexer ... - -# Indexer agent -cd packages/indexer-agent -./bin/graph-indexer-service start ... - # Indexer CLI cd packages/indexer-cli ./bin/graph-indexer-cli indexer connect http://localhost:18000/ @@ -505,9 +447,6 @@ docker build \ ```sh docker run -p 7600:7600 -it indexer-service:latest ... docker run -p 18000:8000 -it indexer-agent:latest ... -docker run -p 18000:8000 -it indexer-agent:latest ... -docker run -p 18000:8000 -it indexer-agent:latest ... -docker run -p 18000:8000 -it indexer-agent:latest ... ``` 请参阅 [在 Google Cloud 上使用 Terraform 设置服务器基础架构](/indexing#setup-server-infrastructure-using-terraform-on-google-cloud) 一节。 @@ -576,7 +515,7 @@ graph-indexer-service start \ #### 索引人 CLI -The Indexer CLI is a plugin for [`@graphprotocol/graph-cli`](https://www.npmjs.com/package/@graphprotocol/graph-cli) accessible in the terminal at `graph indexer`. +Indexer CLI是一个可以在终端访问`graph indexer`的插件,地址是[`@graphprotocol/graph-cli`](https://www.npmjs.com/package/@graphprotocol/graph-cli)。 ```sh graph indexer connect http://localhost:18000 @@ -585,7 +524,7 @@ graph indexer status #### 使用索引人 CLI 管理索引人 -索引人代理需要来自索引人的输入,才能代表索引人自主地与网络交互。 定义索引人代理行为的机制是**索引规则**. 使用**索引规则**,索引人可以应用其特定的策略来选择子图进行索引和服务查询。 Using **indexing rules** an indexer can apply their specific strategy for picking subgraphs to index and serve queries for. 规则是通过由代理提供的 GraphQL API 来管理的,被称为索引人管理 API。 规则是通过由代理提供的 GraphQL API 来管理的,被称为索引人管理 API。 与**索引管理 API**交互的建议工具是 **索引人 CLI** ,它是 **Graph CLI**的扩展。 +索引人代理需要来自索引人的输入,才能代表索引人自主地与网络交互。 定义索引人代理行为的机制是**索引规则**. 使用**索引规则**,索引人可以应用其特定的策略来选择子图进行索引和服务查询。 使用**索引规则** ,索引人可以应用他们特定的策略来挑选子图,为其建立索引和提供查询。 规则是通过由代理提供的 GraphQL API 来管理的,被称为索引人管理 API。 与**索引管理 API**交互的建议工具是 **索引人 CLI** ,它是 **Graph CLI**的扩展。 #### 使用方法 @@ -659,7 +598,7 @@ default => 0.1 * $SYSTEM_LOAD; 成本模型示例: -| 询问 | 价格 | +| 询问 | 价格 | | ---------------------------------------------------------------------------- | ------- | | { pairs(skip: 5000) { id } } | 0.5 GRT | | { tokens { symbol } } | 0.1 GRT | diff --git a/pages/zh/studio/billing.mdx b/pages/zh/studio/billing.mdx index c29dc6b4454e..ce99acd65775 100644 --- a/pages/zh/studio/billing.mdx +++ b/pages/zh/studio/billing.mdx @@ -1,43 +1,43 @@ --- -title: Billing on the Subgraph Studio +title: 子图工作室的计费 --- -### Overview +### 概述 -Invoices are statements of payment amounts owed by a customer and are typically generated on a weekly basis in the system. You’ll be required to pay fees based on the query fees you generate using your API keys. The billing contract lives on the [Polygon](https://polygon.technology/) network. It’ll allow you to: +发票是客户所欠付款金额的报表,通常在系统中每周生成一次。 你需要根据你使用API密钥产生的查询费用来支付费用。 账单合同在[Polygon](https://polygon.technology/)网络上。 它将允许你: -- Add and remove GRT -- Keep track of your balances based on how much GRT you have added to your account, how much you have removed, and your invoices -- Automatically clear payments based on query fees generated +- 添加和移除GRT +- 根据你向你的账户添加了多少GRT,你移除了多少,以及你的发票来跟踪你的余额。 +- 根据产生的查询费用自动结算付款 -In order to add GRT to your account, you will need to go through the following steps: +为了将GRT添加到你的账户中,你将需要通过以下步骤: -1. Purchase GRT and ETH on an exchange of your choice -2. Send the GRT and ETH to your wallet -3. Bridge GRT to Polygon using the UI +1. 在您选择的交易所购买GRT和ETH +2. 将GRT和ETH发送到你的钱包里 +3. 使用用户界面桥接GRT到Polygon - a) You will receive 0.001 Matic in a few minutes after you send any amount of GRT to the Polygon bridge. You can track the transaction on [Polygonscan](https://polygonscan.com/) by inputting your address into the search bar. + a) 在你向Polygon桥发送任何数量的GRT后,你将在几分钟内收到0.001 Matic。 你可以在搜索栏中输入你的地址,在 [Polygonscan](https://polygonscan.com/)上跟踪交易情况。 -4. Add bridged GRT to the billing contract on Polygon. The billing contract address is: [0x10829DB618E6F520Fa3A01c75bC6dDf8722fA9fE](https://polygonscan.com/address/0x10829DB618E6F520Fa3A01c75bC6dDf8722fA9fE). +4. 在Polygon的计费合同中加入桥接的GRT。 计费合同地址是:[0x10829DB618E6F520Fa3A01c75bC6dDf8722fA9fE](https://polygonscan.com/address/0x10829DB618E6F520Fa3A01c75bC6dDf8722fA9fE). - a) In order to complete step #4, you'll need to switch your network in your wallet to Polygon. You can add Polygon's network by connecting your wallet and clicking on "Choose Matic (Polygon) Mainnet" [here.](https://chainlist.org/) Once you've added the network, switch it over in your wallet by navigating to the network pill on the top right hand side corner. In Metamask, the network is called **Matic Mainnnet.** + a) 为了完成第4步,你需要将钱包中的网络切换到Polygon。 你可以通过连接你的钱包并点击[这里](https://chainlist.org/) 的 "选择Matic(Polygon)主网 "来添加Polygon的网络。一旦你添加了网络,在你的钱包里通过导航到右上角的网络图标来切换它。 在Metamask中,该网络被称为 **Matic Mainnnet.** -At the end of each week, if you used your API keys, you will receive an invoice based on the query fees you have generated during this period. This invoice will be paid using GRT available in your balance. Query volume is evaluated by the API keys you own. Your balance will be updated after fees are withdrawn. +在每个周末,如果你使用了你的API密钥,你将会收到一张基于你在这期间产生的查询费用的发票。 这张发票将用你余额中的GRT来支付。 查询量是由你拥有的API密钥来评估的。 你的余额将在费用提取后被更新。 -#### Here’s how you go through the invoicing process: +#### 下面是你如何进行开票的过程: -There are 4 states your invoice can be in: +你的发票可以有4种状态: -1. Created - your invoice has just been created and not been paid yet -2. Paid - your invoice has been successfully paid -3. Unpaid - there is not enough GRT in your balance on the billing contract -4. Error - there is an error processing the payment +1. 创建--你的发票刚刚创建,还没有被支付 +2. 已付 - 你的发票已成功支付 +3. 未支付 - 账单合同上你的余额中没有足够的GRT +4. 错误 - 处理付款时出现了错误 -**See the diagram below for more information:** +**更多信息见下图:** ![Billing Flow](/img/billing-flow.png) -For a quick demo of how billing works on the Subgraph Studio, check out the video below: +关于在Subgraph Studio上如何进行计费的快速演示,请看下面的视频。
+>
-### Multisig Users +### 多重签名用户 -Multisigs are smart-contracts that can exist only on the network they have been created, so if you created one on Ethereum Mainnet - it will only exist on Mainnet. Since our billing uses Polygon, if you were to bridge GRT to the multisig address on Polygon the funds would be lost. +多重合约是只能存在于它们所创建的网络上的智能合约,所以如果你在以太坊主网上创建了一个--它将只存在于主网上。 由于我们的账单使用Polygon,如果你将GRT桥接到Polygon的多符号地址上,资金就会丢失。 -To overcome this issue, we created [a dedicated tool](https://multisig-billing.thegraph.com/) that will help you deposit GRT on our billing contract (on behalf of the multisig) with a standard wallet / EOA (an account controlled by a private key). +为了克服这个问题,我们创建了 [一个专门的工具](https://multisig-billing.thegraph.com/),它将帮助你用一个标准的钱包/EOA(一个由私钥控制的账户)在我们的计费合同上存入GRT(代表multisig)。 -You can access our Multisig Billing Tool here: https://multisig-billing.thegraph.com/ +你可以在这里访问我们的Multisig计费工具:https://multisig-billing.thegraph.com/ -This tool will guide you to go through the following steps: +这个工具将指导你完成以下步骤: -1. Connect your standard wallet / EOA (this wallet needs to own some ETH as well as the GRT you want to deposit) -2. Bridge GRT to Polygon. You will have to wait 7-8 minutes after the transaction is complete for the bridge transfer to be finalized. -3. Once your GRT is available on your Polygon balance you can deposit them to the billing contract while specifying the multisig address you are funding in the `Multisig Address` field. +1. 连接你的标准钱包/EOA(这个钱包需要拥有一些ETH以及你要存入的GRT)。 +2. 桥GRT到Polygon。 在交易完成后,你需要等待7-8分钟,以便最终完成桥梁转移。 +3. 一旦你的GRT在你的Polygon余额中可用,你就可以把它们存入账单合同,同时在`Multisig地址栏` 中指定你要资助的multisig地址。 -Once the deposit transaction has been confirmed you can go back to [Subgraph Studio](https://thegraph.com/studio/) and connect with your Gnosis Safe Multisig to create API keys and use them to generate queries. +一旦存款交易得到确认,你就可以回到 [Subgraph Studio](https://thegraph.com/studio/),并与你的Gnosis Safe Multisig连接,以创建API密钥并使用它们来生成查询。 -Those queries will generate invoices that will be paid automatically using the multisig’s billing balance. +这些查询将产生发票,这些发票将使用multisig的账单余额自动支付。 diff --git a/pages/zh/studio/deploy-subgraph-studio.mdx b/pages/zh/studio/deploy-subgraph-studio.mdx index 2155d8fe8976..62f614ab7d15 100644 --- a/pages/zh/studio/deploy-subgraph-studio.mdx +++ b/pages/zh/studio/deploy-subgraph-studio.mdx @@ -1,68 +1,68 @@ --- -title: Deploy a Subgraph to the Subgraph Studio +title: 将一个子图部署到子图工作室 --- -Deploying a Subgraph to the Subgraph Studio is quite simple. This will take you through the steps to: +将一个子图部署到子图工作室是非常简单的。 你可以通过以下步骤完成: -- Install The Graph CLI (with both yarn and npm) -- Create your Subgraph in the Subgraph Studio -- Authenticate your account from the CLI -- Deploying a Subgraph to the Subgraph Studio +- 安装Graph CLI(同时使用yarn和npm)。 +- 在子图工作室中创建你的子图 +- 从CLI认证你的账户 +- 将一个子图部署到子图工作室 -## Installing Graph CLI +## 安装Graph CLI -We are using the same CLI to deploy subgraphs to our [hosted service](https://thegraph.com/hosted-service/) and to the [Subgraph Studio](https://thegraph.com/studio/). Here are the commands to install graph-cli. This can be done using npm or yarn. +我们使用相同的CLI将子图部署到我们的 [托管服务](https://thegraph.com/hosted-service/) 和[Subgraph Studio](https://thegraph.com/studio/)中。 以下是安装graph-cli的命令。 这可以用npm或yarn来完成。 -**Install with yarn:** +**用yarn安装:** ```bash yarn global add @graphprotocol/graph-cli ``` -**Install with npm:** +**用npm安装:** ```bash npm install -g @graphprotocol/graph-cli ``` -## Create your Subgraph in Subgraph Studio +## 在子图工作室中创建你的子图 -Before deploying your actual subgraph you need to create a subgraph in [Subgraph Studio](https://thegraph.com/studio/). We recommend you read our [Studio documentation](/studio/subgraph-studio) to learn more about this. +在部署你的实际子图之前,你需要在 [子图工作室](https://thegraph.com/studio/)中创建一个子图。 我们建议你阅读我们的[Studio文档](/studio/subgraph-studio)以了解更多这方面的信息。 -## Initialize your Subgraph +## 初始化你的子图 -Once your subgraph has been created in Subgraph Studio you can initialize the subgraph code using this command: +一旦你的子图在子图工作室中被创建,你可以用这个命令初始化子图代码。 ```bash graph init --studio ``` -The `` value can be found on your subgraph details page in Subgraph Studio: +``值可以在Subgraph Studio中你的子图详情页上找到。 ![Subgraph Studio - Slug](/img/doc-subgraph-slug.png) -After running `graph init`, you will be asked to input the contract address, network and abi that you want to query. Doing this will generate a new folder on your local machine with some basic code to start working on your subgraph. You can then finalize your subgraph to make sure it works as expected. +运行`graph init`后,你会被要求输入你想查询的合同地址、网络和abi。 这样做将在你的本地机器上生成一个新的文件夹,里面有一些基本代码,可以开始在你的子图上工作。 然后,你可以最终确定你的子图,以确保它按预期工作。 -## Graph Auth +## Graph 认证 -Before being able to deploy your subgraph to Subgraph Studio, you need to login to your account within the CLI. To do this, you will need your deploy key that you can find on your "My Subgraphs" page or on your subgraph details page. +在能够将你的子图部署到子图工作室之前,你需要在CLI中登录到你的账户。 要做到这一点,你将需要你的部署密钥,你可以在你的 "我的子图 "页面或子图的详细信息页面上找到。 -Here is the command that you need to use to authenticate from the CLI: +以下是你需要使用的命令,以从CLI进行认证: ```bash graph auth --studio ``` -## Deploying a Subgraph to Subgraph Studio +## 将一个子图部署到子图工作室 -Once you are ready, you can deploy your subgraph to Subgraph Studio. Doing this won't publish your subgraph to the decentralized network, it will only deploy it to your Studio account where you will be able to test it and update the metadata. +一旦你准备好了,你可以将你的子图部署到子图工作室。 这样做不会将你的子图发布到去中心化的网络中,它只会将它部署到你的Studio账户中,在那里你将能够测试它并更新元数据。 -Here is the CLI command that you need to use to deploy your subgraph. +这里是你需要使用的CLI命令,以部署你的子图。 ```bash graph deploy --studio ``` -After running this command, the CLI will ask for a version label, you can name it however you want, you can use labels such as `0.1` and `0.2` or use letters as well such as `uniswap-v2-0.1` . Those labels will be visible in Graph Explorer and can be used by curators to decide if they want to signal on this version or not, so choose them wisely. +运行这个命令后,CLI会要求提供一个版本标签,你可以随意命名,你可以使用 `0.1`和 `0.2`这样的标签,或者也可以使用字母,如 `uniswap-v2-0.1` . 这些标签将在Graph Explorer中可见,并可由策展人用来决定是否要在这个版本上发出信号,所以要明智地选择它们。 -Once deployed, you can test your subgraph in Subgraph Studio using the playground, deploy another version if needed, update the metadata, and when you are ready, publish your subgraph to Graph Explorer. +一旦部署完毕,你可以在子图工作室中使用控制面板测试你的子图,如果需要的话,可以部署另一个版本,更新元数据,当你准备好后,将你的子图发布到Graph Explorer。 diff --git a/pages/zh/studio/studio-faq.mdx b/pages/zh/studio/studio-faq.mdx index 4db4d7ccddaa..b5f894110682 100644 --- a/pages/zh/studio/studio-faq.mdx +++ b/pages/zh/studio/studio-faq.mdx @@ -1,21 +1,21 @@ --- -title: Subgraph Studio FAQs +title: 子图工作室常见问题 --- -### 1. How do I create an API Key? +### 1. 我如何创建一个 API 密钥? -In the Subgraph Studio, you can create API Keys as needed and add security settings to each of them. +在 Subgraph Studio 中,你可以根据需要创建 API 密钥,并为每个密钥添加安全设置。 -### 2. Can I create multiple API Keys? +### 2. 我可以创建多个 API 密钥吗? -A: Yes! You can create multiple API Keys to use in different projects. Check out the link [here](https://thegraph.com/studio/apikeys/). +是的,可以。 你可以创建多个 API 密钥,在不同的项目中使用。 点击 [这里](https://thegraph.com/studio/apikeys/)查看。 -### 3. How do I restrict a domain for an API Key? +### 3. 我如何为 API 密钥限制一个域名? -After creating an API Key, in the Security section you can define the domains that can query a specific API Key. +创建了 API 密钥后,在安全部分,你可以定义可以查询特定 API 密钥的域。 -### 4. How do I find query URLs for subgraphs if I’m not the developer of the subgraph I want to use? +### 4. 如果我不是我想使用的子图的开发者,我怎样才能找到子图的查询 URL? -You can find the query URL of each subgraph in the Subgraph Details section of The Graph Explorer. When you click on the “Query” button, you will be directed to a pane wherein you can view the query URL of the subgraph you’re interested in. You can then replace the `` placeholder with the API key you wish to leverage in the Subgraph Studio. +你可以在 The Graph Explorer 的 Subgraph Details 部分找到每个子图的查询 URL。 当你点击 "查询 "按钮时,你将被引导到一个窗格,在这里你可以查看你感兴趣的子图的查询 URL。 然后你可以把 `api_key` 占位符替换成你想在 Subgraph Studio 中利用的 API 密钥。 -Remember that you can create an API key and query any subgraph published to the network, even if you build a subgraph yourself. These queries via the new API key, are paid queries as any other on the network. +请记住,你可以创建一个 API 密钥并查询发布到网络上的任何子图,即使你自己建立了一个子图。 这些通过新的 API 密钥进行的查询,与网络上的任何其他查询一样,都是付费查询。 diff --git a/pages/zh/studio/subgraph-studio.mdx b/pages/zh/studio/subgraph-studio.mdx index e01de9f15305..9af3926db3df 100644 --- a/pages/zh/studio/subgraph-studio.mdx +++ b/pages/zh/studio/subgraph-studio.mdx @@ -73,7 +73,7 @@ You’ve made it this far - congrats! Publishing your subgraph means that an IPF title="YouTube video player" frameBorder="0" allowFullScreen - > +> Remember, while you’re going through your publishing flow, you’ll be able to push to either mainnet or Rinkeby, the testnet we support. If you’re a first time subgraph developer, we highly suggest you start with publishing to Rinkeby, which is free to do. This will allow you to see how the subgraph will work in The Graph Explorer and will allow you to test curation elements. diff --git a/pages/zh/supported-networks/near.mdx b/pages/zh/supported-networks/near.mdx index bff2f82364d9..e5980fba4e95 100644 --- a/pages/zh/supported-networks/near.mdx +++ b/pages/zh/supported-networks/near.mdx @@ -1,56 +1,56 @@ --- -title: Building Subgraphs on NEAR +title: 在 NEAR 上构建子图 --- -> NEAR support in Graph Node and on the Hosted Service is in beta: please contact near@thegraph.com with any questions about building NEAR subgraphs! +> Graph节点和托管服务中对NEAR 的支持目前处于测试阶段:任何有关构建 NEAR 子图的任何问题,请联系 near@thegraph.com! -This guide is an introduction to building subgraphs indexing smart contracts on the [NEAR blockchain](https://docs.near.org/). +本指南介绍了如何在[NEAR区块链](https://docs.near.org/)上构建索引智能合约的子图。 -## What is NEAR? +## NEAR是什么? -[NEAR](https://near.org/) is a smart contract platform for building decentralised applications. Visit the [official documentation](https://docs.near.org/docs/concepts/new-to-near) for more information. +[NEAR](https://near.org/) 是一个用于构建去中心化应用程序的智能合约平台。 请访问 [官方文档](https://docs.near.org/docs/concepts/new-to-near) 了解更多信息。 -## What are NEAR subgraphs? +## NEAR子图是什么? -The Graph gives developers tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is now able to process NEAR events, which means that NEAR developers can now build subgraphs to index their smart contracts. +Graph 为开发人员提供了一种被称为子图的工具,利用这个工具,开发人员能够处理区块链事件,并通过 GraphQL API提供结果数据。 [Graph节点](https://github.com/graphprotocol/graph-node)现在能够处理 NEAR 事件,这意味着 NEAR 开发人员现在可以构建子图来索引他们的智能合约。 -Subgraphs are event-based, which means that they listen for and then process on-chain events. There are currently two types of handlers supported for NEAR subgraphs: +子图是基于事件的,这意味着子图可以侦听并处理链上事件。 NEAR 子图目前支持两种类型的处理程序: -- Block handlers: these are run on every new block -- Receipt handlers: run every time a message is executed at a specified account +- 区块处理器: 这些处理程序在每个新区块上运行 +- 收据处理器: 每次在指定帐户上一个消息被执行时运行。 -[From the NEAR documentation](https://docs.near.org/docs/concepts/transaction#receipt): +[NEAR 文档中](https://docs.near.org/docs/concepts/transaction#receipt): -> A Receipt is the only actionable object in the system. When we talk about "processing a transaction" on the NEAR platform, this eventually means "applying receipts" at some point. +> Receipt是系统中唯一可操作的对象。 当我们在 NEAR 平台上谈论“处理交易”时,这最终意味着在某个时候“应用收据”。 -## Building a NEAR Subgraph +## 构建NEAR子图 -`@graphprotocol/graph-cli` is a command line tool for building and deploying subgraphs. +`@graphprotocol/graph-cli`是一个用于构建和部署子图的命令行工具。 -`@graphprotocol/graph-ts` is a library of subgraph-specific types. +`@graphprotocol/graph-ts` 是子图特定类型的库。 -NEAR subgraph development requires `graph-cli` above version `0.23.0`, and `graph-ts` above version `0.23.0`. +NEAR子图开发需要`0.23.0`以上版本的`graph-cli`,以及 `0.23.0`以上版本的`graph-ts`。 -> Building a NEAR subgraph is very similar to building a subgraph which indexes Ethereum. +> 构建 NEAR 子图与构建索引以太坊的子图非常相似。 -There are three aspects of subgraph definition: +子图定义包括三个方面: -**subgraph.yaml:** the subgraph manifest, defining the data sources of interest, and how they should be processed. NEAR is a new `kind` of data source. +**subgraph.yaml:** 子图清单,定义感兴趣的数据源以及如何处理它们。 NEAR 是一种全新`类型`数据源。 -**schema.graphql:** a schema file that defines what data is stored for your subgraph, and how to query it via GraphQL. The requirements for NEAR subgraphs are covered by [the existing documentation](/developer/create-subgraph-hosted#the-graphql-schema). +**schema.graphql:** 一个模式文件,它定义为您的子图存储哪些数据,以及如何通过 GraphQL 查询它。 NEAR 子图的要求包含在 [现有文档](/developer/create-subgraph-hosted#the-graphql-schema)中。 -**AssemblyScript Mappings:** [AssemblyScript code](/developer/assemblyscript-api) that translates from the event data to the entities defined in your schema. NEAR support introduces NEAR-specific data types, and new JSON parsing functionality. +**AssemblyScript 映射:**将事件数据转换为模式文件中定义的实体的[AssemblyScript 代码](/developer/assemblyscript-api)。 NEAR 支持引入了 NEAR 特定的数据类型和新的JSON 解析功能。 -During subgraph development there are two key commands: +在子图开发过程中,有两个关键命令: ```bash -$ graph codegen # generates types from the schema file identified in the manifest -$ graph build # generates Web Assembly from the AssemblyScript files, and prepares all the subgraph files in a /build folder +$ graph codegen # 从清单中标识的模式文件生成类型 +$ graph build # 从 AssemblyScript 文件生成 Web Assembly,并在 /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 a NEAR subgraph:: +子图清单(`subgraph.yaml`)标识子图的数据源、感兴趣的触发器以及响应这些触发器而运行的函数。 以下是一个NEAR 的子图清单的例子: ```yaml specVersion: 0.0.2