Skip to content

Commit

Permalink
refactor: update to internal segment event client
Browse files Browse the repository at this point in the history
  • Loading branch information
camerow committed Nov 8, 2024
1 parent e38af3e commit 127ea65
Show file tree
Hide file tree
Showing 17 changed files with 260 additions and 193 deletions.
20 changes: 10 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -144,16 +144,16 @@
"@coinbase/cbpay-js": "2.1.0",
"@fungible-systems/zone-file": "2.0.0",
"@hirosystems/token-metadata-api-client": "1.2.0",
"@hookform/resolvers": "3.9.1",
"@leather.io/bitcoin": "0.16.0",
"@leather.io/constants": "0.13.0",
"@leather.io/crypto": "1.6.7",
"@leather.io/models": "0.18.3",
"@leather.io/query": "2.19.0",
"@leather.io/stacks": "1.3.0",
"@leather.io/tokens": "0.9.2",
"@leather.io/ui": "1.32.0",
"@leather.io/utils": "0.16.7",
"@leather.io/analytics": "2.0.0",
"@leather.io/bitcoin": "0.14.2",
"@leather.io/constants": "0.12.5",
"@leather.io/crypto": "1.6.6",
"@leather.io/models": "0.18.2",
"@leather.io/query": "2.16.0",
"@leather.io/stacks": "1.2.3",
"@leather.io/tokens": "0.9.1",
"@leather.io/ui": "1.30.0",
"@leather.io/utils": "0.16.6",
"@ledgerhq/hw-transport-webusb": "6.27.19",
"@noble/hashes": "1.5.0",
"@noble/secp256k1": "2.1.0",
Expand Down
371 changes: 213 additions & 158 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 @@ -84,7 +84,7 @@ export function useHandleQueuedBackgroundAnalytics() {
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
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 @@ -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

0 comments on commit 127ea65

Please sign in to comment.