BlockChain區塊鏈
  • 本書簡介
  • 區塊鏈運作原理
  • Bitcoin介紹
    • 簡介
    • Bitcoin其他知識
  • Bitcoin原理與實作
  • BitcoinJS
    • BTC 地址格式種類
    • 從 Mnemonic 轉為地址
  • Serverless 架構實作
  • Docker常用指令
  • ethereum初探
    • ethereum歷史
    • EVM
  • ethereum PoS 節點架設
  • ethereum(Docker)
  • ethereum(Geth)
    • Parity
  • ethereum(智能合約)
    • 合約測試 Unit Test
    • DAO
    • 可升級合約
    • 使用合約進行 multiswap
    • 合約安全
    • 開發工具
    • Hardhat 教學
      • Hardhat 寫測試
    • ERC-721 範例
      • 白名單機制
    • OpenZeppelin 合約 library
    • Truffle
    • 合約部屬
    • solidity 教學
  • ethereum(Dapp)
    • 相關 SDK
    • Multicall
    • Ethers.js 使用
    • Remix IDE
    • web3.js 使用
    • 在網頁上使用 web3 並操作區塊鏈
      • solidity筆記
  • Hyperledger Fabric
  • blockchainDB
  • 挖礦程式使用教學
    • 門羅幣/Monero (XMR)
  • Bitfinex API 使用
  • FTX API
  • CCXT 通用交易所 API
  • Solana 教學
  • Ethereum BigQuery
  • The Graph
    • yaml 定義
    • mapping 語法
    • Schema 定義
    • Query 範例
    • Unit test
  • DeFi 筆記
    • MEV 相關
    • Dex 聚合
    • Yearn
    • Curve
    • Uniswap
      • Swap 互動
    • AAVE、Compound
      • Compound 原理
      • AAVE 合約開發
Powered by GitBook
On this page
  • 可用型別
  • schema 範例
  • 相互引用
  • 一對多引用

Was this helpful?

  1. The Graph

Schema 定義

定義

Previousmapping 語法NextQuery 範例

Last updated 2 years ago

Was this helpful?

subgraph 將索引到的資料存入關連式資料庫中,所以我們需要定義 schema 來讓他知道資料如何儲存。

可用型別

每個 entity 都有一個 id ,類似於 primary key ,只能使用 Bytes! 或 String!

schema 範例

每個 entity 要加上 @entity 於後方預設都是 mutable 也就是可以在 mapping 邏輯改變數值,如果要固定不可被改動可使用 @entity(immutable: true) 下面的 TokenBalance 使用 token: Token! 來把 token 結構關聯到 TokenBalance 內,之後可以方便 query

type Token @entity(immutable: true) {
  id: Bytes!
}

type TokenBalance @entity {
  id: Bytes!
  amount: Int!
  token: Token!
}

相互引用

下面範例中 UserTxHistory 引用 Pair

type UserTxHistory @entity {
  id: ID!
  address: Bytes!, 
  address1: Bytes!, 
  type: String!, 
  value: BigDecimal!
  pairAddress: Bytes!, 
  pair: Pair!
  txHash: Bytes!
}

type Pair @entity {
  # pair address
  id: ID!
  ....
}  

之後於 mapping 檔案可以使用如下將其存入

import { Bundle, Token, Pair, UserTxHistory } from '../types/schema' // codegen 後產生

let user = UserTxHistory.load(address.toHexString())
let pair = Pair.load(pairAddress.toHexString())
user.pair = pair.id
user.save()

一對多引用

TokenBalance 本身納入了 token 結構,但 Token 結構本身也需要用到 TokenBalance 欄位,所以可以在 Token 的 tokenBalances 欄位使用 @derivedFrom,告知他一開始是從 token 引用的

type Token @entity(immutable: true) {
  id: Bytes!
  tokenBalances: [TokenBalance!]! @derivedFrom(field: "token")
}

type TokenBalance @entity {
  id: Bytes!
  amount: Int!
  token: Token!
}

https://thegraph.com/docs/en/developer/create-subgraph-hosted/#built-in-scalar-types