/ examples / postgres / entity_mode.js
entity_mode.js
 1  /* PostgreSQL Entity mode example
 2   *
 3   * This example shows how to use entity mode.
 4   * It listens for VRF requests and status changes from the Pragma's smart
 5   * contract on testnet.
 6   */
 7  
 8  const fromAddress =
 9    "0x693d551265f0be7ccb3c869c64b5920929caaf486497788d43cb37dd17d6be6";
10  
11  // RandomnessRequest event selector
12  const requestSelector =
13    "0x00e3e1c077138abb6d570b1a7ba425f5479b12f50a78a72be680167d4cf79c48";
14  
15  // RandomnessStatusChange event selector
16  const statusChangeSelector =
17    "0x015510b399942790499934b72bc68b883f0905dee5da5aa36e489c9ffb096b8c";
18  
19  export const config = {
20    streamUrl: "https://goerli.starknet.a5a.ch",
21    startingBlock: 908_100,
22    network: "starknet",
23    batchSize: 1,
24    finality: "DATA_STATUS_ACCEPTED",
25    filter: {
26      header: { weak: true },
27      events: [
28        {
29          fromAddress,
30          keys: [requestSelector],
31          includeTransaction: true,
32          includeReceipt: false,
33        },
34        {
35          fromAddress,
36          keys: [statusChangeSelector],
37          includeTransaction: true,
38          includeReceipt: false,
39        },
40      ],
41    },
42    sinkType: "postgres",
43    sinkOptions: {
44      tableName: "vrf_requests",
45      entityMode: true,
46    },
47  };
48  
49  export default function transform({ header, events }) {
50    const { timestamp } = header;
51    return events.flatMap(({ event, transaction }) => {
52      if (event.keys[0] == requestSelector) {
53        // Initialize request entity.
54        const requestId = BigInt(event.data[0]);
55        return {
56          insert: {
57            request_id: +requestId.toString(),
58            created_at: timestamp,
59            created_at_tx: transaction.meta.hash,
60            updated_at: timestamp,
61            updated_at_tx: transaction.meta.hash,
62            status: 0,
63          },
64        };
65      } else if (event.keys[0] == statusChangeSelector) {
66        // Update request entity.
67        const requestId = BigInt(event.data[1]);
68        const status = BigInt(event.data[2]);
69        return {
70          entity: {
71            request_id: +requestId.toString(),
72          },
73          update: {
74            status: +status.toString(),
75            updated_at: timestamp,
76            updated_at_tx: transaction.meta.hash,
77          },
78        };
79      } else {
80        // Do nothing.
81        return [];
82      }
83    });
84  }
85