2023-09-12 15:56:02 +00:00
|
|
|
import lndService from 'ln-service'
|
2024-03-20 00:37:31 +00:00
|
|
|
import lnd from '@/api/lnd'
|
2024-08-01 00:44:08 +00:00
|
|
|
import { isServiceEnabled } from '@/lib/sndev'
|
2023-09-12 15:56:02 +00:00
|
|
|
|
|
|
|
const cache = new Map()
|
|
|
|
const expiresIn = 1000 * 30 // 30 seconds in milliseconds
|
|
|
|
|
|
|
|
async function fetchBlockHeight () {
|
|
|
|
let blockHeight = 0
|
2024-08-01 00:44:08 +00:00
|
|
|
if (!isServiceEnabled('payments')) return blockHeight
|
2023-09-12 15:56:02 +00:00
|
|
|
try {
|
|
|
|
const height = await lndService.getHeight({ lnd })
|
|
|
|
blockHeight = height.current_block_height
|
2024-08-13 14:48:30 +00:00
|
|
|
cache.set('block', { height: blockHeight, createdAt: Date.now() })
|
2023-09-12 15:56:02 +00:00
|
|
|
} catch (err) {
|
|
|
|
console.error('fetchBlockHeight', err)
|
|
|
|
}
|
|
|
|
return blockHeight
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getBlockHeight () {
|
|
|
|
if (cache.has('block')) {
|
|
|
|
const { height, createdAt } = cache.get('block')
|
|
|
|
const expired = createdAt + expiresIn < Date.now()
|
|
|
|
if (expired) fetchBlockHeight().catch(console.error) // update cache
|
|
|
|
return height // serve stale block height (this on the SSR critical path)
|
|
|
|
} else {
|
|
|
|
fetchBlockHeight().catch(console.error)
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
export default {
|
|
|
|
Query: {
|
|
|
|
blockHeight: async (parent, opts, ctx) => {
|
|
|
|
return await getBlockHeight()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|