The graph - 2

정태수·2023년 7월 24일
1

TheGraph

목록 보기
2/2
post-thumbnail

실행순서

  1. npm install -g @graphprotocol/graph-cli
  1. graph init --product hosted-service jungtaesu/workingtest

본인의 상황에 맞게 알맞은 환경을 선택해주시면 됩니다.

저는 폴리곤을 사용할거라 matic 선택을 해주면 이렇게

  1. 사용할 contract address
  2. contract name
  3. 컨트랙트 이벤트를 entity로 사용할 건지 여부
    정하게 되면 프로젝트 생성이 됩니다.

  1. cd 폴더
  2. graph codegen && graph build

build 폴더가 생성이 되네요.

  1. graph auth --product hosted-service 'your deploy key'

그래프 배포를 위해선 권한을 얻고 deploy를 해야합니다.

  1. graph deploy --product hosted-service jungtaesu/workingtest

웹에서 제가 배포한 그래프를 확인할 수 있었습니다.
아직 만든지 얼마안되서 syncing 중인 걸 볼수가 있네요.
그래프가 다루는 데이터양이 많을수록 오래 걸리는 것 같아요.

제가 직접 작성한 contract에 대해서도 graphql에 subgraph를 배포하고자 하려고 했는데

✖ Failed to fetch ABI from Etherscan: ABI not found, try loading it from a local file
✖ Failed to fetch Start Block: Failed to fetch contract creation transaction hash

abi 파일이나 smart contract에 event 를 발생시키는 부분이 없기 때문에 발생하는 에러.

즉 이벤트 발생 안함 -> eventHandler 불가

 event DonationReceived(uint256 campaignId, address donator, uint256 amount);

//이런 식으로 이벤트를 스마트 컨트랙트에 추가해주었음

어떻게 subgraph.yaml 파일과 schema.graphql 파일이 생성되었는지 살펴보면

specVersion: 0.0.5
schema:
  file: ./schema.graphql
dataSources:
  - kind: ethereum
    name: crowdfunding
    network: matic
    source:
      address: "0x561aC79bD080B6e541c3bdacdcc14c5B77A87691"
      abi: crowdfunding
      startBlock: 045448522
    mapping:
      kind: ethereum/events
      apiVersion: 0.0.7
      language: wasm/assemblyscript
      entities:
        - CampaignCreated
        - DonationReceived
      abis:
        - name: crowdfunding
          file: ./abis/crowdfunding.json
      eventHandlers:
        - event: CampaignCreated(uint256,address,string,uint256)
          handler: handleCampaignCreated
        - event: DonationReceived(uint256,address,uint256)
          handler: handleDonationReceived
      file: ./src/crowdfunding.ts

이벤트가 사용하는 파라미터를 사용

type CampaignCreated @entity(immutable: true) {
  id: Bytes!
  campaignId: BigInt! # uint256
  owner: Bytes! # address
  title: String! # string
  target: BigInt! # uint256
  blockNumber: BigInt!
  blockTimestamp: BigInt!
  transactionHash: Bytes!
}

type DonationReceived @entity(immutable: true) {
  id: Bytes!
  campaignId: BigInt! # uint256
  donator: Bytes! # address
  amount: BigInt! # uint256
  blockNumber: BigInt!
  blockTimestamp: BigInt!
  transactionHash: Bytes!
}

schema.graphql 같은 경우 함수에서 사용한 변수나 파라미터들을 적당히 가져와서 entitiy에 넣어준 듯하다.

웹에서 확인한 entity 모습과 event 발생시에 데이터가 잘 저장된 모습을 볼 수 있다.

info logs 살펴보면 handler: handleDonationReceived 내가 생성한 이벤트로 인해 trigger 된 것을 볼수 있다.
블록넘버 역시 폴리곤스캔에서 확인한대로 45450551 이 넘버에서 로그가 찍힌 것 을 볼수 있다.

profile
프론트엔드 개발자

1개의 댓글

comment-user-thumbnail
2023년 7월 24일

잘 봤습니다. 좋은 글 감사합니다.

답글 달기