Skip to content

Commit

Permalink
fix(extension): replace local logic with txSummaryInspector - LW-11936 (
Browse files Browse the repository at this point in the history
#1589)

- replace local logic with txSummaryInspector
- test(extension): update step for tx cost and fee verification
- test(extension): add fee to tx summary value

---------

Co-authored-by: wklos-iohk <[email protected]>
  • Loading branch information
mirceahasegan and wklos-iohk authored Jan 17, 2025
1 parent 9a05eba commit 37ffbe2
Show file tree
Hide file tree
Showing 17 changed files with 72 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ import {
AssetActivityItemProps,
AssetActivityListProps,
ConwayEraCertificatesTypes,
DelegationActivityType,
TransactionActivityType
DelegationActivityType
} from '@lace/core';
import { CurrencyInfo, TxDirections } from '@src/types';
import { getTxDirection, inspectTxType } from '@src/utils/tx-inspection';
Expand Down Expand Up @@ -91,7 +90,7 @@ const getDelegationAmount = (activity: DelegationActivityItemProps) => {
activity.type === DelegationActivityType.delegationRegistration ||
activity.type === ConwayEraCertificatesTypes.Registration
) {
return fee.plus(activity.deposit);
return fee.plus(activity.deposit).negated();
}

if (
Expand All @@ -101,7 +100,7 @@ const getDelegationAmount = (activity: DelegationActivityItemProps) => {
return new BigNumber(activity.depositReclaim).minus(fee);
}

return fee;
return fee.negated();
};

const FIAT_PRICE_DECIMAL_PLACES = 2;
Expand Down Expand Up @@ -371,12 +370,6 @@ const mapWalletActivities = memoize(
amount: `${getDelegationAmount(activity)} ${cardanoCoin.symbol}`,
fiatAmount: `${getFiatAmount(getDelegationAmount(activity), cardanoFiatPrice)} ${fiatCurrency.code}`
}),
...(activity.type === TransactionActivityType.self && {
amount: `${activity.fee} ${cardanoCoin.symbol}`,
fiatAmount: cardanoFiatPrice
? `${getFiatAmount(new BigNumber(activity.fee), cardanoFiatPrice)} ${fiatCurrency.code}`
: '-'
}),
assets: activity.assets.map((asset: ActivityAssetProp) => {
const assetId = Wallet.Cardano.AssetId(asset.id);
const token = assetsInfo.get(assetId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const mockWalletState: ObservableWalletState = {
value: { assets: new Map(), coins: BigInt(200) }
}
],
fee: '100000'
fee: BigInt(100_000)
}
} as unknown as Wallet.Cardano.HydratedTx
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ describe('Testing tx transformers utils', () => {
Promise.resolve({
address: sendingAddress,
value: {
coins: BigInt('2000000')
coins: BigInt('2000000'),
assets: new Map([
[Wallet.Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'), BigInt('100')]
]) as Wallet.Cardano.TokenMap
}
})
});
Expand All @@ -118,13 +121,13 @@ describe('Testing tx transformers utils', () => {
depositReclaim: undefined,
direction: 'Outgoing',
fee: '1.00',
fiatAmount: '1.00 USD',
fiatAmount: '-2.00 USD',
id: '6804edf9712d2b619edb6ac86861fe93a730693183a262b165fcc1ba1bc99cad',
amount: '1.00 ADA',
amount: '-2.00 ADA',
assets: [
{
id: '6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7',
val: '100'
val: '-100'
}
],
assetsNumber: 2,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
import BigNumber from 'bignumber.js';
import { Wallet } from '@lace/cardano';
import { CurrencyInfo, TxDirections } from '@types';
import { inspectTxValues, inspectTxType, txIncludesConwayCertificates } from '@src/utils/tx-inspection';
import { inspectTxType, txIncludesConwayCertificates } from '@src/utils/tx-inspection';
import { formatDate, formatTime } from '@src/utils/format-date';
import { getTransactionTotalAmount } from '@src/utils/get-transaction-total-amount';
import type { TransformedActivity, TransformedTransactionActivity } from './types';
import { ActivityStatus, ConwayEraCertificatesTypes, DelegationActivityType } from '@lace/core';
import capitalize from 'lodash/capitalize';
import dayjs from 'dayjs';
import { hasPhase2ValidationFailed } from '@src/utils/phase2-validation';
import { createTxInspector, Milliseconds, transactionSummaryInspector } from '@cardano-sdk/core';

const { util } = Wallet.Cardano;
// eslint-disable-next-line no-magic-numbers
const TIMEOUT = 1000 as Milliseconds;

export interface TxTransformerInput {
tx: Wallet.TxInFlight | Wallet.Cardano.HydratedTx | Wallet.KeyManagement.WitnessedTx;
Expand Down Expand Up @@ -110,24 +111,14 @@ const transformTransactionStatus = (
};

type GetTxFormattedAmount = (
args: Pick<
TxTransformerInput,
'walletAddresses' | 'tx' | 'direction' | 'resolveInput' | 'cardanoCoin' | 'fiatCurrency' | 'fiatPrice'
>
args: Pick<TxTransformerInput, 'tx' | 'cardanoCoin' | 'fiatCurrency' | 'fiatPrice'> & { amount: bigint }
) => Promise<{
amount: string;
fiatAmount: string;
}>;

const getTxFormattedAmount: GetTxFormattedAmount = async ({
resolveInput,
tx,
walletAddresses,
direction,
cardanoCoin,
fiatCurrency,
fiatPrice
}) => {
const getTxFormattedAmount: GetTxFormattedAmount = async ({ tx, cardanoCoin, fiatCurrency, fiatPrice, amount }) => {
const outputAmount = new BigNumber(amount.toString());
const transaction = 'tx' in tx ? tx.tx : tx;
const { body } = transaction;
if (hasPhase2ValidationFailed(transaction)) {
Expand All @@ -141,16 +132,6 @@ const getTxFormattedAmount: GetTxFormattedAmount = async ({
};
}

const outputAmount = await getTransactionTotalAmount({
addresses: walletAddresses,
inputs: body.inputs,
outputs: body.outputs,
fee: body.fee,
direction,
withdrawals: body.withdrawals,
resolveInput
});

return {
amount: Wallet.util.getFormattedAmount({ amount: outputAmount.toString(), cardanoCoin }),
fiatAmount: getFormattedFiatAmount({ amount: outputAmount, fiatCurrency, fiatPrice })
Expand Down Expand Up @@ -186,17 +167,36 @@ export const txTransformer = async ({
isSharedWallet
}: TxTransformerInput): Promise<TransformedTransactionActivity[]> => {
const transaction = 'tx' in tx ? tx.tx : tx;
const implicitCoin = util.computeImplicitCoin(protocolParameters, transaction.body);
const deposit = implicitCoin.deposit ? Wallet.util.lovelacesToAdaString(implicitCoin.deposit.toString()) : undefined;
const depositReclaimValue = Wallet.util.calculateDepositReclaim(implicitCoin);

const txSummaryInspector = createTxInspector({
summary: transactionSummaryInspector({
addresses: walletAddresses.map((addr) => addr.address),
rewardAccounts: walletAddresses.map((addr) => addr.rewardAccount),
inputResolver: { resolveInput },
protocolParameters,
// Using a dummy asset provider as we don't need to fetch assets for the summary
// On reject, the summary inspector will use the information it can extract from the assetId, and
// all we need here is the id and the amount
assetProvider: {
getAsset: () => Promise.reject({}),
getAssets: () => Promise.reject({}),
healthCheck: () => Promise.resolve({ ok: true })
},
timeout: TIMEOUT,
logger: console
})
});

// TODO: LW-8767 investigate why in-flight transactions do not have a `witness` property and add it
const { summary } = await txSummaryInspector({ witness: undefined, ...transaction });

const deposit = summary.deposit ? Wallet.util.lovelacesToAdaString(summary.deposit.toString()) : undefined;
const depositReclaimValue = summary.returnedDeposit;
const depositReclaim = depositReclaimValue
? Wallet.util.lovelacesToAdaString(depositReclaimValue.toString())
: undefined;
const { assets } = await inspectTxValues({
addresses: walletAddresses,
tx: transaction as unknown as Wallet.Cardano.HydratedTx,
direction
});

const assets = summary.assets;

const formattedDate = dayjs().isSame(date, 'day')
? 'Today'
Expand All @@ -208,25 +208,23 @@ export const txTransformer = async ({

const assetsEntries = assets
? [...assets.entries()]
.map(([id, val]) => ({ id: id.toString(), val: val.toString() }))
.map(([id, { amount: val }]) => ({ id: id.toString(), val: val.toString() }))
.sort((a, b) => Number(b.val) - Number(a.val))
: [];

const formattedAmount = await getTxFormattedAmount({
cardanoCoin,
fiatCurrency,
resolveInput,
tx,
walletAddresses,
direction,
fiatPrice
fiatPrice,
amount: summary.coins
});

const baseTransformedActivity = {
id: transaction.id.toString(),
deposit,
depositReclaim,
fee: Wallet.util.lovelacesToAdaString(transaction.body.fee.toString()),
fee: Wallet.util.lovelacesToAdaString(summary.fee.toString()),
status: transformTransactionStatus(transaction, status),
amount: formattedAmount.amount,
fiatAmount: formattedAmount.fiatAmount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,7 @@ export const AssetActivityItem = ({
ref={ref}
>
<span>
<span data-testid="balance">
{isNegativeBalance ? '-' : ''}
{assetsText.text}
</span>
<span data-testid="balance">{assetsText.text}</span>
{assetsText.suffix && (
<Tooltip
overlayClassName={styles.tooltip}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('Testing AssetActivityItem component', () => {

const totalAmount = await findByTestId('balance');

expect(totalAmount).toHaveTextContent(`-${props.amount}`);
expect(totalAmount).toHaveTextContent(`${props.amount}`);
});
});

Expand All @@ -65,7 +65,7 @@ describe('Testing AssetActivityItem component', () => {
const { findByTestId } = render(<AssetActivityItem {...props} />);

const activityAmount = await findByTestId(assetsAmountTestId);
const tickerText = `-${props.amount}, ${props.assets?.[0].val} ${props.assets?.[0].info?.ticker}`;
const tickerText = `${props.amount}, ${props.assets?.[0].val} ${props.assets?.[0].info?.ticker}`;
const activityAssetTickerText = await within(activityAmount).findByText(tickerText);

expect(activityAssetTickerText).toBeVisible();
Expand Down
2 changes: 1 addition & 1 deletion packages/e2e-tests/src/features/HdWalletExtended.feature
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Feature: HD wallet - extended view
Then I can see transaction <txNumber> has type "<txType>" and value "<txValue>"
Examples:
| txNumber | txType | txValue | Notes |
| 1 | Sent | 17.00 | |
| 1 | Sent | 17.19 | |
| 2 | Received | 16.00 | Was received to not first address |
| 3 | Received | 4.00 | Was received to first address |
| 6 | Self Transaction | 0.17 | Was send to first address |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Feature: Transactions - Extended view
And I save tx hash value "a21a3069e214f34ef32e4797865233f87195b753a4cfbca7bed2ccf4807d98d0"
And I am on Transactions extended page
And I wait for the transaction history to be loaded and all transactions to be confirmed
When the Sent transaction is displayed with value: "24.79 tADA" and tokens count 1
When the Sent transaction is displayed with value: "25.00 tADA" and tokens count 1
When I click on a transaction: 1
Then The Tx details are displayed as "core.activityDetails.sent" for ADA with value: 24.79 and wallet: "addr_test1qp7vynpwhsyjsqvyw9n8r4uy3uj5hu2arfy94vynvng6556hhqrnhndmg2pntqazt36v700x6kryqjhe75p58v65v6kszx7h3j" address

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ Feature: Wallet address page
And The Transaction submitted screen is displayed in extended mode
And I close the drawer by clicking close button
And I navigate to Transactions extended page
And the Sent transaction is displayed with value: "2.00 tADA" and tokens count 1
And the Sent transaction is displayed with value: "2.17 tADA" and tokens count 1
And I open wallet: "UnusedAddressWallet" in: extended mode
And I click "Receive" button on page header
And I click "Wallet Address" "Advanced mode" toggle
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Feature: Analytics - Posthog - Sending - Extended View
And I click "View transaction" button on submitted transaction page
And Local storage unconfirmedTransaction contains tx with type: "internal"
And I validate latest analytics single event "send | all done | view transaction | click"
When the Sent transaction is displayed with value: "2.12 tADA" and tokens count 1
When the Sent transaction is displayed with value: "2.30 tADA" and tokens count 1
Then I validate latest analytics single event "send | transaction confirmed"
And I validate that the "send | transaction confirmed" event includes property "tx_creation_type" with value "internal" in posthog
And I validate that 7 analytics event(s) have been sent
Expand Down Expand Up @@ -62,7 +62,7 @@ Feature: Analytics - Posthog - Sending - Extended View
And I wait 2000 milliseconds
And I set up request interception for posthog analytics request(s)
Then Local storage unconfirmedTransaction contains tx with type: "external"
When the Sent transaction is displayed with value: "3.00 tADA" and tokens count 1
When the Sent transaction is displayed with value: "3.17 tADA" and tokens count 1
Then I validate latest analytics single event "send | transaction confirmed"
And I validate that the "send | transaction confirmed" event includes property "tx_creation_type" with value "external" in posthog
And I validate that 1 analytics event(s) have been sent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Feature: Analytics - Posthog - Sending - Popup View
And I click "View transaction" button on submitted transaction page
And Local storage unconfirmedTransaction contains tx with type: "internal"
And I validate latest analytics single event "send | all done | view transaction | click"
When the Sent transaction is displayed with value: "1.12 tADA" and tokens count 1
When the Sent transaction is displayed with value: "1.29 tADA" and tokens count 1
Then I validate latest analytics single event "send | transaction confirmed"
And I validate that the "send | transaction confirmed" event includes property "tx_creation_type" with value "internal" in posthog
And I validate that 7 analytics event(s) have been sent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Feature: Send Transactions from Dapp - E2E
And I navigate to Tokens extended page
Then the sent amount of: "3" with "DApp transaction" fee for token "Cardano" is subtracted from the total balance
When I navigate to Transactions extended page
Then the Sent transaction is displayed with value: "3.00 tADA" and tokens count 1
Then the Sent transaction is displayed with value: "-3.17 tADA" and tokens count 1
And I click on a transaction: 1
Then The Tx details are displayed as "core.activityDetails.sent" for ADA with value: 3.00 and wallet: "WalletReceiveDappTransactionE2E" address
When I open wallet: "WalletReceiveDappTransactionE2E" in: extended mode
Expand Down Expand Up @@ -70,7 +70,7 @@ Feature: Send Transactions from Dapp - E2E
And I navigate to Tokens extended page
Then the sent amount of: "2" for token "LaceCoin2" is subtracted from the total balance
When I navigate to Transactions extended page
Then the Sent transaction is displayed with value: "1.38 tADA, 2 LaceCoin2" and tokens count 2
Then the Sent transaction is displayed with value: "-1.56 tADA, -2 LaceCoin2" and tokens count 2
And I click on a transaction: 1
Then The Tx details are displayed as "core.activityDetails.sent" for ADA with value: "1.38" and LaceCoin2 with value: "2" and wallet: "WalletReceiveDappTransactionE2E" address
When I open wallet: "WalletReceiveDappTransactionE2E" in: extended mode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Feature: Send Simple Transactions - Extended view - E2E
And I navigate to Tokens extended page
Then the sent amount of: "1.123" with "saved" fee for token "Cardano" is subtracted from the total balance
When I navigate to Transactions extended page
Then the Sent transaction is displayed with value: "1.12 tADA" and tokens count 1
Then the Sent transaction is displayed with value: "1.29 tADA" and tokens count 1
And I click and open recent transactions details until find transaction with correct hash
Then The Tx details are displayed as "core.activityDetails.sent" for ADA with value: 1.12 and wallet: "WalletReceiveSimpleTransactionE2E" address
When I open wallet: "WalletReceiveSimpleTransactionE2E" in: extended mode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Feature: Send Simple Transactions - Popup view - E2E
And I navigate to Tokens popup page
Then the sent amount of: "1.123" with "saved" fee for token "Cardano" is subtracted from the total balance
When I navigate to Transactions popup page
Then the Sent transaction is displayed with value: "1.12 tADA" and tokens count 1
Then the Sent transaction is displayed with value: "1.29 tADA" and tokens count 1
And I click and open recent transactions details until find transaction with correct hash
Then The Tx details are displayed as "core.activityDetails.sent" for ADA with value: 1.12 and wallet: "WalletReceiveSimpleTransaction2E2E" address
When I open wallet: "WalletReceiveSimpleTransaction2E2E" in: popup mode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ Feature: Delegating funds to new pool E2E
And valid password is not in snapshot
When I close the drawer by clicking close button
And I navigate to Transactions extended page
Then the Sent transaction is displayed with value: "5.00 tADA" and tokens count 1
Then the Sent transaction is displayed with value: "-15.17 tADA" and tokens count 1
When I open wallet: "newCreatedWallet" in: extended mode
And Wallet is synced
And I navigate to Transactions extended page
Then the Received transaction is displayed with value: "5.00 tADA" and tokens count 1
Then the Received transaction is displayed with value: "15.00 tADA" and tokens count 1
And I disable showing Multidelegation beta banner
And I disable showing Multidelegation DApps issue modal
And I navigate to Staking extended page
Expand Down
1 change: 1 addition & 0 deletions packages/e2e-tests/src/helpers/NFTPageHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const progressWithSendUntilPasswordPage = async (
await TransactionNewPage.coinConfigure(1).fillTokenValue(1);
await TransactionNewPage.reviewTransactionButton.waitForClickable({ timeout: 15_000 });
await TransactionNewPage.reviewTransactionButton.click();
await TransactionSummaryPage.saveFeeValue();
await TransactionSummaryPage.confirmButton.waitForClickable();
await TransactionSummaryPage.confirmButton.click();
};
9 changes: 7 additions & 2 deletions packages/e2e-tests/src/steps/nftsCommonSteps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,16 @@ Then(
name: string,
mode: 'extended' | 'popup'
) => {
const fee = typeOfAsset === 'NFT' ? '1.17' : '1.19';
const fee = Number(String(testContext.load('feeValue')).split(' ')[0]);
const adaAllocationValue = typeOfAsset === 'NFT' ? 1.17 : 1.19;
const adaValue = transactionType === 'Sent' ? -(adaAllocationValue + fee) : adaAllocationValue;
const assetValue = transactionType === 'Received' ? 1 : -1;
const expectedTransactionRowAssetDetailsSent = {
type: transactionType,
tokensAmount:
mode === 'extended' ? `${fee} ${Asset.CARDANO.ticker}, 1 ${name}` : `${fee} ${Asset.CARDANO.ticker} , +1`,
mode === 'extended'
? `${adaValue.toFixed(2)} ${Asset.CARDANO.ticker}, ${assetValue} ${name}`
: `${adaValue.toFixed(2)} ${Asset.CARDANO.ticker} , +1`,
tokensCount: 2
};
await transactionsPageAssert.assertSeeTransactionRowWithAssetDetails(0, expectedTransactionRowAssetDetailsSent);
Expand Down

0 comments on commit 37ffbe2

Please sign in to comment.