1659229200
Le Graph est un protocole d'indexation pour organiser les données de la blockchain. Il utilise une API GraphQL pour fournir un accès plus facile aux informations en chaîne que la méthode traditionnelle d'envoi d'un appel RPC.
Le réseau organise les données avec des sous-graphes ; API open source créées par la communauté et utilisées pour récupérer des données auprès des indexeurs, des curateurs et des délégants.
Dans cet article, nous allons voir comment vous pouvez utiliser The Graph et les sous-graphes pour l'interrogation des données Web3.
Les indexeurs exploitent les nœuds du réseau, qui indexent les données et servent les requêtes.
Étant donné que le réseau Graph utilise un algorithme de preuve de participation, les indexeurs jalonnent les jetons de graphe (GRT) pour fournir des services d'indexation et de traitement des requêtes. À leur tour, les indexeurs peuvent gagner des frais de requête et des récompenses d'indexation.
Ils sélectionnent les sous-graphes à indexer en fonction du signal de curation du sous-graphe. Les applications qui consomment les données des indexeurs peuvent définir des paramètres pour lesquels elles souhaitent traiter leurs requêtes, ainsi que leurs préférences en matière de tarification des frais de requête.
Les conservateurs organisent les données des sous-graphes en signalant sur les sous-graphes qui doivent être indexés par le Graph Network.
Pour ce faire, ils utilisent les Graph Curation Shares (GCS), qui leur permettent de placer l'équivalent d'un investissement sur un sous-graphe.
Les conservateurs jalonnent GRT, ce qui leur permet de frapper GCS. Chaque sous-graphique a une courbe de liaison qui détermine la relation entre le prix du GRT et le nombre d'actions pouvant être frappées.
Selon la documentation de Graph, la conservation est considérée comme risquée et ne doit être effectuée qu'après une recherche approfondie et une enquête sur les compromis impliqués.
Les délégants jalonnent GRT sur un ou plusieurs indexeurs pour aider à sécuriser le réseau sans avoir à exécuter eux-mêmes un nœud.
Les délégants gagnent des parties des frais de requête et des récompenses de l'indexeur, qui dépendent de la participation de l'indexeur et du délégant, ainsi que du prix que l'indexeur facture pour chaque requête.
Allouer plus de participation à un indexeur permet de traiter plus de requêtes potentielles. La documentation du Graph affirme qu'être un délégant comporte moins de risques qu'être un conservateur car ils ne sont pas exposés aux fluctuations du prix du GRT, en raison de la combustion des actions de GCS.
The Graph est développé et maintenu par The Graph Foundation. Pour s'assurer que le réseau et la communauté élargie continuent de s'améliorer, la fondation distribue des subventions (appelées Graph Grants) aux membres de la communauté travaillant sur l'infrastructure de protocole, les outils, les dApps, les sous-graphes et le développement de la communauté.
Il existe trois manières différentes d'interagir avec le graphique si vous n'hébergez pas votre propre sous-graphique :
Le service hébergé ne nécessite pas de portefeuille cryptographique et peut être utilisé avec un compte GitHub. Le Graph Explorer et Subgraph Studio vous demanderont tous deux de connecter un portefeuille tel que MetaMask ou Coinbase.
Après avoir créé un compte sur le service hébergé, cliquez sur Mon tableau de bord dans la barre de navigation pour voir votre tableau de bord.
Cliquez sur Ajouter un sous-graphe pour créer un sous-graphe.
Ajoutez un nom et un sous-titre pour votre sous-graphique. Une fois que vous avez rempli les informations de votre sous-graphique, faites défiler vers le bas de la page et cliquez sur Créer un sous-graphique .
Avec notre configuration de sous-graphe sur le service hébergé, nous pouvons créer nos fichiers de projet. Créez un nouveau répertoire, initialisez un package.json
et installez les dépendances.
mkdir graphrocket
cd graphrocket
yarn init -y
yarn add -D @graphprotocol/graph-cli @graphprotocol/graph-ts
Copiez le jeton d'accès disponible sur le tableau de bord de votre projet sur Hosted Service. Collez le jeton après la yarn graph auth --product hosted-service
commande.
yarn graph auth --product hosted-service YOURTOKEN
Créez des fichiers de configuration pour TypeScript et Git.
echo '{"extends": "@graphprotocol/graph-ts/types/tsconfig.base.json"}' > tsconfig.json
echo '.DS_Store\nnode_modules' > .gitignore
Les contrats intelligents sur la blockchain Ethereum exposent une interface binaire d'application (ou ABI) en tant qu'interface entre les applications côté client et la blockchain Ethereum. Nous en aurons besoin pour notre sous-graphe.
Téléchargez l'ABI du contrat avec cURL et enregistrez-le dans un fichier appelé Token.json
.
curl "http://api.etherscan.io/api?module=contract&action=getabi&address=0xe7c29cba93ef8017c7824dd0f25923c38d08065c&format=raw" > Token.json
Créez trois fichiers de projet comprenant :
token.ts
pour le code AssemblyScript qui traduit les données d'événement Ethereum dans les entités définies dans le schémasubgraph.yaml
pour une configuration YAML du manifeste du sous-grapheschema.graphql
pour un schéma GraphQL définissant les données stockées pour le sous-graphe et comment l'interroger via GraphQLecho > token.ts
echo > schema.graphql
echo > subgraph.yaml
Token
et User
entitésDans schema.graphql
nous avons défini deux types, Token
et User
.
# schema.graphql
type Token @entity {}
type User @entity {}
Le Token
contient un name
et d'autres informations telles que la date de sa création, l'URI du contenu et le chemin du fichier IPFS. Il comprend également des informations sur les creator
et owner
.
# schema.graphql
type Token @entity {
id: ID!
tokenID: BigInt!
contentURI: String
tokenIPFSPath: String
name: String!
createdAtTimestamp: BigInt!
creator: User!
owner: User!
}
Les creator
et owner
sont des User
types. Ils ont un id
, un tableau tokens
qui leur appartient et un tableau tokens
qu'ils ont created
.
# schema.graphql
type User @entity {
id: ID!
tokens: [Token!]! @derivedFrom(field: "owner")
created: [Token!]! @derivedFrom(field: "creator")
}
@derivedFrom
permet les recherches inversées, ce qui signifie que nous ne stockons pas les deux côtés de la relation pour améliorer les performances d'indexation et de requête. Pour les relations un-à-plusieurs, la relation doit être stockée du côté « un » avec le côté « plusieurs » dérivé de celle-ci.
Le subgraph.yaml
fichier contiendra la définition de notre sous-graphe. Commencez par la version de la spécification utilisée et un chemin de fichier vers les types d'entités dans schema.graphql
.
# subgraph.yaml
specVersion: 0.0.4
schema:
file: ./schema.graphql
Vient ensuite le réseau contenant nos sources de données. dataSources.source
a besoin de l'adresse et de l'ABI du contrat intelligent.
# subgraph.yaml
dataSources:
- kind: ethereum
name: Token
network: mainnet
source:
address: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405"
abi: Token
startBlock: 11648721
dataSources.mapping.entities
définit les entités que la source de données écrit dans le magasin et est spécifié par le schéma dans schema.graphql
.
# subgraph.yaml
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
entities:
- Token
- User
dataSources.mapping.abis
prend le name
et l' file
emplacement de l'ABI pour le contrat source.
# subgraph.yaml
abis:
- name: Token
file: ./Token.json
dataSources.mapping.eventHandlers
répertorie les événements de contrat intelligent auxquels le sous-graphe réagit et les gestionnaires dans les mappages qui transforment ces événements en entités dans le magasin.
# subgraph.yaml
eventHandlers:
- event: TokenIPFSPathUpdated(indexed uint256,indexed string,string)
handler: handleTokenIPFSPathUpdated
- event: Transfer(indexed address,indexed address,indexed uint256)
handler: handleTransfer
file: ./token.ts
Dossier completsubgraph.yaml
:
# subgraph.yaml
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum
name: Token
network: mainnet
source:
address: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405"
abi: Token
startBlock: 11648721
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
entities:
- Token
- User
abis:
- name: Token
file: ./Token.json
eventHandlers:
- event: TokenIPFSPathUpdated(indexed uint256,indexed string,string)
handler: handleTokenIPFSPathUpdated
- event: Transfer(indexed address,indexed address,indexed uint256)
handler: handleTransfer
file: ./token.ts
Générez des types AssemblyScript pour l'ABI et le schéma de sous-graphe.
yarn graph codegen
Importez les types générés et le schéma généré et créez deux fonctions : handleTransfer
et handleTokenURIUpdated
.
Lorsqu'un nouveau jeton est créé, transféré ou mis à jour, un événement est déclenché et les mappages enregistrent les données dans le sous-graphe.
// token.ts
import {
TokenIPFSPathUpdated as TokenIPFSPathUpdatedEvent,
Transfer as TransferEvent,
Token as TokenContract,
} from "./generated/Token/Token"
import {
Token, User
} from './generated/schema'
export function handleTransfer(event: TransferEvent): void {}
export function handleTokenURIUpdated(event: TokenIPFSPathUpdatedEvent): void {}
handleTransfer
charge le tokenId
et définit le owner
.
// token.ts
export function handleTransfer(event: TransferEvent): void {
let token = Token.load(event.params.tokenId.toString())
if (!token) {
token = new Token(event.params.tokenId.toString())
token.creator = event.params.to.toHexString()
token.tokenID = event.params.tokenId
let tokenContract = TokenContract.bind(event.address)
token.contentURI = tokenContract.tokenURI(event.params.tokenId)
token.tokenIPFSPath = tokenContract.getTokenIPFSPath(event.params.tokenId)
token.name = tokenContract.name()
token.createdAtTimestamp = event.block.timestamp
}
token.owner = event.params.to.toHexString()
token.save()
let user = User.load(event.params.to.toHexString())
if (!user) {
user = new User(event.params.to.toHexString())
user.save()
}
}
handleTokenURIUpdated
met à jour le tokenIPFSPath
chaque fois qu'il change.
// token.ts
export function handleTokenURIUpdated(event: TokenIPFSPathUpdatedEvent): void {
let token = Token.load(event.params.tokenId.toString())
if (!token) return
token.tokenIPFSPath = event.params.tokenIPFSPath
token.save()
}
Créez votre projet pour le déploiement :
yarn graph build
Incluez votre propre nom d'utilisateur GitHub suivi du nom de votre sous-graphe :
yarn graph deploy --node https://api.thegraph.com/deploy/ USERNAME/logrocketgraph
Le terminal renverra une URL avec un explorateur pour le sous-graphe et un point de terminaison API pour l'envoi de requêtes.
Déployé sur https://thegraph.com/explorer/subgraph/ajcwebdev/logrocketgraph Points de terminaison Subgraph : Requêtes (HTTP) : https://api.thegraph.com/subgraphs/name/ajcwebdev/logrocketgraph
Vous devrez attendre que votre sous-graphe se synchronise avec l'état actuel de la blockchain. Une fois la synchronisation terminée, exécutez la requête suivante pour afficher les deux premiers jetons classés par id
dans l'ordre décroissant.
{
tokens(first: 2, orderBy: id, orderDirection: desc) {
id
tokenID
contentURI
tokenIPFSPath
}
}
Cela affichera ce qui suit :
{
"data": {
"tokens": [
{
"id": "99999",
"tokenID": "99999",
"contentURI": "https://ipfs.foundation.app/ipfs/QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json",
"tokenIPFSPath": "QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json"
},
{
"id": "99998",
"tokenID": "99998",
"contentURI": "https://ipfs.foundation.app/ipfs/QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json",
"tokenIPFSPath": "QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json"
}
]
}
}
Requête pour le premier utilisateur et son contenu associé :
{
users(first: 1, orderBy: id, orderDirection: desc) {
id
tokens {
contentURI
}
}
}
Cela affichera ce qui suit :
{
"data": {
"users": [
{
"id": "0xfffff449f1a35eb0facca8d4659d8e15cf2f77ba",
"tokens": [
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmVkXqo2hmC2j18udhZG1KavxaTGrnEX7uuddEbghPKCUW/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmTSEgtJmptBCpEJKubK6xDZFiCMEHgGQjhrUAsJSXwzKZ/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmPzSJGhheyyA7MZMYz7VngnZWN8TinH75PTP7M1HAedti/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmeroC2cWfdN31hLd3JpBQMbbWqnQdUdGx94FGUR4AGBUP/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmQVkhqEsZvsstfDp6QAPXB4TkxFnpeAc9BWu2eQo6QvZD/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmRax3fw4skHp95i2v3BzroMoKQVHqAkwbov8FyPdesk3j/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmViGRnvHFBZ6CWHoxZGJoU9iwnoGwZfqj2vgDN3dgsGv4/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmdRBPxDF1tUzm1Pczyme24vguUjW28cLwM4n9MvtxAWX6/metadata.json"
}
]
}
]
}
}
Recherchez les deux derniers NFT créés.
{
tokens(
first: 2,
orderBy: createdAtTimestamp,
orderDirection: desc
) {
id
tokenID
contentURI
createdAtTimestamp
}
}
Cela affichera ce qui suit :
{
"data": {
"tokens": [
{
"id": "133012",
"tokenID": "133012",
"contentURI": "https://ipfs.foundation.app/ipfs/QmSmk85TjpaegCmHDRWZQqMz18vJtACZdugVx5a1tmfjpv/metadata.json",
"createdAtTimestamp": "1656792769"
},
{
"id": "133011",
"tokenID": "133011",
"contentURI": "https://ipfs.foundation.app/ipfs/QmU6RFcKFDteUTipg5tg4NFkWKApdVbo9oq9UYMtSmcWVe/metadata.json",
"createdAtTimestamp": "1653825764"
}
]
}
}
Vous pouvez également utiliser le point de terminaison HTTP et envoyer des requêtes GraphQL directement avec cURL.
curl \
--header 'content-type: application/json' \
--url 'https://api.thegraph.com/subgraphs/name/ajcwebdev/logrocketgraph' \
--data '{"query":"{ tokens(first: 1) { contentURI tokenIPFSPath } }"}'
Dans cet article, nous avons vu comment créer un endpoint GraphQL qui expose certaines informations contenues sur la blockchain Ethereum. En écrivant un schéma contenant nos entités, nous avons défini les informations qui seront indexées par le sous-graphe.
La quantité et la diversité des réseaux blockchain continuent de proliférer dans le Web3. Disposer d'un langage de requête standardisé et largement adopté permettra aux développeurs d'itérer et de tester leurs applications plus rapidement.
Source : https://blog.logrocket.com/web3-data-querying-the-graph-subgraphs/
1659229200
Le Graph est un protocole d'indexation pour organiser les données de la blockchain. Il utilise une API GraphQL pour fournir un accès plus facile aux informations en chaîne que la méthode traditionnelle d'envoi d'un appel RPC.
Le réseau organise les données avec des sous-graphes ; API open source créées par la communauté et utilisées pour récupérer des données auprès des indexeurs, des curateurs et des délégants.
Dans cet article, nous allons voir comment vous pouvez utiliser The Graph et les sous-graphes pour l'interrogation des données Web3.
Les indexeurs exploitent les nœuds du réseau, qui indexent les données et servent les requêtes.
Étant donné que le réseau Graph utilise un algorithme de preuve de participation, les indexeurs jalonnent les jetons de graphe (GRT) pour fournir des services d'indexation et de traitement des requêtes. À leur tour, les indexeurs peuvent gagner des frais de requête et des récompenses d'indexation.
Ils sélectionnent les sous-graphes à indexer en fonction du signal de curation du sous-graphe. Les applications qui consomment les données des indexeurs peuvent définir des paramètres pour lesquels elles souhaitent traiter leurs requêtes, ainsi que leurs préférences en matière de tarification des frais de requête.
Les conservateurs organisent les données des sous-graphes en signalant sur les sous-graphes qui doivent être indexés par le Graph Network.
Pour ce faire, ils utilisent les Graph Curation Shares (GCS), qui leur permettent de placer l'équivalent d'un investissement sur un sous-graphe.
Les conservateurs jalonnent GRT, ce qui leur permet de frapper GCS. Chaque sous-graphique a une courbe de liaison qui détermine la relation entre le prix du GRT et le nombre d'actions pouvant être frappées.
Selon la documentation de Graph, la conservation est considérée comme risquée et ne doit être effectuée qu'après une recherche approfondie et une enquête sur les compromis impliqués.
Les délégants jalonnent GRT sur un ou plusieurs indexeurs pour aider à sécuriser le réseau sans avoir à exécuter eux-mêmes un nœud.
Les délégants gagnent des parties des frais de requête et des récompenses de l'indexeur, qui dépendent de la participation de l'indexeur et du délégant, ainsi que du prix que l'indexeur facture pour chaque requête.
Allouer plus de participation à un indexeur permet de traiter plus de requêtes potentielles. La documentation du Graph affirme qu'être un délégant comporte moins de risques qu'être un conservateur car ils ne sont pas exposés aux fluctuations du prix du GRT, en raison de la combustion des actions de GCS.
The Graph est développé et maintenu par The Graph Foundation. Pour s'assurer que le réseau et la communauté élargie continuent de s'améliorer, la fondation distribue des subventions (appelées Graph Grants) aux membres de la communauté travaillant sur l'infrastructure de protocole, les outils, les dApps, les sous-graphes et le développement de la communauté.
Il existe trois manières différentes d'interagir avec le graphique si vous n'hébergez pas votre propre sous-graphique :
Le service hébergé ne nécessite pas de portefeuille cryptographique et peut être utilisé avec un compte GitHub. Le Graph Explorer et Subgraph Studio vous demanderont tous deux de connecter un portefeuille tel que MetaMask ou Coinbase.
Après avoir créé un compte sur le service hébergé, cliquez sur Mon tableau de bord dans la barre de navigation pour voir votre tableau de bord.
Cliquez sur Ajouter un sous-graphe pour créer un sous-graphe.
Ajoutez un nom et un sous-titre pour votre sous-graphique. Une fois que vous avez rempli les informations de votre sous-graphique, faites défiler vers le bas de la page et cliquez sur Créer un sous-graphique .
Avec notre configuration de sous-graphe sur le service hébergé, nous pouvons créer nos fichiers de projet. Créez un nouveau répertoire, initialisez un package.json
et installez les dépendances.
mkdir graphrocket
cd graphrocket
yarn init -y
yarn add -D @graphprotocol/graph-cli @graphprotocol/graph-ts
Copiez le jeton d'accès disponible sur le tableau de bord de votre projet sur Hosted Service. Collez le jeton après la yarn graph auth --product hosted-service
commande.
yarn graph auth --product hosted-service YOURTOKEN
Créez des fichiers de configuration pour TypeScript et Git.
echo '{"extends": "@graphprotocol/graph-ts/types/tsconfig.base.json"}' > tsconfig.json
echo '.DS_Store\nnode_modules' > .gitignore
Les contrats intelligents sur la blockchain Ethereum exposent une interface binaire d'application (ou ABI) en tant qu'interface entre les applications côté client et la blockchain Ethereum. Nous en aurons besoin pour notre sous-graphe.
Téléchargez l'ABI du contrat avec cURL et enregistrez-le dans un fichier appelé Token.json
.
curl "http://api.etherscan.io/api?module=contract&action=getabi&address=0xe7c29cba93ef8017c7824dd0f25923c38d08065c&format=raw" > Token.json
Créez trois fichiers de projet comprenant :
token.ts
pour le code AssemblyScript qui traduit les données d'événement Ethereum dans les entités définies dans le schémasubgraph.yaml
pour une configuration YAML du manifeste du sous-grapheschema.graphql
pour un schéma GraphQL définissant les données stockées pour le sous-graphe et comment l'interroger via GraphQLecho > token.ts
echo > schema.graphql
echo > subgraph.yaml
Token
et User
entitésDans schema.graphql
nous avons défini deux types, Token
et User
.
# schema.graphql
type Token @entity {}
type User @entity {}
Le Token
contient un name
et d'autres informations telles que la date de sa création, l'URI du contenu et le chemin du fichier IPFS. Il comprend également des informations sur les creator
et owner
.
# schema.graphql
type Token @entity {
id: ID!
tokenID: BigInt!
contentURI: String
tokenIPFSPath: String
name: String!
createdAtTimestamp: BigInt!
creator: User!
owner: User!
}
Les creator
et owner
sont des User
types. Ils ont un id
, un tableau tokens
qui leur appartient et un tableau tokens
qu'ils ont created
.
# schema.graphql
type User @entity {
id: ID!
tokens: [Token!]! @derivedFrom(field: "owner")
created: [Token!]! @derivedFrom(field: "creator")
}
@derivedFrom
permet les recherches inversées, ce qui signifie que nous ne stockons pas les deux côtés de la relation pour améliorer les performances d'indexation et de requête. Pour les relations un-à-plusieurs, la relation doit être stockée du côté « un » avec le côté « plusieurs » dérivé de celle-ci.
Le subgraph.yaml
fichier contiendra la définition de notre sous-graphe. Commencez par la version de la spécification utilisée et un chemin de fichier vers les types d'entités dans schema.graphql
.
# subgraph.yaml
specVersion: 0.0.4
schema:
file: ./schema.graphql
Vient ensuite le réseau contenant nos sources de données. dataSources.source
a besoin de l'adresse et de l'ABI du contrat intelligent.
# subgraph.yaml
dataSources:
- kind: ethereum
name: Token
network: mainnet
source:
address: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405"
abi: Token
startBlock: 11648721
dataSources.mapping.entities
définit les entités que la source de données écrit dans le magasin et est spécifié par le schéma dans schema.graphql
.
# subgraph.yaml
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
entities:
- Token
- User
dataSources.mapping.abis
prend le name
et l' file
emplacement de l'ABI pour le contrat source.
# subgraph.yaml
abis:
- name: Token
file: ./Token.json
dataSources.mapping.eventHandlers
répertorie les événements de contrat intelligent auxquels le sous-graphe réagit et les gestionnaires dans les mappages qui transforment ces événements en entités dans le magasin.
# subgraph.yaml
eventHandlers:
- event: TokenIPFSPathUpdated(indexed uint256,indexed string,string)
handler: handleTokenIPFSPathUpdated
- event: Transfer(indexed address,indexed address,indexed uint256)
handler: handleTransfer
file: ./token.ts
Dossier completsubgraph.yaml
:
# subgraph.yaml
specVersion: 0.0.4
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum
name: Token
network: mainnet
source:
address: "0x3B3ee1931Dc30C1957379FAc9aba94D1C48a5405"
abi: Token
startBlock: 11648721
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
entities:
- Token
- User
abis:
- name: Token
file: ./Token.json
eventHandlers:
- event: TokenIPFSPathUpdated(indexed uint256,indexed string,string)
handler: handleTokenIPFSPathUpdated
- event: Transfer(indexed address,indexed address,indexed uint256)
handler: handleTransfer
file: ./token.ts
Générez des types AssemblyScript pour l'ABI et le schéma de sous-graphe.
yarn graph codegen
Importez les types générés et le schéma généré et créez deux fonctions : handleTransfer
et handleTokenURIUpdated
.
Lorsqu'un nouveau jeton est créé, transféré ou mis à jour, un événement est déclenché et les mappages enregistrent les données dans le sous-graphe.
// token.ts
import {
TokenIPFSPathUpdated as TokenIPFSPathUpdatedEvent,
Transfer as TransferEvent,
Token as TokenContract,
} from "./generated/Token/Token"
import {
Token, User
} from './generated/schema'
export function handleTransfer(event: TransferEvent): void {}
export function handleTokenURIUpdated(event: TokenIPFSPathUpdatedEvent): void {}
handleTransfer
charge le tokenId
et définit le owner
.
// token.ts
export function handleTransfer(event: TransferEvent): void {
let token = Token.load(event.params.tokenId.toString())
if (!token) {
token = new Token(event.params.tokenId.toString())
token.creator = event.params.to.toHexString()
token.tokenID = event.params.tokenId
let tokenContract = TokenContract.bind(event.address)
token.contentURI = tokenContract.tokenURI(event.params.tokenId)
token.tokenIPFSPath = tokenContract.getTokenIPFSPath(event.params.tokenId)
token.name = tokenContract.name()
token.createdAtTimestamp = event.block.timestamp
}
token.owner = event.params.to.toHexString()
token.save()
let user = User.load(event.params.to.toHexString())
if (!user) {
user = new User(event.params.to.toHexString())
user.save()
}
}
handleTokenURIUpdated
met à jour le tokenIPFSPath
chaque fois qu'il change.
// token.ts
export function handleTokenURIUpdated(event: TokenIPFSPathUpdatedEvent): void {
let token = Token.load(event.params.tokenId.toString())
if (!token) return
token.tokenIPFSPath = event.params.tokenIPFSPath
token.save()
}
Créez votre projet pour le déploiement :
yarn graph build
Incluez votre propre nom d'utilisateur GitHub suivi du nom de votre sous-graphe :
yarn graph deploy --node https://api.thegraph.com/deploy/ USERNAME/logrocketgraph
Le terminal renverra une URL avec un explorateur pour le sous-graphe et un point de terminaison API pour l'envoi de requêtes.
Déployé sur https://thegraph.com/explorer/subgraph/ajcwebdev/logrocketgraph Points de terminaison Subgraph : Requêtes (HTTP) : https://api.thegraph.com/subgraphs/name/ajcwebdev/logrocketgraph
Vous devrez attendre que votre sous-graphe se synchronise avec l'état actuel de la blockchain. Une fois la synchronisation terminée, exécutez la requête suivante pour afficher les deux premiers jetons classés par id
dans l'ordre décroissant.
{
tokens(first: 2, orderBy: id, orderDirection: desc) {
id
tokenID
contentURI
tokenIPFSPath
}
}
Cela affichera ce qui suit :
{
"data": {
"tokens": [
{
"id": "99999",
"tokenID": "99999",
"contentURI": "https://ipfs.foundation.app/ipfs/QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json",
"tokenIPFSPath": "QmdDdmRAw8zgmN9iE23oz14a55oHGWtqBrR1RbFcFq4Abn/metadata.json"
},
{
"id": "99998",
"tokenID": "99998",
"contentURI": "https://ipfs.foundation.app/ipfs/QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json",
"tokenIPFSPath": "QmZwZ5ChjHNwAS5rFDGkom2GpZvTau6xzr8M7gro5HqQhB/metadata.json"
}
]
}
}
Requête pour le premier utilisateur et son contenu associé :
{
users(first: 1, orderBy: id, orderDirection: desc) {
id
tokens {
contentURI
}
}
}
Cela affichera ce qui suit :
{
"data": {
"users": [
{
"id": "0xfffff449f1a35eb0facca8d4659d8e15cf2f77ba",
"tokens": [
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmVkXqo2hmC2j18udhZG1KavxaTGrnEX7uuddEbghPKCUW/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmTSEgtJmptBCpEJKubK6xDZFiCMEHgGQjhrUAsJSXwzKZ/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmPzSJGhheyyA7MZMYz7VngnZWN8TinH75PTP7M1HAedti/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmeroC2cWfdN31hLd3JpBQMbbWqnQdUdGx94FGUR4AGBUP/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmQVkhqEsZvsstfDp6QAPXB4TkxFnpeAc9BWu2eQo6QvZD/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmRax3fw4skHp95i2v3BzroMoKQVHqAkwbov8FyPdesk3j/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmViGRnvHFBZ6CWHoxZGJoU9iwnoGwZfqj2vgDN3dgsGv4/metadata.json"
},
{
"contentURI": "https://ipfs.foundation.app/ipfs/QmdRBPxDF1tUzm1Pczyme24vguUjW28cLwM4n9MvtxAWX6/metadata.json"
}
]
}
]
}
}
Recherchez les deux derniers NFT créés.
{
tokens(
first: 2,
orderBy: createdAtTimestamp,
orderDirection: desc
) {
id
tokenID
contentURI
createdAtTimestamp
}
}
Cela affichera ce qui suit :
{
"data": {
"tokens": [
{
"id": "133012",
"tokenID": "133012",
"contentURI": "https://ipfs.foundation.app/ipfs/QmSmk85TjpaegCmHDRWZQqMz18vJtACZdugVx5a1tmfjpv/metadata.json",
"createdAtTimestamp": "1656792769"
},
{
"id": "133011",
"tokenID": "133011",
"contentURI": "https://ipfs.foundation.app/ipfs/QmU6RFcKFDteUTipg5tg4NFkWKApdVbo9oq9UYMtSmcWVe/metadata.json",
"createdAtTimestamp": "1653825764"
}
]
}
}
Vous pouvez également utiliser le point de terminaison HTTP et envoyer des requêtes GraphQL directement avec cURL.
curl \
--header 'content-type: application/json' \
--url 'https://api.thegraph.com/subgraphs/name/ajcwebdev/logrocketgraph' \
--data '{"query":"{ tokens(first: 1) { contentURI tokenIPFSPath } }"}'
Dans cet article, nous avons vu comment créer un endpoint GraphQL qui expose certaines informations contenues sur la blockchain Ethereum. En écrivant un schéma contenant nos entités, nous avons défini les informations qui seront indexées par le sous-graphe.
La quantité et la diversité des réseaux blockchain continuent de proliférer dans le Web3. Disposer d'un langage de requête standardisé et largement adopté permettra aux développeurs d'itérer et de tester leurs applications plus rapidement.
Source : https://blog.logrocket.com/web3-data-querying-the-graph-subgraphs/
1656899776
Simple scrolling events for d3 graphs. Based on stack
graph-scroll takes a selection of explanatory text sections and dispatches active
events as different sections are scrolled into to view. These active
events can be used to update a chart's state.
d3.graphScroll()
.sections(d3.selectAll('#sections > div'))
.on('active', function(i){ console.log(i + 'th section active') })
The top most element scrolled fully into view is classed graph-scroll-active
. This makes it easy to highlight the active section with css:
#sections > div{
opacity: .3
}
#sections div.graph-scroll-active{
opacity: 1;
}
To support headers and intro images/text, we use a container element containing the explanatory text and graph.
<h1>Page Title</div>
<div id='container'>
<div id='graph'></div>
<div id='sections'>
<div>Section 0</div>
<div>Section 1</div>
<div>Section 2</div>
</div>
</div>
<h1>Footer</h1>
If these elements are passed to graphScroll as selections with container
and graph
, every element in the graph selection will be classed graph-scroll-graph
if the top of the container is out of view.
d3.graphScroll()
.graph(d3.selectAll('#graph'))
.container(d3.select('#container'))
.sections(d3.selectAll('#sections > div'))
.on('active', function(i){ console.log(i + 'th section active') })
When the graph starts to scroll out of view, position: sticky
keeps the graph element stuck to the top of the page while the text scrolls by.
#container{
position: relative;
}
#sections{
width: 340px;
}
#graph{
margin-left: 40px;
width: 500px;
position: sticky;
top: 0px;
float: right;
}
On mobile centering the graph and sections while adding a some padding for the first slide is a good option:
@media (max-width: 925px) {
#graph{
width: 100%;
margin-left: 0px;
float: none;
}
#sections{
position: relative;
margin: 0px auto;
padding-top: 400px;
}
}
Adjust the amount of pixels before a new section is triggered is also helpful on mobile (Defaults to 200 pixels):
graphScroll.offset(300)
To update or replace a graphScroll instance, pass a string to eventId
to remove the old event listeners:
graphScroll.eventId('uniqueId1')
Author: 1wheel
Source Code: https://github.com/1wheel/graph-scroll
License: MIT license
1617257581
¿Quiere restaurar los buzones de correo de PST a Exchange Server? Entonces, estás en la página correcta. Aquí, lo guiaremos sobre cómo puede restaurar fácilmente mensajes y otros elementos de PST a MS Exchange Server.
Muchas veces, los usuarios necesitan restaurar los elementos de datos de PST en Exchange Server, pero debido a la falta de disponibilidad de una solución confiable, los usuarios no pueden obtener la solución. Háganos saber primero sobre el archivo PST y MS Exchange Server.
PST es un formato de archivo utilizado por MS Outlook, un cliente de correo electrónico de Windows y muy popular entre los usuarios domésticos y comerciales.
Por otro lado, Exchange Server es un poderoso servidor de correo electrónico donde todos los datos se almacenan en un archivo EDB. Los usuarios generalmente guardan la copia de seguridad de los buzones de correo de Exchange en el archivo PST, pero muchas veces, los usuarios deben restaurar los datos del archivo PST en Exchange. Para resolver este problema, estamos aquí con una solución profesional que discutiremos en la siguiente sección de esta publicación.
No le recomendamos que elija una solución al azar para restaurar los datos de PST en Exchange Server. Por lo tanto, al realizar varias investigaciones, estamos aquí con una solución inteligente y conveniente, es decir, Exchange Restore Software. Es demasiado fácil de manejar por todos los usuarios y restaurar cómodamente todos los datos del archivo PST a Exchange Server.
El software es demasiado simple de usar y se puede instalar fácilmente en todas las versiones de Windows. Con unos pocos clics, la herramienta puede restaurar los elementos del buzón de Exchange.
No es necesario que MS Outlook restaure los datos PST en Exchange. Todos los correos electrónicos, contactos, notas, calendarios, etc. se restauran desde el archivo PST a Exchange Server.
Todas las versiones de Outlook son compatibles con la herramienta, como Outlook 2019, 2016, 2013, 2010, 2007, etc. La herramienta proporciona varios filtros mediante los cuales se pueden restaurar los datos deseados desde un archivo PST a Exchange Server. El programa se puede instalar en todas las versiones de Windows como Windows 10, 8.1, 8, 7, XP, Vista, etc.
Descargue la versión de demostración del software de restauración de Exchange y analice el funcionamiento del software restaurando los primeros 50 elementos por carpeta.
No existe una solución manual para restaurar los buzones de correo de Exchange desde el archivo PST. Por lo tanto, hemos explicado una solución fácil e inteligente para restaurar datos de archivos PST en Exchange Server. Simplemente puede usar este software y restaurar todos los datos de PST a Exchange Server.
Más información:- https://www.datavare.com/software/exchange-restore.html
#intercambio de software de restauración #intercambio de restauración #buzón del servidor de intercambio #herramienta de restauración de intercambio
1621327800
As 2020 is coming to an end, let’s see it off in style. Our journey in the world of Graph Analytics, Graph Databases, Knowledge Graphs and Graph AI culminate.
The representation of the relationships among data, information, knowledge and --ultimately-- wisdom, known as the data pyramid, has long been part of the language of information science. Digital transformation has made this relevant beyond the confines of information science. COVID-19 has brought years’ worth of digital transformation in just a few short months.
In this new knowledge-based digital world, encoding and making use of business and operational knowledge is the key to making progress and staying competitive. So how do we go from data to information, and from information to knowledge? This is the key question Knowledge Connexions aims to address.
Graphs in all shapes and forms are a key part of this.
Knowledge Connexions is a visionary event featuring a rich array of technological building blocks to support the transition to a knowledge-based economy: Connecting data, people and ideas, building a global knowledge ecosystem.
The Year of the Graph will be there, in the workshop “From databases to platforms: the evolution of Graph databases”. George Anadiotis, Alan Morrison, Steve Sarsfield, Juan Sequeda and Steven Xi bring many years of expertise in the domain, and will analyze Graph Databases from all possible angles.
This is the first step in the relaunch of the Year of the Graph Database Report. Year of the Graph Newsletter subscribers just got a 25% discount code. To be always in the know, subscribe to the newsletter, and follow the newly launched Year of the Graph account on Twitter! In addition to getting the famous YotG news stream every day, you will also get a 25% discount code.
#database #machine learning #artificial intelligence #data science #graph databases #graph algorithms #graph analytics #emerging technologies #knowledge graphs #semantic technologies
1595924640
Parts of the world are still in lockdown, while others are returning to some semblance of normalcy. Either way, while the last few months have given some things pause, they have boosted others. It seems like developments in the world of Graphs are among those that have been boosted.
An abundance of educational material on all things graph has been prepared and delivered online, and is now freely accessible, with more on the way.
Graph databases have been making progress and announcements, repositioning themselves by a combination of releasing new features, securing additional funds, and entering strategic partnerships.
A key graph database technology, RDF*, which enables compatibility between RDF and property graph databases, is gaining momentum and tool support.
And more cutting edge research combining graph AI and knowledge graphs is seeing the light, too. Buckle up and enjoy some graph therapy.
Stanford’s series of online seminars featured some of the world’s leading experts on all things graph. If you missed it, or if you’d like to have an overview of what was said, you can find summaries for each lecture in this series of posts by Bob Kasenchak and Ahren Lehnert. Videos from the lectures are available here.
Stanford University’s computer science department is offering a free class on Knowledge Graphs available to the public. Stanford is also making recordings of the class available via the class website.
Another opportunity to get up to speed with educational material: The entire program of the course “Information Service Engineering” at KIT - Karlsruhe Institute of Technology, is delivered online and made freely available on YouTube. It includes topics such as ontology design, knowledge graph programming, basic graph theory, and more.
Knowledge representation as a prerequisite for knowledge graphs. Learn about knowledge representation, ontologies, RDF(S), OWL, SPARQL, etc.
Ontology may sound like a formal term, while knowledge graph is a more approachable one. But the 2 are related, and so is ontology and AI. Without a consistent, thoughtful approach to developing, applying, evolving an ontology, AI systems lack underpinning that would allow them to be smart enough to make an impact.
The ontology is an investment that will continue to pay off, argue Seth Earley and Josh Bernoff in Harvard Business Review, making the case for how businesses may benefit from a knowldge-centric approach
Even after multiple generations of investments and billions of dollars of digital transformations, organizations struggle to use data to improve customer service, reduce costs, and speed the core processes that provide competitive advantage. AI was supposed to help with that.
Besides AI, knowledge graphs have a part to play in the Cloud, too. State is good, and lack of support for Stateful Cloud-native applications is a roadblock for many enterprise use-cases, writes Dave Duggal.
Graph knowledge bases are an old idea now being revisited to model complex, distributed domains. Combining high-level abstraction with Cloud-native design principles offers efficient “Context-as-a-Service” for hydrating stateless services. Graph knowledge-based systems can enable composition of Cloud-native services into event-driven dataflow processes.
Kubernetes also touches upon Organizational Knowledge, and that may be modeled as a Knowledge Graph.
Extending graph knowledge bases to model distributed systems creates a new kind of information system, one intentionally designed for today’s IT challenges.
The Enterprise Knowledge Graph Foundation was recently established to define best practices and mature the marketplace for EKG adoption, with a launch webinar on June the 23rd.
The Foundation defines its mission as including adopting semantic standards, developing best practices for accelerated EKG deployment, curating a repository of reusable models and resources, building a mechanism for engagement and shared knowledge, and advancing the business cases for EKG adoption.
The Enterprise Knowledge Graph Maturity Model (EKG/MM) is the industry-standard definition of the capabilities required for an enterprise knowledge graph. It establishes standard criteria for measuring progress and sets out the practical questions that all involved stakeholders ask to ensure trust, confidence and usage flexibility of data. Each capability area provides a business summary denoting its importance, a definition of the added value from semantic standards and scoring criteria based on five levels of defined maturity.
Enterprise Knowledge Graphs is what the Semantic Web Company (SWC) and Ontotext have been about for a long time, too. Two of the vendors in this space that have been around for the longer time just announced a strategic partnership: Ontotext, a graph database and platform provider, meets SWC, a management and added value layer that sits on top.
SWC and Ontotext CEOs emphasize how their portfolios are complementary, while the press release states that the companies have implemented a seamless integration of the PoolParty Semantic Suite™ v.8 with the GraphDB™ and Ontotext Platform, which offers benefits for many use cases.
#database #artificial intelligence #graph databases #rdf #graph analytics #knowledge graph #graph technology