Skip to content

Commit

Permalink
ref(useCurrentBlock.ts): Subscribe to blocks with subscribeNewHeads
Browse files Browse the repository at this point in the history
  • Loading branch information
hassnian committed Jan 23, 2025
1 parent 12d8047 commit afa5f80
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 22 deletions.
4 changes: 1 addition & 3 deletions composables/transaction/transactionOffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ export const getOfferCollectionId = (prefix: Prefix) => {

export const OFFER_MINT_PRICE = 5e8

export const SECONDS_PER_BLOCK = 12 // 12 sec/block
const BLOCKS_PER_HOUR = (3600 / SECONDS_PER_BLOCK) // 300 blocks/hr
export const BLOCKS_PER_DAY = BLOCKS_PER_HOUR * 24
export const BLOCKS_PER_DAY = 300 * 24 // 12sec /block --> 300blocks/hr

async function execMakingOffer(item: ActionOffer, api: ApiPromise, executeTransaction) {
const { accountId } = useAuth()
Expand Down
28 changes: 9 additions & 19 deletions composables/useCurrentBlock.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,27 @@
import { SECONDS_PER_BLOCK } from '@/composables/transaction/transactionOffer'

const currentBlock = ref(0)
const interval = ref<NodeJS.Timeout>()
const subscription = ref()
const syncCount = ref(0)

export default function useCurrentBlock() {
const { apiInstance } = useApi()

const getCurrentBlock = async () => {
const api = await apiInstance.value
const { number } = await api.rpc.chain.getHeader()
return number.toNumber()
}

const syncCurrentBlock = async () => {
currentBlock.value = await getCurrentBlock()
}

syncCount.value++

if (syncCount.value === 1) {
if (!subscription.value) {
onBeforeMount(async () => {
await syncCurrentBlock()
interval.value = setInterval(syncCurrentBlock, SECONDS_PER_BLOCK * 1000)
const api = await apiInstance.value
subscription.value = await api.rpc.chain.subscribeNewHeads((lastHeader) => {
currentBlock.value = lastHeader.number.toNumber()
})
})
}

onBeforeUnmount(() => {
syncCount.value--

if (syncCount.value === 0 && interval.value) {
clearInterval(interval.value)
interval.value = undefined
if (syncCount.value === 0 && subscription.value) {
subscription.value()
subscription.value = undefined
}
})

Expand Down

0 comments on commit afa5f80

Please sign in to comment.