Skip to content
Closed
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
92 changes: 44 additions & 48 deletions src/shared/analytics/analytics.background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
getProviderForMetabase,
getProviderNameFromGroup,
} from './shared/getProviderNameFromGroup';
import { addressActionToAnalytics } from './shared/addressActionToAnalytics';
import { transactionContextToAnalytics } from './shared/transactionContextToAnalytics';
import { mixpanelTrack, mixpanelIdentify, mixpanelReset } from './mixpanel';
import {
getChainBreakdown,
Expand Down Expand Up @@ -135,60 +135,56 @@ function trackAppEvents({ account }: { account: Account }) {
sendToMetabase('client_error', params);
});

emitter.on(
'transactionSent',
async ({
emitter.on('transactionSent', async (contextParams) => {
const {
transaction,
initiator,
feeValueCommon,
addressAction,
quote,
clientScope,
chain,
}) => {
const initiatorURL = new URL(initiator);
const { origin, pathname } = initiatorURL;
const isInternalOrigin = globalThis.location.origin === origin;
const initiatorName = isInternalOrigin ? 'Extension' : 'External Dapp';
const addressActionAnalytics = addressActionToAnalytics({
addressAction,
quote,
});
const preferences = await account
.getCurrentWallet()
.getPreferences({ context: INTERNAL_SYMBOL_CONTEXT });
} = contextParams;

const params = createParams({
request_name: 'signed_transaction',
screen_name: origin === initiator ? 'Transaction Request' : pathname,
wallet_address: transaction.from,
/* @deprecated */
context: initiatorName,
/* @deprecated */
type: 'Sign',
client_scope: clientScope ?? initiatorName,
action_type: addressActionAnalytics?.action_type ?? 'Execute',
dapp_domain: isInternalOrigin ? null : origin,
chain,
gas: transaction.gasLimit.toString(),
hash: transaction.hash,
asset_amount_sent: [], // TODO
gas_price: null, // TODO
network_fee: null, // TODO
network_fee_value: feeValueCommon,
contract_type: quote?.contract_metadata?.name ?? null,
hold_sign_button: Boolean(preferences.enableHoldToSignButton),
...addressActionAnalytics,
});
sendToMetabase('signed_transaction', params);
const mixpanelParams = omit(params, [
'request_name',
'hash',
'wallet_address',
]);
mixpanelTrack(account, 'Transaction: Signed Transaction', mixpanelParams);
}
);
const initiatorURL = new URL(initiator);
const { origin, pathname } = initiatorURL;
const isInternalOrigin = globalThis.location.origin === origin;
const initiatorName = isInternalOrigin ? 'Extension' : 'External Dapp';

const analyticsData = transactionContextToAnalytics(contextParams);
const preferences = await account
.getCurrentWallet()
.getPreferences({ context: INTERNAL_SYMBOL_CONTEXT });

const params = createParams({
request_name: 'signed_transaction',
screen_name: origin === initiator ? 'Transaction Request' : pathname,
wallet_address: transaction.from,
/* @deprecated */
context: initiatorName,
/* @deprecated */
type: 'Sign',
client_scope: clientScope ?? initiatorName,
action_type: analyticsData?.action_type ?? 'Execute',
dapp_domain: isInternalOrigin ? null : origin,
chain,
gas: transaction.gasLimit.toString(),
hash: transaction.hash,
asset_amount_sent: [], // TODO
gas_price: null, // TODO
network_fee: null, // TODO
network_fee_value: feeValueCommon,
contract_type: quote?.contract_metadata?.name ?? null,
hold_sign_button: Boolean(preferences.enableHoldToSignButton),
...analyticsData,
});
sendToMetabase('signed_transaction', params);
const mixpanelParams = omit(params, [
'request_name',
'hash',
'wallet_address',
]);
mixpanelTrack(account, 'Transaction: Signed Transaction', mixpanelParams);
});

async function handleSign({
type,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import type { ActionAsset } from 'defi-sdk';
import { isTruthy } from 'is-truthy-ts';
import { getFungibleAsset } from 'src/modules/ethereum/transactions/actionAsset';
import type { AnyAddressAction } from 'src/modules/ethereum/transactions/addressAction';
import type { Chain } from 'src/modules/networks/Chain';
import { createChain } from 'src/modules/networks/Chain';
import { getDecimals } from 'src/modules/networks/asset';
import type { Quote } from 'src/shared/types/Quote';
import type { TransactionContextParams } from 'src/shared/types/SignatureContextParams';
import { baseToCommon } from 'src/shared/units/convert';

interface AnalyticsTransactionData {
Expand All @@ -21,6 +20,8 @@ interface AnalyticsTransactionData {
zerion_fee_percentage?: number;
zerion_fee_usd_amount?: number;
output_chain?: string;
warning_was_shown: TransactionContextParams['warningWasShown'];
output_amount_color: TransactionContextParams['outputAmountColor'];
}

interface AssetQuantity {
Expand Down Expand Up @@ -79,13 +80,12 @@ function toMaybeArr<T>(
return arr?.length ? arr.filter(isTruthy) : undefined;
}

export function addressActionToAnalytics({
export function transactionContextToAnalytics({
addressAction,
quote,
}: {
addressAction: AnyAddressAction | null;
quote?: Quote;
}): AnalyticsTransactionData | null {
warningWasShown,
outputAmountColor,
}: TransactionContextParams): AnalyticsTransactionData | null {
if (!addressAction) {
return null;
}
Expand All @@ -106,7 +106,10 @@ export function addressActionToAnalytics({
asset_name_received: toMaybeArr(incoming?.map(getAssetName)),
asset_address_sent: toMaybeArr(outgoing?.map(getAssetAddress)),
asset_address_received: toMaybeArr(incoming?.map(getAssetAddress)),
warning_was_shown: warningWasShown,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you send these fields for Approve transactions?
If I remember right, we still need send them, but with the default values

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By default values you mean

    warning_was_shown: undefined,
    output_amount_color: undefined,

or

    warning_was_shown: false,
    output_amount_color: 'grey',

?

Copy link
Contributor Author

@vyorkin vyorkin Apr 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated to

 warning_was_shown: false,
output_amount_color: 'grey',

in case of approval tx ✅

output_amount_color: outputAmountColor,
};

if (quote) {
const zerion_fee_percentage = quote.protocol_fee;
const feeAmount = quote.protocol_fee_amount;
Expand Down
2 changes: 2 additions & 0 deletions src/shared/types/SignatureContextParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export interface TransactionContextParams {
clientScope: ClientScope | null;
addressAction: AnyAddressAction | null;
quote?: Quote;
warningWasShown?: boolean;
outputAmountColor?: 'grey' | 'red';
}

export interface MessageContextParams {
Expand Down
28 changes: 15 additions & 13 deletions src/ui/components/FiatInputValue/FiatInputValue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import { useCurrency } from 'src/modules/currency/useCurrency';
import type { Asset } from 'defi-sdk';
import { HStack } from 'src/ui/ui-kit/HStack';
import type { PriceImpact } from 'src/ui/pages/SwapForm/shared/price-impact';
import { getPriceImpactPercentage } from 'src/ui/pages/SwapForm/shared/price-impact';
import {
getPriceImpactPercentage,
isSignificantValueLoss,
} from 'src/ui/pages/SwapForm/shared/price-impact';
import { formatPercent } from 'src/shared/units/formatPercent';

export function FiatInputValue({
Expand Down Expand Up @@ -88,9 +91,9 @@ export function ReceiveFiatInputValue({
}: {
priceImpact: PriceImpact | null;
} & FieldInputValueProps) {
const isSignificantLoss =
priceImpact?.kind === 'loss' &&
(priceImpact.level === 'medium' || priceImpact.level === 'high');
const isSignificantLoss = Boolean(
priceImpact && isSignificantValueLoss(priceImpact)
);

const priceImpactPercentage = priceImpact
? getPriceImpactPercentage(priceImpact)
Expand All @@ -104,27 +107,26 @@ export function ReceiveFiatInputValue({
[priceImpactPercentage]
);

const showPercentageChange =
const pecentageChangeVisible =
Boolean(percentageChange) &&
(priceImpact?.kind === 'zero' || priceImpact?.kind === 'loss');

const color = isSignificantLoss
? 'var(--negative-500)'
: 'var(--neutral-600)';

return (
<FiatInputValue
{...props}
name="receiveInput"
percentageChange={
showPercentageChange && percentageChange ? (
<UIText
kind="small/regular"
color={
isSignificantLoss ? 'var(--negative-500)' : 'var(--neutral-600)'
}
>
pecentageChangeVisible && percentageChange ? (
<UIText kind="small/regular" color={color}>
{`(${percentageChange})`}
</UIText>
) : null
}
color={isSignificantLoss ? 'var(--negative-500)' : 'var(--neutral-600)'}
color={color}
style={isSignificantLoss ? { cursor: 'help' } : undefined}
title={
isSignificantLoss
Expand Down
23 changes: 18 additions & 5 deletions src/ui/pages/BridgeForm/BridgeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ import { TransactionConfiguration } from '../SendTransaction/TransactionConfigur
import { ApproveHintLine } from '../SwapForm/ApproveHintLine';
import { txErrorToMessage } from '../SendTransaction/shared/transactionErrorToMessage';
import { getQuotesErrorMessage } from '../SwapForm/Quotes/getQuotesErrorMessage';
import { calculatePriceImpact } from '../SwapForm/shared/price-impact';
import type { BridgeFormState } from './shared/types';
import { useBridgeTokens } from './useBridgeTokens';
import { getAvailablePositions } from './getAvailablePositions';
Expand Down Expand Up @@ -444,6 +445,15 @@ function BridgeFormComponent() {
[selectedQuote]
);

const priceImpact = useMemo(() => {
return calculatePriceImpact({
inputValue: spendInput || null,
outputValue: receiveInput || null,
inputAsset: spendAsset,
outputAsset: receiveAsset,
});
}, [receiveAsset, receiveInput, spendAsset, spendInput]);

const reverseChains = useCallback(
() =>
setUserFormState((state) => ({
Expand Down Expand Up @@ -665,6 +675,11 @@ function BridgeFormComponent() {
resetApproveMutation,
]);

const isApproveMode =
approveMutation.isLoading ||
(quotesData.done && !enough_allowance) ||
approveTxStatus === 'pending';

const {
mutate: sendTransaction,
data: transactionHash,
Expand Down Expand Up @@ -709,6 +724,8 @@ function BridgeFormComponent() {
chain: spendChain,
}),
quote: selectedQuote,
warningWasShown: false,
outputAmountColor: 'grey',
});
return txResponse.hash;
},
Expand Down Expand Up @@ -786,11 +803,6 @@ function BridgeFormComponent() {
);
}

const isApproveMode =
approveMutation.isLoading ||
(quotesData.done && !enough_allowance) ||
approveTxStatus === 'pending';

const showApproveHintLine =
(quotesData.done && !enough_allowance) || !approveMutation.isIdle;

Expand Down Expand Up @@ -981,6 +993,7 @@ function BridgeFormComponent() {
}
spendInput={spendInput}
spendAsset={spendAsset}
priceImpact={priceImpact}
onChangeAmount={(value) => handleChange('receiveInput', value)}
onChangeToken={(value) =>
handleChange('receiveTokenInput', value)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import React, { useEffect, useId, useMemo, useRef } from 'react';
import { getPositionBalance } from 'src/ui/components/Positions/helpers';
import type { EmptyAddressPosition } from '@zeriontech/transactions';
import type { AddressPosition, Asset } from 'defi-sdk';
import React, { useEffect, useId, useRef } from 'react';
import type { Chain } from 'src/modules/networks/Chain';
import {
formatTokenValue,
roundTokenValue,
} from 'src/shared/units/formatTokenValue';
import { ReceiveFiatInputValue } from 'src/ui/components/FiatInputValue/FiatInputValue';
import { getPositionBalance } from 'src/ui/components/Positions/helpers';
import { MarketAssetSelect } from 'src/ui/pages/SwapForm/fieldsets/ReceiveTokenField/MarketAssetSelect';
import type { PriceImpact } from 'src/ui/pages/SwapForm/shared/price-impact';
import { FLOAT_INPUT_PATTERN } from 'src/ui/shared/forms/inputs';
import { NBSP } from 'src/ui/shared/typography';
import { FormFieldset } from 'src/ui/ui-kit/FormFieldset';
import type { InputHandle } from 'src/ui/ui-kit/Input/DebouncedInput';
import { DebouncedInput } from 'src/ui/ui-kit/Input/DebouncedInput';
import { FormFieldset } from 'src/ui/ui-kit/FormFieldset';
import { UnstyledInput } from 'src/ui/ui-kit/UnstyledInput';
import type { Chain } from 'src/modules/networks/Chain';
import { NBSP } from 'src/ui/shared/typography';
import { FLOAT_INPUT_PATTERN } from 'src/ui/shared/forms/inputs';
import type { AddressPosition, Asset } from 'defi-sdk';
import { MarketAssetSelect } from 'src/ui/pages/SwapForm/fieldsets/ReceiveTokenField/MarketAssetSelect';
import type { EmptyAddressPosition } from '@zeriontech/transactions';
import { ReceiveFiatInputValue } from 'src/ui/components/FiatInputValue/FiatInputValue';
import { calculatePriceImpact } from 'src/ui/pages/SwapForm/shared/price-impact';

export function ReceiveTokenField({
receiveInput,
Expand All @@ -25,6 +25,7 @@ export function ReceiveTokenField({
availableReceivePositions,
spendInput,
spendAsset,
priceImpact,
onChangeAmount,
onChangeToken,
}: {
Expand All @@ -35,6 +36,7 @@ export function ReceiveTokenField({
availableReceivePositions: AddressPosition[];
spendInput?: string;
spendAsset: Asset | null;
priceImpact: PriceImpact | null;
onChangeAmount: (value: string) => void;
onChangeToken: (value: string) => void;
}) {
Expand All @@ -55,17 +57,6 @@ export function ReceiveTokenField({
}
}, [receiveInput]);

const priceImpact = useMemo(
() =>
calculatePriceImpact({
inputValue: spendInput ?? null,
outputValue: receiveInput ?? null,
inputAsset: spendAsset,
outputAsset: receiveAsset,
}),
[receiveAsset, receiveInput, spendAsset, spendInput]
);

const inputId = useId();
const inputRef = useRef<HTMLInputElement | null>(null);

Expand Down
2 changes: 2 additions & 0 deletions src/ui/pages/SendForm/SendForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,8 @@ function SendFormComponent() {
quantity: amount,
chain,
}),
warningWasShown: false,
outputAmountColor: 'grey',
});
if (preferences) {
setPreferences({
Expand Down
Loading