stacker.news/api/resolvers/chainFee.js
Tom Smith 691818e779
[1124] - Use Mempool For Fee Rate (#1171)
* Use mempool for fee rate

* Add minor logic change

* Restore carousel items
2024-05-15 10:26:49 -05:00

37 lines
903 B
JavaScript

const cache = new Map()
const expiresIn = 1000 * 30 // 30 seconds in milliseconds
async function fetchChainFeeRate () {
const url = 'https://mempool.space/api/v1/fees/recommended'
const chainFee = await fetch(url)
.then((res) => res.json())
.then((body) => body.hourFee)
.catch((err) => {
console.error('fetchChainFee', err)
return 0
})
cache.set('fee', { fee: chainFee, createdAt: Date.now() })
return chainFee
}
async function getChainFeeRate () {
if (cache.has('fee')) {
const { fee, createdAt } = cache.get('fee')
const expired = createdAt + expiresIn < Date.now()
if (expired) fetchChainFeeRate().catch(console.error) // update cache
return fee
} else {
fetchChainFeeRate().catch(console.error)
}
return 0
}
export default {
Query: {
chainFee: async (parent, opts, ctx) => {
return await getChainFeeRate()
}
}
}