La dirección de la cuenta se muestra correctamente en la consola cuando se inicializa, pero se muestra indefinida cuando se llama a console.log(cuenta) desde otras funciones. Aquí está mi código.
var account; window.addEventListener('load', async () => { if (window.ethereum) { window.web3 = new Web3(ethereum); ethereum.autoRefreshOnNetworkChange = false; const accounts = await ethereum.enable(); account = accounts[0]; console.log(account); //here the account working properly. } }); var contractaddress = '0x26708Df214A65Dda444E61266642e6650F4e8923'; function get_request_details() { console.log(account); //here it is showing undefined } window.onload = get_request_details;El problema surgió porque la función se estaba ejecutando antes de que se pudiera realizar la inicialización y es por eso que modifiqué el código de la siguiente manera.
var account; window.addEventListener('load', async () => { if (window.ethereum) { window.web3 = new Web3(ethereum); ethereum.autoRefreshOnNetworkChange = false; const accounts = await ethereum.enable(); account = accounts[0]; console.log(account); //here the account working properly. get_request_details(); } }); var contractaddress = '0x26708Df214A65Dda444E61266642e6650F4e8923'; function get_request_details() { console.log(account); //here it is also working }Llamé a la función desde el evento asíncrono solo para que cuando la inicialización se realice después de que solo se ejecute la función.
No veo la variable contractaddress utilizada en ninguna parte. Así que aquí está mi opinión.
const get_request_details = function(account) { console.log(account); } const run_after_window_loaded = async function() { if (!window.ethereum) { return false; } window.web3 = new Web3(ethereum); ethereum.autoRefreshOnNetworkChange = false; const accounts = await ethereum.enable(); console.log(accounts); if(accounts.length > 0){ get_request_details(accounts[0]); } } window.addEventListener('DOMContentLoaded', async function(event) { await run_after_window_loaded(); });