Skip to content

Commit

Permalink
move analytics to separate dir
Browse files Browse the repository at this point in the history
add dd file

revert usecompliancestate hook

fix import names

fix last broken import filepath

add events to deposit and withdraw forms

fix import names

dydx chain transactions logs. add abacus logger implementation. auto log errors

finish logger implementation

add service name and env

fix logging

fix type

typo
  • Loading branch information
yogurtandjam committed Aug 22, 2024
1 parent 68c4458 commit 50074f4
Show file tree
Hide file tree
Showing 10 changed files with 101 additions and 76 deletions.
11 changes: 2 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/constants/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,9 @@ export const AnalyticsEvents = unionize(
errorMessage?: string;
amount: string;
chainId?: string;
assetId?: string;
assetaddress?: string;
assetSymbol: string;
assetName: string;
}>(),
},
{ tag: 'type' as const, value: 'payload' as const }
Expand Down
2 changes: 1 addition & 1 deletion src/constants/networks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import environments from '../../public/configs/v1/env.json';

const CURRENT_MODE = ({
export const CURRENT_MODE = ({
production: 'MAINNET',
testnet: 'TESTNET',
staging: 'DEV',
Expand Down
14 changes: 14 additions & 0 deletions src/lib/abacus/dydxChainTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { type RootStore } from '@/state/_store';
import { placeOrderTimeout } from '@/state/account';
import { setInitializationError } from '@/state/app';

import { dd } from '../analytics/datadog';
import { signComplianceSignature } from '../compliance';
import { StatefulOrderError, stringifyTransactionError } from '../errors';
import { bytesToBigInt } from '../numbers';
Expand Down Expand Up @@ -410,13 +411,16 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
}

ibcMsg.value.token.amount = amount.toString();

dd.info('sendNobleIBC attempting to submit tx', { ibcMsg, fee, amount });
const tx = await this.nobleClient.send(
[ibcMsg],
undefined,
`${DEFAULT_TRANSACTION_MEMO} | ${this.nobleWallet?.address}`
);

const parsedTx = this.parseToPrimitives(tx);
dd.info('sendNobleIBC tx submitted', { tx, ibcMsg });

return JSON.stringify(parsedTx);
} catch (error) {
Expand Down Expand Up @@ -456,12 +460,16 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
},
};

dd.info('withdrawToNobleIBC attempting to submit tx', { ibcMsg });

const tx = await this.compositeClient.send(
this.localWallet,
() => Promise.resolve([msg, ibcMsg]),
false
);

dd.info('withdrawToNobleIBC tx submitted', { tx, ibcMsg });

return JSON.stringify({
txHash: hashFromTx(tx?.hash),
});
Expand Down Expand Up @@ -494,8 +502,12 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {

ibcMsg.value.amount = amount.toString();

dd.info('cctpWithdraw attempting to submit tx', { ibcMsg, fee, amount });

const tx = await this.nobleClient.send([ibcMsg]);

dd.info('cctpWithdraw tx submitted', { tx, ibcMsg });

const parsedTx = this.parseToPrimitives(tx);

return JSON.stringify(parsedTx);
Expand Down Expand Up @@ -529,7 +541,9 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {

ibcMsgs[0].value.amount = amount.toString();

dd.info('cctpMultiMsgWithdraw attempting to submit tx', { ibcMsgs, fee, amount });
const tx = await this.nobleClient.send(ibcMsgs);
dd.info('cctpMultiMsgWithdraw tx submitted', { tx, ibcMsgs });

const parsedTx = this.parseToPrimitives(tx);

Expand Down
12 changes: 11 additions & 1 deletion src/lib/abacus/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable no-console */
import type { AbacusLoggingProtocol } from '@/constants/abacus';

import { dd } from '../analytics/datadog';

class AbacusLogger implements Omit<AbacusLoggingProtocol, '__doNotUseOrImplementIt'> {
d(tag: string, message: string) {
if (
Expand All @@ -11,13 +13,21 @@ class AbacusLogger implements Omit<AbacusLoggingProtocol, '__doNotUseOrImplement
}
}

e(tag: string, message: string) {
e(tag: string, message: string, context: object, error: Error) {
if (
import.meta.env.VITE_ENABLE_ABACUS_LOGGING ||
import.meta.env.VITE_ABACUS_LOG_LEVEL === 'error'
) {
console.error(`${tag}: ${message}`);
}
dd.error(message, context, error);
}

ddInfo(message: string, context: object) {
if (import.meta.env.VITE_ABACUS_LOG_LEVEL === 'debug') {
console.log(`dd info: ${message}`, context);
}
dd.info(message, context);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib/analytics/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const identify = (property: AnalyticsUserProperty) => {
detail: { property: propertyTypeToLog, propertyValue: property.payload },
});
dd.setContextProperty(propertyTypeToLog, property.payload);
dd.log(`set context item: ${propertyTypeToLog}`, dd.getContext());
dd.info(`set context item: ${propertyTypeToLog}`, dd.getContext());

globalThis.dispatchEvent(customEvent);
};
Expand Down
5 changes: 5 additions & 0 deletions src/lib/analytics/datadog.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { datadogLogs } from '@datadog/browser-logs';

import { CURRENT_MODE } from '@/constants/networks';

const CLIENT_TOKEN = import.meta.env.VITE_DATADOG_CLIENT_TOKEN;
const SERVICE_NAME = import.meta.env.VITE_DATADOG_SERVICE_NAME ?? 'v4-web-frontend-unknown-source';
const LOGGER_NAME = 'v4-web';

if (CLIENT_TOKEN) {
datadogLogs.init({
clientToken: CLIENT_TOKEN,
site: 'datadoghq.com',
service: SERVICE_NAME,
forwardErrorsToLogs: true,
sessionSampleRate: 100,
env: CURRENT_MODE,
});
}

Expand Down
5 changes: 4 additions & 1 deletion src/lib/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { AnalyticsEvents } from '@/constants/analytics';
import { isDev } from '@/constants/networks';

import { track } from './analytics/analytics';
import { dd } from './analytics/datadog';

export const log = (location: string, error: Error, metadata?: any) => {
export const log = (location: string, error: Error, metadata?: object) => {
if (isDev) {
// eslint-disable-next-line no-console
console.warn('telemetry/log:', { location, error, metadata });
Expand All @@ -25,6 +26,8 @@ export const log = (location: string, error: Error, metadata?: any) => {
})
);

dd.error(`[Error] ${location}`, metadata, error);

globalThis.dispatchEvent(customEvent);
};

Expand Down
70 changes: 33 additions & 37 deletions src/views/forms/AccountManagementForms/DepositForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import { getTransferInputs } from '@/state/inputsSelectors';

import abacusStateManager from '@/lib/abacus';
import { track } from '@/lib/analytics/analytics';
import { dd } from '@/lib/analytics/datadog';
import { MustBigNumber } from '@/lib/numbers';
import { getNobleChainId, NATIVE_TOKEN_ADDRESS } from '@/lib/squid';
import { log } from '@/lib/telemetry';
Expand Down Expand Up @@ -279,21 +280,21 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {

const onSubmit = useCallback(
async (e: FormEvent) => {
track(
AnalyticsEvents.TransferDepositFundsClick({
chainId: chainIdStr ?? undefined,
tokenAddress: sourceToken?.address ?? undefined,
tokenSymbol: sourceToken?.symbol ?? undefined,
slippage: slippage ?? undefined,
gasFee: summary?.gasFee ?? undefined,
bridgeFee: summary?.bridgeFee ?? undefined,
exchangeRate: summary?.exchangeRate ?? undefined,
estimatedRouteDuration: summary?.estimatedRouteDuration ?? undefined,
toAmount: summary?.toAmount ?? undefined,
toAmountMin: summary?.toAmountMin ?? undefined,
depositCTAString,
})
);
const transferDepositContext = {
chainId: chainIdStr ?? undefined,
tokenAddress: sourceToken?.address ?? undefined,
tokenSymbol: sourceToken?.symbol ?? undefined,
slippage: slippage ?? undefined,
gasFee: summary?.gasFee ?? undefined,
bridgeFee: summary?.bridgeFee ?? undefined,
exchangeRate: summary?.exchangeRate ?? undefined,
estimatedRouteDuration: summary?.estimatedRouteDuration ?? undefined,
toAmount: summary?.toAmount ?? undefined,
toAmountMin: summary?.toAmountMin ?? undefined,
depositCTAString,
};
track(AnalyticsEvents.TransferDepositFundsClick(transferDepositContext));
dd.info('Transfer deposit click', transferDepositContext);
try {
e.preventDefault();

Expand Down Expand Up @@ -338,19 +339,12 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
});
abacusStateManager.clearTransferInputValues();
setFromAmount('');

onDeposit?.({
chainId: chainIdStr || undefined,
tokenAddress: sourceToken?.address || undefined,
tokenSymbol: sourceToken?.symbol || undefined,
slippage: slippage || undefined,
gasFee: summary?.gasFee || undefined,
bridgeFee: summary?.bridgeFee || undefined,
exchangeRate: summary?.exchangeRate || undefined,
estimatedRouteDuration: summary?.estimatedRouteDuration || undefined,
toAmount: summary?.toAmount || undefined,
toAmountMin: summary?.toAmountMin || undefined,
});
const submittedTransferDepositContext = {
...transferDepositContext,
txHash,
};
onDeposit?.(submittedTransferDepositContext);
dd.info('Transfer deposit submitted', submittedTransferDepositContext);
}
} catch (err) {
log('DepositForm/onSubmit', err);
Expand Down Expand Up @@ -418,15 +412,17 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
}

if (routeErrors) {
track(
AnalyticsEvents.RouteError({
transferType: TransferType.deposit.name,
errorMessage: routeErrorMessage ?? undefined,
amount: debouncedAmount,
chainId: chainIdStr ?? undefined,
assetId: sourceToken?.toString(),
})
);
const routeErrorContext = {
transferType: TransferType.deposit.name,
errorMessage: routeErrorMessage ?? undefined,
amount: debouncedAmount,
chainId: chainIdStr ?? undefined,
assetAddress: sourceToken?.address,
assetSymbol: sourceToken?.symbol,
assetName: sourceToken?.name,
};
track(AnalyticsEvents.RouteError(routeErrorContext));
dd.info('Route error received', routeErrorContext);
return routeErrorMessage
? stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
Expand Down
52 changes: 27 additions & 25 deletions src/views/forms/AccountManagementForms/WithdrawForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import { getSelectedLocale } from '@/state/localizationSelectors';
import abacusStateManager from '@/lib/abacus';
import { validateCosmosAddress } from '@/lib/addressUtils';
import { track } from '@/lib/analytics/analytics';
import { dd } from '@/lib/analytics/datadog';
import { getRouteErrorMessageOverride } from '@/lib/errors';
import { MustBigNumber } from '@/lib/numbers';
import { getNobleChainId } from '@/lib/squid';
Expand Down Expand Up @@ -227,21 +228,21 @@ export const WithdrawForm = () => {
setWithdrawAmount('');

addOrUpdateTransferNotification({ ...notificationParams, txHash, isDummy: false });

track(
AnalyticsEvents.TransferWithdraw({
chainId: toChainId,
tokenAddress: toToken?.address || undefined,
tokenSymbol: toToken?.symbol || undefined,
slippage: slippage || undefined,
gasFee: summary?.gasFee || undefined,
bridgeFee: summary?.bridgeFee || undefined,
exchangeRate: summary?.exchangeRate || undefined,
estimatedRouteDuration: summary?.estimatedRouteDuration || undefined,
toAmount: summary?.toAmount || undefined,
toAmountMin: summary?.toAmountMin || undefined,
})
);
const transferWithdrawContext = {
chainId: toChainId,
tokenAddress: toToken?.address || undefined,
tokenSymbol: toToken?.symbol || undefined,
slippage: slippage || undefined,
gasFee: summary?.gasFee || undefined,
bridgeFee: summary?.bridgeFee || undefined,
exchangeRate: summary?.exchangeRate || undefined,
estimatedRouteDuration: summary?.estimatedRouteDuration || undefined,
toAmount: summary?.toAmount || undefined,
toAmountMin: summary?.toAmountMin || undefined,
txHash,
};
track(AnalyticsEvents.TransferWithdraw(transferWithdrawContext));
dd.info('Transfer withdraw submitted', transferWithdrawContext);
} else {
throw new Error('No transaction hash returned');
}
Expand Down Expand Up @@ -436,16 +437,17 @@ export const WithdrawForm = () => {
routeErrors,
routeErrorMessage
);

track(
AnalyticsEvents.RouteError({
transferType: TransferType.withdrawal.name,
errorMessage: routeErrorMessageOverride ?? undefined,
amount: debouncedAmount,
chainId: chainIdStr ?? undefined,
assetId: toToken?.toString(),
})
);
const routeErrorContext = {
transferType: TransferType.withdrawal.name,
errorMessage: routeErrorMessageOverride ?? undefined,
amount: debouncedAmount,
chainId: chainIdStr ?? undefined,
assetAddress: toToken?.address,
assetSymbol: toToken?.symbol,
assetName: toToken?.name,
};
track(AnalyticsEvents.RouteError(routeErrorContext));
dd.info('Route error received', routeErrorContext);
return {
errorMessage: routeErrorMessageOverride
? stringGetter({
Expand Down

0 comments on commit 50074f4

Please sign in to comment.