编写智能合约时,通常状态的变化是通过触发一个事件来表达,The Graph则是捕捉区块链事件并提供一个查询事件的GraphQL接口,让我们可以方便的跟踪数据的变化。 实际上很多 DEFI 协议及都是The Graph来基于查询数据。
https://thegraph.academy/developers/local-development/
我们以此教程为基础做出一下额外的补充。
工具准备:nodejs、yarn、docker、truffle、graph-cli
1. 合约开发与部署
-
合约的开发环境搭建
npm install -g truffle ganache-cli
-
合约编写
该合约为手写的测试合约,主要定义了两个事件,PairCreated和AddLiquidity。我们用thegarph来监听以下的事件。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Pair{
string private _name;
uint private _liquidity;
constructor(string memory name){
_name = name;
}
function addLiquidity(uint amount) public {
_liquidity+=amount;
}
function getLiquidity() public view returns(uint){
return _liquidity;
}
function getName() public view returns