Skip to content

Commit

Permalink
Merge branch 'main' into feat/CP-9907_logo-rebrand-change
Browse files Browse the repository at this point in the history
  • Loading branch information
vvava committed Feb 14, 2025
2 parents e51394d + cea1f31 commit 4829016
Show file tree
Hide file tree
Showing 15 changed files with 440 additions and 232 deletions.
3 changes: 2 additions & 1 deletion manifest/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"notifications",
"tabs",
"scripting",
"identity"
"identity",
"alarms"
],
"host_permissions": ["file://*/*", "http://*/*", "https://*/*"],
"oauth2": {
Expand Down
10 changes: 1 addition & 9 deletions src/background/connections/ConnectionService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import browser, { Runtime } from 'webextension-polyfill';
import {
CONTENT_SCRIPT,
EXTENSION_SCRIPT,
KEEPALIVE_SCRIPT,
} from '@src/common';
import { CONTENT_SCRIPT, EXTENSION_SCRIPT } from '@src/common';
import { container, singleton } from 'tsyringe';
import { DAppConnectionController } from './dAppConnection/DAppConnectionController';
import { ConnectionController } from './models';
import { KeepaliveConnectionController } from './keepaliveConnection/KeepaliveConnectionController';
import { ExtensionConnectionController } from './extensionConnection/ExtensionConnectionController';
import { CallbackManager } from '../runtime/CallbackManager';

Expand Down Expand Up @@ -46,10 +41,7 @@ export class ConnectionService {
connectionController = container.resolve(ExtensionConnectionController);
} else if (connection.name === CONTENT_SCRIPT) {
connectionController = container.resolve(DAppConnectionController);
} else if (connection.name === KEEPALIVE_SCRIPT) {
connectionController = container.resolve(KeepaliveConnectionController);
}

connectionController?.connect(connection);

return connectionController;
Expand Down

This file was deleted.

35 changes: 22 additions & 13 deletions src/background/services/lock/LockService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ import {
LOCK_TIMEOUT,
SessionAuthData,
SESSION_AUTH_DATA_KEY,
AlarmsEvents,
} from './models';
import { OnAllExtensionClosed } from '@src/background/runtime/lifecycleCallbacks';

@singleton()
export class LockService {
export class LockService implements OnAllExtensionClosed {
private eventEmitter = new EventEmitter();

private _locked = true;

private lockCheckInterval?: any;
#autoLockInMinutes = 30;

public get locked(): boolean {
return this._locked;
Expand All @@ -28,6 +30,15 @@ export class LockService {
) {}

async activate() {
chrome.runtime.onConnect.addListener(() => {
chrome.alarms.clear(AlarmsEvents.AUTO_LOCK);
});

chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === AlarmsEvents.AUTO_LOCK) {
this.lock();
}
});
const authData =
await this.storageService.loadFromSessionStorage<SessionAuthData>(
SESSION_AUTH_DATA_KEY,
Expand All @@ -43,7 +54,14 @@ export class LockService {
}

await this.unlock(authData.password);
this.startAutoLockInterval(authData?.loginTime);
}

onAllExtensionsClosed(): void | Promise<void> {
if (!this._locked) {
chrome.alarms.create(AlarmsEvents.AUTO_LOCK, {
periodInMinutes: this.#autoLockInMinutes,
});
}
}

async unlock(password: string) {
Expand Down Expand Up @@ -78,16 +96,6 @@ export class LockService {
await this.storageService.changePassword(oldPassword, newPassword);
}

private startAutoLockInterval(loginTime: number) {
const timeToLock = loginTime + LOCK_TIMEOUT;
this.lockCheckInterval = setInterval(() => {
if (Date.now() > timeToLock) {
clearInterval(this.lockCheckInterval);
this.lock();
}
}, 60000);
}

async verifyPassword(password: string): Promise<boolean> {
const authData =
await this.storageService.loadFromSessionStorage<SessionAuthData>(
Expand All @@ -104,6 +112,7 @@ export class LockService {
this.eventEmitter.emit(LockEvents.LOCK_STATE_CHANGED, {
isUnlocked: false,
});
chrome.alarms.clear(AlarmsEvents.AUTO_LOCK);
}

addListener(
Expand Down
4 changes: 4 additions & 0 deletions src/background/services/lock/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ export enum LockEvents {
LOCK_STATE_CHANGED = 'LockServiceEvents:Lock',
}

export enum AlarmsEvents {
AUTO_LOCK = 'auto-lock',
}

export interface LockStateChangedEventPayload {
isUnlocked: boolean;
}
19 changes: 2 additions & 17 deletions src/contentscript.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CONTENT_SCRIPT, KEEPALIVE_SCRIPT } from './common';
import browser, { Runtime } from 'webextension-polyfill';
import { CONTENT_SCRIPT } from './common';
import browser from 'webextension-polyfill';
import PortConnection from './background/utils/messaging/PortConnection';
import onPageActivated from './background/providers/utils/onPageActivated';
import AutoPairingPostMessageConnection from './background/utils/messaging/AutoPairingPostMessageConnection';
Expand Down Expand Up @@ -30,21 +30,6 @@ function setupStream() {
backgroundConnection.dispose();
});

let backgroundKeepaliveConnection: Runtime.Port | null = null;

function keepAlive() {
if (backgroundKeepaliveConnection) return;
backgroundKeepaliveConnection = browser.runtime.connect({
name: KEEPALIVE_SCRIPT,
});
backgroundKeepaliveConnection?.onDisconnect.addListener(() => {
backgroundKeepaliveConnection = null;
keepAlive();
});
}

keepAlive();

backgroundConnection.on('disconnect', () => {
console.log('reconnecting...');
setupStream();
Expand Down
10 changes: 10 additions & 0 deletions src/contexts/SwapProvider/SwapProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,16 @@ jest.mock('react-i18next', () => ({
}));

jest.mock('ethers');
jest.mock('@avalabs/core-k2-components', () => ({
toast: {
success: jest.fn(),
loading: jest.fn(),
dismiss: jest.fn(),
error: jest.fn(),
custom: jest.fn(),
remove: jest.fn(),
},
}));

describe('contexts/SwapProvider', () => {
const connectionContext = {
Expand Down
65 changes: 52 additions & 13 deletions src/contexts/SwapProvider/SwapProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext, useCallback, useContext, useMemo } from 'react';
import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
import type { JsonRpcBatchInternal } from '@avalabs/core-wallets-sdk';
import { TransactionParams } from '@avalabs/evm-module';
import { resolve } from '@avalabs/core-utils-sdk';
Expand Down Expand Up @@ -45,6 +45,8 @@ import { assert, assertPresent } from '@src/utils/assertions';
import { CommonError } from '@src/utils/errors';
import { useWalletContext } from '../WalletProvider';
import { SecretType } from '@src/background/services/secrets/models';
import { toast } from '@avalabs/core-k2-components';
import { SwapPendingToast } from '@src/pages/Swap/components/SwapPendingToast';

export const SwapContext = createContext<SwapContextAPI>({} as any);

Expand All @@ -63,6 +65,7 @@ export function SwapContextProvider({ children }: { children: any }) {
forceShowTokensWithoutBalances: true,
disallowedAssets: DISALLOWED_SWAP_ASSETS,
});
const pendingToastIdRef = useRef('');

const paraswap = useMemo(
() => new ParaSwap(ChainId.AVALANCHE_MAINNET_ID, undefined, new Web3()),
Expand Down Expand Up @@ -273,11 +276,23 @@ export function SwapContextProvider({ children }: { children: any }) {
.div(10 ** destDecimals)
.toString();

const notificationText = isSuccessful
? t('Swap transaction succeeded! 🎉')
: t('Swap transaction failed! ❌');

toast.remove(pendingToastIdRef.current);

if (isSuccessful) {
toast.success(notificationText);
}

if (!isSuccessful) {
toast.error(notificationText);
}

browser.notifications.create({
type: 'basic',
title: isSuccessful
? t('Swap transaction succeeded! 🎉')
: t('Swap transaction failed! ❌'),
title: notificationText,
iconUrl: '../../../../images/icon-192.png',
priority: 2,
message: isSuccessful
Expand Down Expand Up @@ -457,6 +472,17 @@ export function SwapContextProvider({ children }: { children: any }) {
swapTxHash = txHash;
}

const toastId = toast.custom(
<SwapPendingToast onDismiss={() => toast.remove(toastId)}>
{t('Swap pending...')}
</SwapPendingToast>,

{
duration: Infinity,
},
);
pendingToastIdRef.current = toastId;

notifyOnSwapResult({
provider: avaxProviderC,
txHash: swapTxHash,
Expand All @@ -470,15 +496,16 @@ export function SwapContextProvider({ children }: { children: any }) {
});
},
[
activeAccount,
isFlagEnabled,
activeNetwork,
networkFee,
activeAccount,
avaxProviderC,
getSwapTxProps,
buildTx,
networkFee,
request,
t,
notifyOnSwapResult,
getSwapTxProps,
isFlagEnabled,
request,
],
);

Expand Down Expand Up @@ -569,6 +596,17 @@ export function SwapContextProvider({ children }: { children: any }) {
}),
);

const toastId = toast.custom(
<SwapPendingToast onDismiss={() => toast.remove(toastId)}>
{t('Swap pending...')}
</SwapPendingToast>,

{
duration: Infinity,
},
);
pendingToastIdRef.current = toastId;

if (signError || !swapTxHash) {
return throwError(signError);
}
Expand All @@ -586,14 +624,15 @@ export function SwapContextProvider({ children }: { children: any }) {
});
},
[
activeAccount,
activeNetwork,
avaxProviderC,
buildTx,
networkFee,
activeAccount,
avaxProviderC,
getSwapTxProps,
request,
t,
notifyOnSwapResult,
getSwapTxProps,
buildTx,
],
);

Expand Down
Loading

0 comments on commit 4829016

Please sign in to comment.