Last active
July 20, 2023 13:43
-
-
Save fzn0x/28f8c8adfd2eebb1b43ef0a62b0b5143 to your computer and use it in GitHub Desktop.
Get Realtime Balance in web3.js | author using v1.3.6.rc-x, vue composition api. FREE TO MODIFY FOR YOUR OWN USE.
This file contains hidden or 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
/* | |
* Author : Muhammad Fauzan | fauzan121002 | |
* Web3.js v1.3.6 | |
* | |
* No License Used, Free to modify, commercial use and distribute. | |
*/ | |
import { defineComponent, useAsync, ref } from '@nuxtjs/composition-api' | |
export const useGetUserBalance = async () => { | |
try { | |
const data = window.web3.eth.getBalance( | |
window.web3.eth.currentProvider.selectedAddress | |
) | |
return window.web3.utils.fromWei(await data, 'ether') + ' ETH' | |
} catch (e) { console.error(e) } | |
} | |
export default defineComponent({ | |
setup() { | |
// using vue reactivity object | |
let userBalance = ref({ value: 0 }) | |
userBalance.value = useAsync(() => useGetUserBalance()) | |
window.web3.eth.getAccounts().then(() => { | |
return web3.eth.subscribe('newBlockHeaders', (err) => { | |
if (err) { | |
console.log(err) | |
} else { | |
userBalance.value = useAsync(() => useGetUserBalance()) | |
} | |
}) | |
}) | |
} | |
}); | |
isn't that gonna fire a RPC call on every newBlock. the balance wouldn't necessarily change on every new block.
is there a more efficient way?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/fauzan121002/nuxt-web3
Web3.js module integration for nuxt.js