Last active
July 17, 2022 13:34
-
-
Save schmidsi/664c4bc8f8adc4fc402d26217950fdb6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql, useQuery } from '@apollo/client'; | |
import { useWeb3React } from '@web3-react/core'; | |
import { useEffect, useState } from 'react'; | |
import { useAppContext } from '../components/AppContextWrapper'; | |
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
export const useLastMints = () => { | |
const [eventHandlerBound, setEventHandlerBound] = useState(false); | |
const { library } = useWeb3React(); | |
const { getReadContract } = useAppContext(); | |
const { loading, error, data, refetch, networkStatus } = useQuery( | |
gql` | |
query LastMints($minBlock: Int!) { | |
tokens( | |
first: 100 | |
orderBy: timestamp | |
orderDirection: desc | |
block: { number_gte: $minBlock } | |
) { | |
id | |
owner { | |
id | |
} | |
uri | |
} | |
} | |
`, | |
{ | |
pollInterval: 60 * 1000, | |
// notifyOnNetworkStatusChange: true, | |
variables: { minBlock: 0 }, | |
// onError: (error) => { | |
// console.log('query erro', error); | |
// }, | |
}, // Fallback polling every minute | |
); | |
useEffect(() => { | |
if (library && !eventHandlerBound) { | |
const contract = getReadContract(library); | |
/* | |
Timings: | |
- Between transaction success in the frontend and the Mint-event here: ~200ms | |
- Refetch the query without the new mint: ~1000ms | |
*/ | |
contract.on('Transfer', async (_, __, ___, event) => { | |
console.timeEnd('New mint'); | |
console.time('Subgraph update'); | |
let rendered = false; | |
while (!rendered) { | |
try { | |
await refetch({ minBlock: event.blockNumber }); | |
rendered = true; | |
} catch (e) { | |
if (e.message.includes('has only indexed up to block number')) { | |
await wait(1000); | |
} else { | |
throw e; | |
} | |
} | |
} | |
console.timeEnd('Subgraph update'); | |
}); | |
setEventHandlerBound(true); | |
return () => { | |
contract.off('Transfer', refetch); | |
}; | |
} | |
}, [eventHandlerBound, getReadContract, library, refetch]); | |
const nfts = data?.tokens || []; | |
return { loading, error, nfts, networkStatus }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment