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

refactor: update to internal segment event client #5937

Merged
merged 1 commit into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"@fungible-systems/zone-file": "2.0.0",
"@hirosystems/token-metadata-api-client": "1.2.0",
"@hookform/resolvers": "3.9.1",
"@leather.io/analytics": "2.0.0",
"@leather.io/bitcoin": "0.16.0",
"@leather.io/constants": "0.13.0",
"@leather.io/crypto": "1.6.7",
Expand Down
124 changes: 63 additions & 61 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/app/common/app-analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,14 @@
export function useHandleQueuedBackgroundAnalytics() {
useOnMount(() => {
async function handleQueuedAnalytics() {
const queuedEventsStore = await chrome.storage.local.get(analyticsEventKey);

Check warning on line 80 in src/app/common/app-analytics.ts

View workflow job for this annotation

GitHub Actions / lint-eslint

'chrome' is deprecated. Part of the deprecated Chrome Apps platform

try {
const events = analyicsQueueSchema.parse(queuedEventsStore[analyticsEventKey] ?? []);
if (!events.length) return;
await chrome.storage.local.remove(analyticsEventKey);

Check warning on line 85 in src/app/common/app-analytics.ts

View workflow job for this annotation

GitHub Actions / lint-eslint

'chrome' is deprecated. Part of the deprecated Chrome Apps platform
await Promise.all(
events.map(({ eventName, properties }) => analytics.track(eventName, properties))
events.map(({ eventName, properties }) => analytics.untypedTrack(eventName, properties))
);
} catch (e) {
void analytics.track('background_analytics_schema_fail');
Expand Down
4 changes: 3 additions & 1 deletion src/app/common/hooks/use-submit-stx-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export function useSubmitTransactionCallback({ loadingKey }: UseSubmitTransactio

await delay(500);

void analytics.track('broadcast_transaction', { symbol: 'stx' });
void analytics.track('broadcast_transaction', {
symbol: 'stx',
});
onSuccess(safelyFormatHexTxid(response.txid));
setIsIdle();
await refreshAccountData(timeForApiToUpdate);
Expand Down
2 changes: 1 addition & 1 deletion src/app/common/persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@

const storage = {
getItem: async (key: string) => {
const storageVal = await chrome.storage.local.get(key);

Check warning on line 15 in src/app/common/persistence.ts

View workflow job for this annotation

GitHub Actions / lint-eslint

'chrome' is deprecated. Part of the deprecated Chrome Apps platform
return storageVal[key];
},
setItem: (key: string, value: string) => chrome.storage.local.set({ [key]: value }),

Check warning on line 18 in src/app/common/persistence.ts

View workflow job for this annotation

GitHub Actions / lint-eslint

'chrome' is deprecated. Part of the deprecated Chrome Apps platform
removeItem: (key: string) => chrome.storage.local.remove([key]),
};

Expand All @@ -36,7 +36,7 @@
hash: query.queryHash,
error: error.toJSON(),
};
void analytics.track('api_error', errorReport);
void analytics.untypedTrack('api_error', errorReport);
}

if (isZodError(error)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function StacksCryptoAssets({ address }: StacksCryptoAssetsProps) {
void analytics.track('view_collectibles', {
stacks_nfts_count: stacksNftsMetadataResp.length,
});
void analytics.identify({ stacks_nfts_count: stacksNftsMetadataResp.length });
void analytics.client.identify({ stacks_nfts_count: stacksNftsMetadataResp.length });
}
}, [stacksNftsMetadataResp.length]);

Expand Down
2 changes: 1 addition & 1 deletion src/app/features/ledger/hooks/use-ledger-analytics.hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function useLedgerAnalytics() {
return useMemo(
() => ({
trackDeviceVersionInfo(info: object) {
void analytics.track('ledger_app_version_info', info);
void analytics.track('ledger_app_version_info', { info });
},
transactionSignedOnLedgerSuccessfully() {
void analytics.track('ledger_transaction_signed_approved');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function InsufficientFundsActionButtons({ eventName }: InsufficientFundsActionBu
const [isShowingSwitchAccount, setIsShowingSwitchAccount] = useState(false);

const onGetStx = () => {
void analytics.track(eventName);
void analytics.untypedTrack(eventName);
closeWindow();
void chrome.tabs.create({ url: 'index.html#/fund' });
};
Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/receive/receive-btc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function ReceiveBtcModal({ type = 'btc' }: ReceiveBtcModalType) {
<ReceiveTokensLayout
address={btcAddress}
onCopyAddressToClipboard={async () => {
void analytics.track('copy_btc_address_to_clipboard');
void analytics.track('copy_btc_address_to_clipboard', { type });
await copyToClipboard(btcAddress);
toast.success('Copied to clipboard!');
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useLocation, useNavigate } from 'react-router-dom';
import { HStack, Stack, styled } from 'leather-styles/jsx';
import get from 'lodash.get';

import { decodeBitcoinTx } from '@leather.io/bitcoin';
import type { CryptoCurrency } from '@leather.io/models';
import {
useBitcoinBroadcastTransaction,
Expand Down Expand Up @@ -56,7 +55,6 @@ export function RpcSendTransferConfirmation() {
const { filteredUtxosQuery } = useCurrentNativeSegwitUtxos();
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');

const psbt = decodeBitcoinTx(tx);
const transferAmount = sumMoney(recipients.map(r => r.amount));
const txFiatValue = i18nFormatCurrency(baseCurrencyAmountInQuote(transferAmount, btcMarketData));
const txFiatValueSymbol = btcMarketData.price.symbol;
Expand Down Expand Up @@ -96,10 +94,7 @@ export function RpcSendTransferConfirmation() {
async onSuccess(txid) {
void analytics.track('broadcast_transaction', {
symbol: 'btc',
amount: transferAmount,
fee,
inputs: psbt.inputs.length,
outputs: psbt.inputs.length,
amount: transferAmount.amount.toNumber(),
});
await filteredUtxosQuery.refetch();

Expand Down
4 changes: 3 additions & 1 deletion src/app/pages/rpc-sign-psbt/use-rpc-sign-psbt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ export function useRpcSignPsbt() {
fee,
tx,
}: BroadcastSignedPsbtTxArgs) {
void analytics.track('user_approved_sign_and_broadcast_psbt', { origin });
void analytics.track('user_approved_sign_and_broadcast_psbt', {
origin: origin || 'no_origin',
});

const transferTotalAsMoney = sumMoney([addressNativeSegwitTotal, addressTaprootTotal]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ export function SendInscriptionContainer() {
iterationLimit: 100,
})(routeState.inscription.address);

void analytics.track('recurse_addresses_to_find_derivation_path', {
void analytics.untypedTrack('recurse_addresses_to_find_derivation_path', {
duration: result.duration,
});

if (result.status !== 'success') {
void analytics.track('error_did_not_find_owner_path_of_inscription', {
void analytics.untypedTrack('error_did_not_find_owner_path_of_inscription', {
inscription: routeState.inscription.id,
});
throw new Error('Unable to find key of owner inscription address');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function BtcSendFormConfirmation() {
async onSuccess(txid) {
void analytics.track('broadcast_transaction', {
symbol: 'btc',
amount: transferAmount,
amount: Number(transferAmount),
fee,
inputs: decodedTx.inputs.length,
outputs: decodedTx.inputs.length,
Expand Down
2 changes: 1 addition & 1 deletion src/app/pages/transaction-request/transaction-request.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function TransactionRequestBase() {
await stacksBroadcastTransaction(unsignedTx);

void analytics.track('submit_fee_for_transaction', {
calculation: stxFees?.calculation,
calculation: stxFees?.calculation || 'unknown',
fee: values.fee,
type: values.feeType,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function useBreakOnNonCompliantEntity(address: string | string[]) {
]);

if (complianceReports.some(report => report.data?.isOnSanctionsList)) {
void analytics.track('non_compliant_entity_detected');
void analytics.track('non_compliant_entity_detected', { address });
throw new Error(compliantErrorBody);
}
}
4 changes: 2 additions & 2 deletions src/app/store/accounts/blockchain/bitcoin/bitcoin.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,9 @@ export function useSignLedgerBitcoinTx() {
// exist, and we want the user to proceed, despite the warning.
try {
await addNativeSegwitUtxoHexLedgerProps(psbt, nativeSegwitInputsToSign);
void analytics.track('successfully_added_native_segwit_tx_hex_to_ledger_tx');
void analytics.track('native_segwit_tx_hex_to_ledger_tx', { success: true });
} catch (e) {
void analytics.track('failed_to_add_native_segwit_tx_hex_to_ledger_tx');
void analytics.track('native_segwit_tx_hex_to_ledger_tx', { success: false });
}

await addNativeSegwitBip32Derivation(psbt, fingerprint, nativeSegwitInputsToSign);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,13 @@ export function useUpdateLedgerSpecificNativeSegwitUtxoHexForAdddressIndexZero()
tx.updateInput(index, {
nonWitnessUtxo: Buffer.from(inputsTxHex[index], 'hex'),
});
void analytics.track('ledger_nativesegwit_add_nonwitnessutxo');
void analytics.track('ledger_nativesegwit_add_nonwitnessutxo', {
action: 'add_nonwitness_utxo',
});
} else {
void analytics.track('ledger_nativesegwit_skip_add_nonwitnessutxo');
void analytics.track('ledger_nativesegwit_add_nonwitnessutxo', {
action: 'skip_add_nonwitness_utxo',
});
}
});
};
Expand Down
17 changes: 13 additions & 4 deletions src/shared/utils/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,30 @@ import { feedbackIntegration } from '@sentry/browser';
import * as Sentry from '@sentry/react';
import { token } from 'leather-styles/tokens';

import { configureAnalyticsClient } from '@leather.io/analytics';

import {
IS_TEST_ENV,
SEGMENT_WRITE_KEY,
SENTRY_DSN,
WALLET_ENVIRONMENT,
} from '@shared/environment';

export const analytics = new AnalyticsBrowser();
const segmentClient = new AnalyticsBrowser();

export const analytics = configureAnalyticsClient<AnalyticsBrowser>({
client: segmentClient,
defaultProperties: {
platform: 'mobile',
},
});

export function decorateAnalyticsEventsWithContext(
getEventContextProperties: () => Record<string, unknown>
) {
void analytics.ready(
void analytics.client.ready(
() =>
void analytics.addSourceMiddleware(({ payload, next }) => {
void analytics.client.addSourceMiddleware(({ payload, next }) => {
Object.entries(getEventContextProperties()).forEach(([key, value]) => {
payload.obj.context = payload.obj.context || {};
payload.obj.context.ip = '0.0.0.0';
Expand All @@ -41,7 +50,7 @@ export function decorateAnalyticsEventsWithContext(
}

export function initAnalytics() {
return analytics.load(
return analytics.client.load(
{ writeKey: SEGMENT_WRITE_KEY },
{
integrations: {
Expand Down
2 changes: 1 addition & 1 deletion src/shared/workers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export enum WorkerScript {
export function createWorker(scriptName: WorkerScript) {
const worker = new Worker(scriptName);
worker.addEventListener('error', error => {
void analytics?.track(`worker_error_thrown_${scriptName}`, { error });
void analytics?.untypedTrack(`worker_error_thrown_${scriptName}`, { error });
});

return worker;
Expand Down
Loading