Skip to content

Commit

Permalink
Merge pull request #1013 from madfish-solutions/TW-1127-track-users-a…
Browse files Browse the repository at this point in the history
…ddresses-who-view-ads-on-external-links

TW-1127 Add account PKH to 'External links activity' event
  • Loading branch information
lourenc authored Oct 31, 2023
2 parents bbb8097 + 1e7fcfb commit 270ce74
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 40 deletions.
25 changes: 18 additions & 7 deletions src/app/hooks/use-user-analytics-and-ads-settings.hook.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';

import { useAnalytics } from 'lib/analytics';
import { WEBSITES_ANALYTICS_ENABLED } from 'lib/constants';
import { AnalyticsEventCategory } from 'lib/temple/analytics-types';
import { useAccountPkh } from 'lib/temple/front';
import { usePassiveStorage } from 'lib/temple/front/storage';

import { usePassiveStorage } from '../../lib/temple/front/storage';
import { useShouldShowPartnersPromoSelector } from '../store/partners-promotion/selectors';
import { useAnalyticsEnabledSelector } from '../store/settings/selectors';

const WEBSITES_ANALYTICS_ENABLED = 'WEBSITES_ANALYTICS_ENABLED';

export const useUserAnalyticsAndAdsSettings = () => {
const { trackEvent } = useAnalytics();
const isAnalyticsEnabled = useAnalyticsEnabledSelector();
const isAdsEnabled = useShouldShowPartnersPromoSelector();

const [, setIsWebsitesAnalyticsEnabled] = usePassiveStorage(WEBSITES_ANALYTICS_ENABLED);
const prevWebsiteAnalyticsEnabledRef = useRef(isAnalyticsEnabled && isAdsEnabled);
const accountPkh = useAccountPkh();

useEffect(() => {
const isAnalyticsAndAdsEnabled = isAnalyticsEnabled && isAdsEnabled;
const shouldEnableAnalyticsAndAds = isAnalyticsEnabled && isAdsEnabled;

setIsWebsitesAnalyticsEnabled(shouldEnableAnalyticsAndAds);

setIsWebsitesAnalyticsEnabled(isAnalyticsAndAdsEnabled);
}, [isAnalyticsEnabled, isAdsEnabled, setIsWebsitesAnalyticsEnabled]);
if (shouldEnableAnalyticsAndAds && !prevWebsiteAnalyticsEnabledRef.current) {
trackEvent('AnalyticsAndAdsEnabled', AnalyticsEventCategory.General, { accountPkh });
}
prevWebsiteAnalyticsEnabledRef.current = shouldEnableAnalyticsAndAds;
}, [isAnalyticsEnabled, isAdsEnabled, setIsWebsitesAnalyticsEnabled, trackEvent, accountPkh]);
};
43 changes: 30 additions & 13 deletions src/app/pages/NewWallet/setWalletPassword/SetWalletPassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import {
setOnRampPossibilityAction
} from 'app/store/settings/actions';
import { AnalyticsEventCategory, TestIDProps, useAnalytics } from 'lib/analytics';
import { WEBSITES_ANALYTICS_ENABLED } from 'lib/constants';
import { T, t } from 'lib/i18n';
import { putToStorage } from 'lib/storage';
import { useTempleClient } from 'lib/temple/front';
import PasswordStrengthIndicator, { PasswordValidation } from 'lib/ui/PasswordStrengthIndicator';
import { navigate } from 'lib/woozie';
Expand Down Expand Up @@ -58,16 +60,22 @@ export const SetWalletPassword: FC<SetWalletPasswordProps> = ({

const dispatch = useDispatch();

const setAnalyticsEnabled = (analyticsEnabled: boolean) => dispatch(setIsAnalyticsEnabledAction(analyticsEnabled));
const setAdsViewEnabled = (adsViewEnabled: boolean) => {
if (adsViewEnabled) {
dispatch(setAdsBannerVisibilityAction(false));
dispatch(togglePartnersPromotionAction(true));
} else {
dispatch(setAdsBannerVisibilityAction(true));
dispatch(togglePartnersPromotionAction(false));
}
};
const setAnalyticsEnabled = useCallback(
(analyticsEnabled: boolean) => dispatch(setIsAnalyticsEnabledAction(analyticsEnabled)),
[dispatch]
);
const setAdsViewEnabled = useCallback(
(adsViewEnabled: boolean) => {
if (adsViewEnabled) {
dispatch(setAdsBannerVisibilityAction(false));
dispatch(togglePartnersPromotionAction(true));
} else {
dispatch(setAdsBannerVisibilityAction(true));
dispatch(togglePartnersPromotionAction(false));
}
},
[dispatch]
);

const { setOnboardingCompleted } = useOnboardingProgress();

Expand Down Expand Up @@ -128,17 +136,24 @@ export const SetWalletPassword: FC<SetWalletPasswordProps> = ({
: data.password
: data.password;
try {
const shouldEnableAnalytics = Boolean(data.analytics);
setAdsViewEnabled(data.viewAds);
setAnalyticsEnabled(!!data.analytics);
setAnalyticsEnabled(shouldEnableAnalytics);
const shouldEnableWebsiteAnalytics = data.viewAds && shouldEnableAnalytics;
await putToStorage(WEBSITES_ANALYTICS_ENABLED, shouldEnableWebsiteAnalytics);

setOnboardingCompleted(data.skipOnboarding!);

await registerWallet(password!, formatMnemonic(seedPhrase));
const accountPkh = await registerWallet(password!, formatMnemonic(seedPhrase));
trackEvent(
data.skipOnboarding ? 'OnboardingSkipped' : 'OnboardingNotSkipped',
AnalyticsEventCategory.General,
undefined,
data.analytics
);
if (shouldEnableWebsiteAnalytics) {
trackEvent('AnalyticsAndAdsEnabled', AnalyticsEventCategory.General, { accountPkh }, data.analytics);
}
navigate('/loading');
!ownMnemonic && dispatch(setOnRampPossibilityAction(true));
dispatch(shouldShowNewsletterModalAction(true));
Expand All @@ -154,11 +169,13 @@ export const SetWalletPassword: FC<SetWalletPasswordProps> = ({
isKeystorePasswordWeak,
ownMnemonic,
keystorePassword,
setAdsViewEnabled,
setAnalyticsEnabled,
setOnboardingCompleted,
registerWallet,
seedPhrase,
trackEvent
trackEvent,
dispatch
]
);

Expand Down
7 changes: 4 additions & 3 deletions src/contentScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ if (window.frameElement === null) {
let oldHref = '';

const trackUrlChange = () => {
if (oldHref !== window.parent.location.href) {
oldHref = window.parent.location.href;
const newHref = window.parent.location.href;
if (oldHref !== newHref) {
oldHref = newHref;

browser.runtime.sendMessage({
type: ContentScriptType.ExternalLinksActivity,
url: window.parent.location.href
url: newHref
});
}
};
Expand Down
4 changes: 4 additions & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export enum ContentScriptType {
ExternalLinksActivity = 'ExternalLinksActivity'
}

export const WEBSITES_ANALYTICS_ENABLED = 'WEBSITES_ANALYTICS_ENABLED';

export const ACCOUNT_PKH_STORAGE_KEY = 'account_publickeyhash';
4 changes: 3 additions & 1 deletion src/lib/temple/back/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,10 @@ export async function isDAppEnabled() {

export function registerNewWallet(password: string, mnemonic?: string) {
return withInited(async () => {
await Vault.spawn(password, mnemonic);
const accountPkh = await Vault.spawn(password, mnemonic);
await unlock(password);

return accountPkh;
});
}

Expand Down
13 changes: 9 additions & 4 deletions src/lib/temple/back/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { clearAsyncStorages } from 'lib/temple/reset';
import { TempleMessageType, TempleRequest, TempleResponse } from 'lib/temple/types';
import { getTrackedUrl } from 'lib/utils/url-track/get-tracked-url';

import { ContentScriptType } from '../../constants';
import { ACCOUNT_PKH_STORAGE_KEY, ContentScriptType } from '../../constants';
import * as Actions from './actions';
import * as Analytics from './analytics';
import { intercom } from './defaults';
Expand Down Expand Up @@ -50,8 +50,8 @@ const processRequest = async (req: TempleRequest, port: Runtime.Port): Promise<T
};

case TempleMessageType.NewWalletRequest:
await Actions.registerNewWallet(req.password, req.mnemonic);
return { type: TempleMessageType.NewWalletResponse };
const accountPkh = await Actions.registerNewWallet(req.password, req.mnemonic);
return { type: TempleMessageType.NewWalletResponse, accountPkh };

case TempleMessageType.UnlockRequest:
await Actions.unlock(req.password);
Expand Down Expand Up @@ -249,7 +249,12 @@ browser.runtime.onMessage.addListener(msg => {
const url = getTrackedUrl(msg.url);

if (url) {
Analytics.client.track('External links activity', { url });
browser.storage.local
.get(ACCOUNT_PKH_STORAGE_KEY)
.then(({ [ACCOUNT_PKH_STORAGE_KEY]: accountPkh }) =>
Analytics.client.track('External links activity', { url, accountPkh })
)
.catch(console.error);
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/lib/temple/back/vault/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ export class Vault {
return SessionStore.removePassHash();
}

/**
* Creates a new wallet and saves it securely.
* @param password Password for encryption
* @param mnemonic Seed phrase
* @returns Initial account address
*/
static async spawn(password: string, mnemonic?: string) {
return withError('Failed to create wallet', async () => {
if (!mnemonic) {
Expand Down Expand Up @@ -121,6 +127,8 @@ export class Vault {
passKey
);
await savePlain(migrationLevelStrgKey, MIGRATIONS.length);

return accPublicKeyHash;
});
}

Expand Down
2 changes: 2 additions & 0 deletions src/lib/temple/front/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ export const [TempleClientProvider, useTempleClient] = constate(() => {
});
assertResponse(res.type === TempleMessageType.NewWalletResponse);
clearLocalStorage(['onboarding', 'analytics']);

return res.accountPkh;
}, []);

const unlock = useCallback(async (password: string) => {
Expand Down
1 change: 1 addition & 0 deletions src/lib/temple/front/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export {
useAllAccounts,
useSetAccountPkh,
useAccount,
useAccountPkh,
useSettings,
useTezos,
useChainId,
Expand Down
5 changes: 4 additions & 1 deletion src/lib/temple/front/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { TezosToolkit } from '@taquito/taquito';
import { Tzip16Module } from '@taquito/tzip16';
import constate from 'constate';

import { ACCOUNT_PKH_STORAGE_KEY } from 'lib/constants';
import { IS_DEV_ENV } from 'lib/env';
import { useRetryableSWR } from 'lib/swr';
import { loadChainId, michelEncoder, loadFastRpcClient } from 'lib/temple/helpers';
Expand Down Expand Up @@ -33,6 +34,7 @@ export const [
useAllAccounts,
useSetAccountPkh,
useAccount,
useAccountPkh,
useSettings,
useTezos
] = constate(
Expand All @@ -43,6 +45,7 @@ export const [
v => v.allAccounts,
v => v.setAccountPkh,
v => v.account,
v => v.accountPkh,
v => v.settings,
v => v.tezos
);
Expand Down Expand Up @@ -82,7 +85,7 @@ function useReadyTemple() {
*/

const defaultAcc = allAccounts[0];
const [accountPkh, setAccountPkh] = usePassiveStorage('account_publickeyhash', defaultAcc.publicKeyHash);
const [accountPkh, setAccountPkh] = usePassiveStorage(ACCOUNT_PKH_STORAGE_KEY, defaultAcc.publicKeyHash);

useEffect(() => {
return intercom.subscribe((msg: TempleNotification) => {
Expand Down
22 changes: 11 additions & 11 deletions src/lib/temple/front/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import browser, { Storage } from 'webextension-polyfill';

import { fetchFromStorage, putToStorage } from 'lib/storage';
import { useRetryableSWR } from 'lib/swr';
import { useDidUpdate } from 'lib/ui/hooks';

export function useStorage<T = any>(key: string): [T | null | undefined, (val: SetStateAction<T>) => Promise<void>];
export function useStorage<T = any>(key: string, fallback: T): [T, (val: SetStateAction<T>) => Promise<void>];
Expand Down Expand Up @@ -43,21 +44,20 @@ export function usePassiveStorage<T = any>(key: string, fallback?: T) {

const [value, setValue] = useState(finalData);

useEffect(() => {
useDidUpdate(() => {
setValue(finalData);
}, [finalData]);

const prevValue = useRef(value);

useEffect(() => {
if (prevValue.current !== value && value !== undefined) {
putToStorage(key, value);
}

prevValue.current = value;
}, [key, value]);
const updateValue = useCallback(
(newValue: T | null | undefined) => {
const newValueWithFallback = fallback === undefined ? newValue : newValue ?? fallback;
putToStorage(key, newValueWithFallback);
setValue(newValueWithFallback);
},
[fallback, key]
);

return [value, setValue];
return [value, updateValue];
}

function onStorageChanged<T = any>(key: string, callback: (newValue: T) => void) {
Expand Down
1 change: 1 addition & 0 deletions src/lib/temple/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ interface TempleNewWalletRequest extends TempleMessageBase {

interface TempleNewWalletResponse extends TempleMessageBase {
type: TempleMessageType.NewWalletResponse;
accountPkh: string;
}

interface TempleUnlockRequest extends TempleMessageBase {
Expand Down

0 comments on commit 270ce74

Please sign in to comment.