Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

94-event-tracking-add-mixpanel-event-tracking #241

Merged
merged 8 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,17 @@ export default [
message: 'DOM APIs are not available in background scripts',
},
],
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['ui/*', '**/ui/**'],
message: 'UI components/modules cannot be imported into background scripts',
},
],
},
],
},
},
];
15 changes: 9 additions & 6 deletions src/background/controller/provider/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import { TypedDataUtils, SignTypedDataVersion, normalize } from '@metamask/eth-s
import * as fcl from '@onflow/fcl';
import BigNumber from 'bignumber.js';
import { ethErrors } from 'eth-rpc-errors';
import { isHexString, intToHex } from 'ethereumjs-util';
import { intToHex } from 'ethereumjs-util';
import { ethers } from 'ethers';
import RLP from 'rlp';
import Web3 from 'web3';
import { stringToHex } from 'web3-utils';

import { ensureEvmAddressPrefix, isValidEthereumAddress } from '@/ui/utils/address';
import { signWithKey } from '@/ui/utils/modules/passkey.js';
import { ensureEvmAddressPrefix, isValidEthereumAddress } from '@/shared/utils/address';
import {
permissionService,
sessionService,
Expand All @@ -23,6 +21,9 @@ import { storage } from '../../webapi';
import BaseController from '../base';
import Wallet from '../wallet';

// eslint-disable-next-line import/order,no-restricted-imports
import { signWithKey } from '@/ui/utils/modules/passkey.js';

interface Web3WalletPermission {
// The name of the method corresponding to the permission
parentCapability: string;
Expand Down Expand Up @@ -69,6 +70,7 @@ function createAndEncodeCOAOwnershipProof(
return encodedData; // Convert the encoded data to a hexadecimal string for easy display or transmission
}

// Should not be in controller
async function signMessage(msgParams, opts = {}) {
const web3 = new Web3();
const textData = msgParams.data;
Expand Down Expand Up @@ -386,7 +388,8 @@ class ProviderController extends BaseController {
});
}
};

/*
// Should not be in controller
personalSign = async ({ data, approvalRes, session }) => {
if (!data.params) return;
const [string, from] = data.params;
Expand All @@ -400,7 +403,7 @@ class ProviderController extends BaseController {
});
return result;
};

*/
private _checkAddress = async (address) => {
return normalize(address).toLowerCase();
};
Expand Down
2 changes: 1 addition & 1 deletion src/background/controller/provider/rpcFlow.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ethErrors } from 'eth-rpc-errors';

import eventBus from '@/eventBus';
import { isValidEthereumAddress } from '@/ui/utils/address';
import { isValidEthereumAddress } from '@/shared/utils/address';
import {
keyringService,
notificationService,
Expand Down
17 changes: 9 additions & 8 deletions src/background/controller/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { getAuth } from 'firebase/auth';
import web3, { TransactionError } from 'web3';

import eventBus from '@/eventBus';
import { isValidEthereumAddress, withPrefix } from '@/shared/utils/address';
import { getHashAlgo, getSignAlgo } from '@/shared/utils/algo';
import {
keyringService,
Expand Down Expand Up @@ -43,13 +44,9 @@ import fetchConfig from 'background/utils/remoteConfig';
import { notification, storage } from 'background/webapi';
import { openIndexPage } from 'background/webapi/tab';
import { INTERNAL_REQUEST_ORIGIN, EVENTS, KEYRING_TYPE } from 'consts';
import placeholder from 'ui/FRWAssets/image/placeholder.png';
import { getStoragedAccount } from 'ui/utils';
import { isValidEthereumAddress, withPrefix } from 'ui/utils/address';
import { openInternalPageInTab } from 'ui/utils/webapi';

import { pk2PubKey, seed2PubKey, formPubKey } from '../../ui/utils/modules/passkey';
import { fclTestnetConfig, fclMainnetConfig } from '../fclConfig';
import placeholder from '../images/placeholder.png';
import type { CoinItem } from '../service/coinList';
import DisplayKeyring from '../service/keyring/display';
import type { NFTData, NFTModel, StorageInfo, WalletResponse } from '../service/networkModel';
Expand All @@ -58,10 +55,14 @@ import type { Account } from '../service/preference';
import { StorageEvaluator } from '../service/storage-evaluator';
import type { UserInfoStore } from '../service/user';
import defaultConfig from '../utils/defaultConfig.json';
import { getStoragedAccount } from '../utils/getStoragedAccount';

import BaseController from './base';
import provider from './provider';

// eslint-disable-next-line import/order,no-restricted-imports
import { pk2PubKey, seed2PubKey, formPubKey } from '@/ui/utils/modules/passkey.js';

interface Keyring {
type: string;
getAccounts(): Promise<string[]>;
Expand Down Expand Up @@ -287,7 +288,7 @@ export class WalletController extends BaseController {
await passwordService.clear();
sessionService.broadcastEvent('accountsChanged', []);
sessionService.broadcastEvent('lock');
openInternalPageInTab('addwelcome', true);
openIndexPage('addwelcome');
await this.switchNetwork(switchingTo);
};

Expand All @@ -301,7 +302,7 @@ export class WalletController extends BaseController {
await passwordService.clear();
sessionService.broadcastEvent('accountsChanged', []);
sessionService.broadcastEvent('lock');
openInternalPageInTab('reset', true);
openIndexPage('reset');
await this.switchNetwork(switchingTo);
};

Expand All @@ -316,7 +317,7 @@ export class WalletController extends BaseController {

sessionService.broadcastEvent('accountsChanged', []);
sessionService.broadcastEvent('lock');
openInternalPageInTab('restore', true);
openIndexPage('restore');
await this.switchNetwork(switchingTo);
};

Expand Down
Binary file added src/background/images/placeholder.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import {
} from 'firebase/auth';

import eventBus from '@/eventBus';
import { Message } from '@/shared/utils/messaging';
import type { WalletController } from 'background/controller/wallet';
import { EVENTS } from 'consts';
import { Message } from 'utils';

import { providerController, walletController } from './controller';
import { preAuthzServiceDefinition } from './controller/serviceDefinition';
Expand Down
13 changes: 9 additions & 4 deletions src/background/service/mixpanel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,35 @@ class MixpanelService {
this.initialized = true;
}
track<T extends keyof TrackingEvents>(eventName: T, properties?: TrackingEvents[T]) {
eventBus.emit('track_event', {
chrome.runtime.sendMessage({
msg: 'track_event',
eventName,
properties,
});
}

time<T extends keyof TrackingEvents>(eventName: T) {
eventBus.emit('track_time', {
chrome.runtime.sendMessage({
msg: 'track_time',
eventName,
});
}

identify(userId: string) {
if (!this.initialized) return;

eventBus.emit('track_user', {
chrome.runtime.sendMessage({
msg: 'track_user',
userId,
});
}

reset() {
if (!this.initialized) return;

eventBus.emit('track_reset');
chrome.runtime.sendMessage({
msg: 'track_reset',
});
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/background/service/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ import type { TokenInfo } from 'flow-native-token-registry';
import log from 'loglevel';

import { storage } from '@/background/webapi';
import { isValidEthereumAddress } from '@/shared/utils/address';
import { getStringFromHashAlgo, getStringFromSignAlgo } from '@/shared/utils/algo';
import { getPeriodFrequency } from '@/shared/utils/getPeriodFrequency';
import { createPersistStore, getScripts, findKeyAndInfo } from 'background/utils';
import { getFirbaseConfig, getFirbaseFunctionUrl } from 'background/utils/firebaseConfig';
import fetchConfig from 'background/utils/remoteConfig';
import { INITIAL_OPENAPI_URL, WEB_NEXT_URL } from 'consts';
import { isValidEthereumAddress } from 'ui/utils/address';

import { getPeriodFrequency } from '../../utils';
import { fclMainnetConfig, fclTestnetConfig } from '../fclConfig';

import {
Expand Down
6 changes: 4 additions & 2 deletions src/background/service/userWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ import * as fcl from '@onflow/fcl';
import { getApp } from 'firebase/app';
import { getAuth, signInAnonymously } from 'firebase/auth';

import { withPrefix } from '@/shared/utils/address';
import { getHashAlgo, getSignAlgo } from '@/shared/utils/algo';
import { withPrefix } from '@/ui/utils/address';
// eslint-disable-next-line no-restricted-imports
import { findAddressWithSeed, findAddressWithPK } from '@/ui/utils/modules/findAddressWithPK';
// eslint-disable-next-line no-restricted-imports
import { signWithKey, seed2PubKey } from '@/ui/utils/modules/passkey.js';
import wallet from 'background/controller/wallet';
import { keyringService, mixpanelTrack, openapiService } from 'background/service';
import { createPersistStore } from 'background/utils';
import { getStoragedAccount } from 'ui/utils';
import { getStoragedAccount } from 'background/utils/getStoragedAccount';

import { storage } from '../webapi';

Expand Down
30 changes: 30 additions & 0 deletions src/background/utils/getStoragedAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { storage } from '@/background/webapi';

export const getStoragedAccount = async () => {
const accountIndex = (await storage.get('currentAccountIndex')) || 0;
const currentId = (await storage.get('currentId')) || null;
const loggedInAccounts = (await storage.get('loggedInAccounts')) || [];
let account;

// Check if currentId is provided and valid
if (currentId !== null) {
// Find account with the currentId
account = loggedInAccounts.find((acc) => acc.id === currentId);

// If no account is found with currentId, default to accountIndex
if (!account) {
account = loggedInAccounts[accountIndex];
}
} else {
// If currentId is not provided, use accountIndex
account = loggedInAccounts[accountIndex];
}

if (!account) {
// Handle the case when no account is found
throw new Error('Account info not found.');
} else {
// Return account
return account;
}
};
2 changes: 1 addition & 1 deletion src/content-script/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { nanoid } from 'nanoid';
import { v4 as uuid } from 'uuid';

import { Message } from 'utils';
import { Message } from '@/shared/utils/messaging';

const channelName = nanoid();

Expand Down
6 changes: 5 additions & 1 deletion src/eventBus.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
type Listener = (params?: any) => void;

/**
* EventBus is a singleton class that allows for event-based communication between different parts of the application.
* It provides methods for emitting events, listening for events, and removing event listeners.
* IMPORTANT: This only works in one thread - either the background, content script, or UI. It does not work across threads.
*/
class EventBus {
events: Record<string, Listener[]> = {};

Expand Down
26 changes: 26 additions & 0 deletions src/shared/types/tracking-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,29 @@ export type TrackingEvents = {
methods: KeyType[]; // Array of providers used in the multi-backup, GoogleDrive, iCloud, Seed
};
};

export type TrackEventMessage<T extends keyof TrackingEvents = keyof TrackingEvents> = {
msg: 'track_event';
eventName: T;
properties?: TrackingEvents[T];
};

export type TrackUserMessage = {
msg: 'track_user';
userId: string;
};

export type TrackResetMessage = {
msg: 'track_reset';
};

export type TrackTimeMessage = {
msg: 'track_time';
eventName: keyof TrackingEvents;
};

export type TrackMessage =
| TrackEventMessage
| TrackUserMessage
| TrackResetMessage
| TrackTimeMessage;
7 changes: 4 additions & 3 deletions src/ui/utils/address.ts → src/shared/utils/address.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { AccountKey } from 'background/service/networkModel';
import HDWallet from 'ethereum-hdwallet';

import { type AccountKey } from 'background/service/networkModel';

export function sansPrefix(address) {
if (address == null) return null;
if (address === null) return null;
return address.replace(/^0x/, '').replace(/^Fx/, '');
}

export function withPrefix(address): string | null {
if (address == null) return null;
if (address === null) return null;
return '0x' + sansPrefix(address);
}

Expand Down
20 changes: 20 additions & 0 deletions src/shared/utils/getPeriodFrequency.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Period, PeriodFrequency } from '@/background/service/networkModel';

export const getPeriodFrequency = (period: Period): PeriodFrequency => {
switch (period) {
case Period.oneDay:
return PeriodFrequency.halfHour;
case Period.oneWeek:
return PeriodFrequency.oneHour;
case Period.oneMonth:
return PeriodFrequency.oneDay;
case Period.threeMonth:
return PeriodFrequency.oneDay;
case Period.oneYear:
return PeriodFrequency.threeDay;
case Period.all:
return PeriodFrequency.oneWeek;
default:
return PeriodFrequency.oneDay;
}
};
File renamed without changes.
19 changes: 19 additions & 0 deletions src/shared/utils/messaging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import BroadcastChannelMessage from './message/broadcastChannelMessage';
import PortMessage from './message/portMessage';

const Message = {
BroadcastChannelMessage,
PortMessage,
};

declare global {
const langLocales: Record<string, Record<'message', string>>;
}

const t = (name) => chrome.i18n.getMessage(name);

const format = (str, ...args) => {
return args.reduce((m, n) => m.replace('_s_', n), str);
};

export { Message, t, format };
2 changes: 1 addition & 1 deletion src/ui/FRWComponent/FRWChildProfile.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Box, Typography, Avatar } from '@mui/material';
import React, { useState, useEffect, useCallback } from 'react';

import { isValidEthereumAddress } from '@/shared/utils/address';
import { useWallet } from 'ui/utils';
import { isValidEthereumAddress } from 'ui/utils/address';

const tempEmoji = {
emoji: '🥥',
Expand Down
2 changes: 1 addition & 1 deletion src/ui/FRWComponent/FRWDropdownProfileCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import {
import { makeStyles } from '@mui/styles';
import React, { useState, useEffect, useCallback } from 'react';

import { isValidEthereumAddress } from '@/shared/utils/address';
import { useWallet, formatAddress, isEmoji } from 'ui/utils';
import { isValidEthereumAddress } from 'ui/utils/address';

const tempEmoji = {
emoji: '🥥',
Expand Down
Loading