diff --git a/.changeset/beige-olives-dress.md b/.changeset/beige-olives-dress.md new file mode 100644 index 0000000000..b975434c46 --- /dev/null +++ b/.changeset/beige-olives-dress.md @@ -0,0 +1,5 @@ +--- +"fuels-wallet": patch +--- + +fix: auto-update in background to wait for update to be downloaded diff --git a/packages/app/src/systems/CRX/background/actions/autoUpdate.ts b/packages/app/src/systems/CRX/background/actions/autoUpdate.ts index 109afd8f21..5713c837a7 100644 --- a/packages/app/src/systems/CRX/background/actions/autoUpdate.ts +++ b/packages/app/src/systems/CRX/background/actions/autoUpdate.ts @@ -11,28 +11,62 @@ async function isOpen() { return isOpen; } -async function runVersionCheck() { +async function getLatestVersion() { const latestVersion = await fetch(VITE_CRX_VERSION_API) .then((res) => res.json()) // If fails to fetch the version return a empty object .catch(() => ({})); - const version = latestVersion[WALLET_NAME] || APP_VERSION; + return latestVersion[WALLET_NAME] || APP_VERSION; +} + +async function runVersionCheck() { + const version = await getLatestVersion(); // If app version is greater than the one on the release API ignores the check if (compareVersions(APP_VERSION, version) > -1) return; if (await isOpen()) return; // Request update check and reload if available - console.log('[FUEL WALLET] Checking for updates...'); + console.debug('[FUEL WALLET] Checking for updates...'); chrome.runtime.requestUpdateCheck((details) => { if (details === 'update_available') { console.log('[FUEL WALLET] Update available reload application...'); - chrome.runtime.reload(); + // Remove the alarm to check for updates until next reload + chrome.alarms.clear('autoUpdate'); + return; } + console.debug('[FUEL WALLET] No update available', details); }); } -chrome.alarms.create('autoUpdate', { periodInMinutes: 5 }); +async function reloadWallet() { + if (await isOpen()) { + console.debug('[FUEL WALLET] Wallet is open, waiting 5 minutes...'); + // If the wallet is open, wait 5 minutes and try again + chrome.alarms.create('reloadWallet', { delayInMinutes: 5 }); + return; + } + // Check if reload already happened + const version = await getLatestVersion(); + if (APP_VERSION === version) { + chrome.alarms.clear('reloadWallet'); + return; + } + chrome.runtime.reload(); +} + +// Once the app is updated reload the wallet +chrome.runtime.onUpdateAvailable.addListener(() => reloadWallet()); chrome.alarms.onAlarm.addListener(async (alarm) => { - if (alarm.name === 'autoUpdate') { - runVersionCheck(); + switch (alarm.name) { + case 'autoUpdate': + runVersionCheck(); + break; + case 'reloadWallet': + reloadWallet(); + break; + default: + break; } }); + +// Register alarms to check for updates and reload the wallet +chrome.alarms.create('autoUpdate', { periodInMinutes: 10 });