From 73616dc99181b89de0c3a241f0729bf7f51f5850 Mon Sep 17 00:00:00 2001 From: abefernan <44572727+abefernan@users.noreply.github.com> Date: Thu, 27 Jun 2024 11:34:16 +0200 Subject: [PATCH] Add nonce graphql helpers --- graphql/nonce.ts | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 graphql/nonce.ts diff --git a/graphql/nonce.ts b/graphql/nonce.ts new file mode 100644 index 0000000..8c32c04 --- /dev/null +++ b/graphql/nonce.ts @@ -0,0 +1,80 @@ +import { gql } from "graphql-request"; +import { z } from "zod"; +import { gqlClient } from "."; + +const DbNonceObjNonce = z.object({ nonce: z.number() }); +type DbNonceObjNonce = Readonly>; + +export const getNonce = async (chainId: string, address: string) => { + type QueryResponse = { readonly queryNonce: readonly DbNonceObjNonce[] }; + type QueryVariables = { readonly chainId: string; readonly address: string }; + + const { queryNonce } = await gqlClient.request( + gql` + query GetNonce($chainId: String!, $address: String!) { + queryNonce(filter: { chainId: { eq: $chainId }, address: { eq: $address } }) { + nonce + } + } + `, + { chainId, address }, + ); + + const dbNonceObj = queryNonce.length ? queryNonce[0] : null; + + if (dbNonceObj) { + DbNonceObjNonce.parse(dbNonceObj); + return dbNonceObj.nonce; + } + + type AddResponse = { readonly addNonce: { readonly nonce: readonly DbNonceObjNonce[] } }; + type AddVariables = { readonly chainId: string; readonly address: string }; + + const { addNonce } = await gqlClient.request( + gql` + mutation CreateNonce($chainId: String!, $address: String!) { + addNonce(input: { chainId: $chainId, address: $address, nonce: 1 }) { + nonce { + nonce + } + } + } + `, + { chainId, address }, + ); + + const createdNonceObj = addNonce.nonce[0]; + DbNonceObjNonce.parse(createdNonceObj); + + return createdNonceObj.nonce; +}; + +export const incrementNonce = async (chainId: string, address: string) => { + const dbNonce = await getNonce(chainId, address); + + type Response = { readonly updateNonce: { readonly nonce: readonly DbNonceObjNonce[] } }; + type Variables = { readonly chainId: string; readonly address: string; readonly nonce: number }; + + const { updateNonce } = await gqlClient.request( + gql` + mutation IncrementNonce($chainId: String!, $address: String!, $nonce: Int!) { + updateNonce( + input: { + filter: { chainId: { eq: $chainId }, address: { eq: $address } } + set: { nonce: $nonce } + } + ) { + nonce { + nonce + } + } + } + `, + { chainId, address, nonce: dbNonce + 1 }, + ); + + const updatedNonceObj = updateNonce.nonce[0]; + DbNonceObjNonce.parse(updatedNonceObj); + + return updatedNonceObj.nonce; +};