The-Graph

如何搜尋交易的目的地

  • October 27, 2022

我定義了一個沒有合約地址的子圖

 - kind: ethereum/contract
   name: Trove
   network: mainnet
   source:
     abi: Trove
     startBlock: 5
   mapping:
     kind: ethereum/events
     apiVersion: 0.0.5
     language: wasm/assemblyscript
     entities:
       - Trove
     abis:
       - name: Trove
         file: ./artifacts/contracts/trove.sol/Trove.json
     eventHandlers:
       - event: OwnershipTransferred(indexed address,indexed address)
         handler: handleOwnershipTransferred
     file: ./mappings/trove.mapping.ts

這解析沒有問題。

在處理程序中,我想根據發出它的契約的地址從數據庫中獲取實體。處理程序非常簡潔:

export function handleOwnershipTransferred(event: OwnershipTransferred): void {
 let id: string = Address.fromString("0x0").toHex();
 if(event.transaction.to) {
   id = event.transaction.to.toHex();
 }
 let trove = Trove.load(id);
 if (trove == null) {
   return;
 }
 trove.owner = event.params.newOwner.toHex();
 trove.save();
}

編譯器拋出一個錯誤,說:

Compile subgraphERROR TS2322: Type '~lib/@graphprotocol/graph-ts/common/numbers/Address | null' is not assignable to type '~lib/@graphprotocol/graph-ts/common/collections/ByteArray'.

    id = event.transaction.to.toHex();

為了檢查我的語法,tofrom

export function handleOwnershipTransferred(event: OwnershipTransferred): void {
 let id: string = Address.fromString("0x0").toHex();
 if(event.transaction.from) {
   id = event.transaction.from.toHex();
 }
 let trove = Trove.load(id);
 if (trove == null) {
   return;
 }
 trove.owner = event.params.newOwner.toHex();
 trove.save();
}

這個版本的編譯就像一個魅力

對我來說,它看起來像類型錯誤,您可以嘗試直接將類型轉換為Address.

程式碼將是

import { Address } from "@graphprotocol/graph-ts";

export function handleOwnershipTransferred(event: OwnershipTransferred): void {
 const id = (event.transaction.to as Address).toHex();
 let trove = Trove.load(id);
 if (trove == null) {
   return;
 }
 trove.owner = event.params.newOwner.toHex();
 trove.save();
}

編譯的版本是:

 let to: Address | null = event.transaction.to;
 if(to) {
   const id: string = to.toHex();
   let trove = Trove.load(id);
   if (trove == null) {
     return;
   }
   trove.owner = event.params.newOwner.toHex();
   trove.save();
 }

引用自:https://ethereum.stackexchange.com/questions/138254