Skip to content

Commit 37ffbe2

Browse files
fix(extension): replace local logic with txSummaryInspector - LW-11936 (#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]>
1 parent 9a05eba commit 37ffbe2

17 files changed

+72
-75
lines changed

apps/browser-extension-wallet/src/stores/slices/wallet-activities-slice.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@ import {
2222
AssetActivityItemProps,
2323
AssetActivityListProps,
2424
ConwayEraCertificatesTypes,
25-
DelegationActivityType,
26-
TransactionActivityType
25+
DelegationActivityType
2726
} from '@lace/core';
2827
import { CurrencyInfo, TxDirections } from '@src/types';
2928
import { getTxDirection, inspectTxType } from '@src/utils/tx-inspection';
@@ -91,7 +90,7 @@ const getDelegationAmount = (activity: DelegationActivityItemProps) => {
9190
activity.type === DelegationActivityType.delegationRegistration ||
9291
activity.type === ConwayEraCertificatesTypes.Registration
9392
) {
94-
return fee.plus(activity.deposit);
93+
return fee.plus(activity.deposit).negated();
9594
}
9695

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

104-
return fee;
103+
return fee.negated();
105104
};
106105

107106
const FIAT_PRICE_DECIMAL_PLACES = 2;
@@ -371,12 +370,6 @@ const mapWalletActivities = memoize(
371370
amount: `${getDelegationAmount(activity)} ${cardanoCoin.symbol}`,
372371
fiatAmount: `${getFiatAmount(getDelegationAmount(activity), cardanoFiatPrice)} ${fiatCurrency.code}`
373372
}),
374-
...(activity.type === TransactionActivityType.self && {
375-
amount: `${activity.fee} ${cardanoCoin.symbol}`,
376-
fiatAmount: cardanoFiatPrice
377-
? `${getFiatAmount(new BigNumber(activity.fee), cardanoFiatPrice)} ${fiatCurrency.code}`
378-
: '-'
379-
}),
380373
assets: activity.assets.map((asset: ActivityAssetProp) => {
381374
const assetId = Wallet.Cardano.AssetId(asset.id);
382375
const token = assetsInfo.get(assetId);

apps/browser-extension-wallet/src/utils/mocks/test-helpers.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export const mockWalletState: ObservableWalletState = {
8383
value: { assets: new Map(), coins: BigInt(200) }
8484
}
8585
],
86-
fee: '100000'
86+
fee: BigInt(100_000)
8787
}
8888
} as unknown as Wallet.Cardano.HydratedTx
8989
],

apps/browser-extension-wallet/src/views/browser-view/features/activity/helpers/__tests__/pending-tx-transformer.test.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,10 @@ describe('Testing tx transformers utils', () => {
106106
Promise.resolve({
107107
address: sendingAddress,
108108
value: {
109-
coins: BigInt('2000000')
109+
coins: BigInt('2000000'),
110+
assets: new Map([
111+
[Wallet.Cardano.AssetId('6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7'), BigInt('100')]
112+
]) as Wallet.Cardano.TokenMap
110113
}
111114
})
112115
});
@@ -118,13 +121,13 @@ describe('Testing tx transformers utils', () => {
118121
depositReclaim: undefined,
119122
direction: 'Outgoing',
120123
fee: '1.00',
121-
fiatAmount: '1.00 USD',
124+
fiatAmount: '-2.00 USD',
122125
id: '6804edf9712d2b619edb6ac86861fe93a730693183a262b165fcc1ba1bc99cad',
123-
amount: '1.00 ADA',
126+
amount: '-2.00 ADA',
124127
assets: [
125128
{
126129
id: '6b8d07d69639e9413dd637a1a815a7323c69c86abbafb66dbfdb1aa7',
127-
val: '100'
130+
val: '-100'
128131
}
129132
],
130133
assetsNumber: 2,

apps/browser-extension-wallet/src/views/browser-view/features/activity/helpers/common-tx-transformer.ts

Lines changed: 38 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,17 @@
44
import BigNumber from 'bignumber.js';
55
import { Wallet } from '@lace/cardano';
66
import { CurrencyInfo, TxDirections } from '@types';
7-
import { inspectTxValues, inspectTxType, txIncludesConwayCertificates } from '@src/utils/tx-inspection';
7+
import { inspectTxType, txIncludesConwayCertificates } from '@src/utils/tx-inspection';
88
import { formatDate, formatTime } from '@src/utils/format-date';
9-
import { getTransactionTotalAmount } from '@src/utils/get-transaction-total-amount';
109
import type { TransformedActivity, TransformedTransactionActivity } from './types';
1110
import { ActivityStatus, ConwayEraCertificatesTypes, DelegationActivityType } from '@lace/core';
1211
import capitalize from 'lodash/capitalize';
1312
import dayjs from 'dayjs';
1413
import { hasPhase2ValidationFailed } from '@src/utils/phase2-validation';
14+
import { createTxInspector, Milliseconds, transactionSummaryInspector } from '@cardano-sdk/core';
1515

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

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

112113
type GetTxFormattedAmount = (
113-
args: Pick<
114-
TxTransformerInput,
115-
'walletAddresses' | 'tx' | 'direction' | 'resolveInput' | 'cardanoCoin' | 'fiatCurrency' | 'fiatPrice'
116-
>
114+
args: Pick<TxTransformerInput, 'tx' | 'cardanoCoin' | 'fiatCurrency' | 'fiatPrice'> & { amount: bigint }
117115
) => Promise<{
118116
amount: string;
119117
fiatAmount: string;
120118
}>;
121119

122-
const getTxFormattedAmount: GetTxFormattedAmount = async ({
123-
resolveInput,
124-
tx,
125-
walletAddresses,
126-
direction,
127-
cardanoCoin,
128-
fiatCurrency,
129-
fiatPrice
130-
}) => {
120+
const getTxFormattedAmount: GetTxFormattedAmount = async ({ tx, cardanoCoin, fiatCurrency, fiatPrice, amount }) => {
121+
const outputAmount = new BigNumber(amount.toString());
131122
const transaction = 'tx' in tx ? tx.tx : tx;
132123
const { body } = transaction;
133124
if (hasPhase2ValidationFailed(transaction)) {
@@ -141,16 +132,6 @@ const getTxFormattedAmount: GetTxFormattedAmount = async ({
141132
};
142133
}
143134

144-
const outputAmount = await getTransactionTotalAmount({
145-
addresses: walletAddresses,
146-
inputs: body.inputs,
147-
outputs: body.outputs,
148-
fee: body.fee,
149-
direction,
150-
withdrawals: body.withdrawals,
151-
resolveInput
152-
});
153-
154135
return {
155136
amount: Wallet.util.getFormattedAmount({ amount: outputAmount.toString(), cardanoCoin }),
156137
fiatAmount: getFormattedFiatAmount({ amount: outputAmount, fiatCurrency, fiatPrice })
@@ -186,17 +167,36 @@ export const txTransformer = async ({
186167
isSharedWallet
187168
}: TxTransformerInput): Promise<TransformedTransactionActivity[]> => {
188169
const transaction = 'tx' in tx ? tx.tx : tx;
189-
const implicitCoin = util.computeImplicitCoin(protocolParameters, transaction.body);
190-
const deposit = implicitCoin.deposit ? Wallet.util.lovelacesToAdaString(implicitCoin.deposit.toString()) : undefined;
191-
const depositReclaimValue = Wallet.util.calculateDepositReclaim(implicitCoin);
170+
171+
const txSummaryInspector = createTxInspector({
172+
summary: transactionSummaryInspector({
173+
addresses: walletAddresses.map((addr) => addr.address),
174+
rewardAccounts: walletAddresses.map((addr) => addr.rewardAccount),
175+
inputResolver: { resolveInput },
176+
protocolParameters,
177+
// Using a dummy asset provider as we don't need to fetch assets for the summary
178+
// On reject, the summary inspector will use the information it can extract from the assetId, and
179+
// all we need here is the id and the amount
180+
assetProvider: {
181+
getAsset: () => Promise.reject({}),
182+
getAssets: () => Promise.reject({}),
183+
healthCheck: () => Promise.resolve({ ok: true })
184+
},
185+
timeout: TIMEOUT,
186+
logger: console
187+
})
188+
});
189+
190+
// TODO: LW-8767 investigate why in-flight transactions do not have a `witness` property and add it
191+
const { summary } = await txSummaryInspector({ witness: undefined, ...transaction });
192+
193+
const deposit = summary.deposit ? Wallet.util.lovelacesToAdaString(summary.deposit.toString()) : undefined;
194+
const depositReclaimValue = summary.returnedDeposit;
192195
const depositReclaim = depositReclaimValue
193196
? Wallet.util.lovelacesToAdaString(depositReclaimValue.toString())
194197
: undefined;
195-
const { assets } = await inspectTxValues({
196-
addresses: walletAddresses,
197-
tx: transaction as unknown as Wallet.Cardano.HydratedTx,
198-
direction
199-
});
198+
199+
const assets = summary.assets;
200200

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

209209
const assetsEntries = assets
210210
? [...assets.entries()]
211-
.map(([id, val]) => ({ id: id.toString(), val: val.toString() }))
211+
.map(([id, { amount: val }]) => ({ id: id.toString(), val: val.toString() }))
212212
.sort((a, b) => Number(b.val) - Number(a.val))
213213
: [];
214214

215215
const formattedAmount = await getTxFormattedAmount({
216216
cardanoCoin,
217217
fiatCurrency,
218-
resolveInput,
219218
tx,
220-
walletAddresses,
221-
direction,
222-
fiatPrice
219+
fiatPrice,
220+
amount: summary.coins
223221
});
224222

225223
const baseTransformedActivity = {
226224
id: transaction.id.toString(),
227225
deposit,
228226
depositReclaim,
229-
fee: Wallet.util.lovelacesToAdaString(transaction.body.fee.toString()),
227+
fee: Wallet.util.lovelacesToAdaString(summary.fee.toString()),
230228
status: transformTransactionStatus(transaction, status),
231229
amount: formattedAmount.amount,
232230
fiatAmount: formattedAmount.fiatAmount,

packages/core/src/ui/components/Activity/AssetActivityItem.tsx

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -243,10 +243,7 @@ export const AssetActivityItem = ({
243243
ref={ref}
244244
>
245245
<span>
246-
<span data-testid="balance">
247-
{isNegativeBalance ? '-' : ''}
248-
{assetsText.text}
249-
</span>
246+
<span data-testid="balance">{assetsText.text}</span>
250247
{assetsText.suffix && (
251248
<Tooltip
252249
overlayClassName={styles.tooltip}

packages/core/src/ui/components/Activity/__tests__/AssetActivityItem.test.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ describe('Testing AssetActivityItem component', () => {
5151

5252
const totalAmount = await findByTestId('balance');
5353

54-
expect(totalAmount).toHaveTextContent(`-${props.amount}`);
54+
expect(totalAmount).toHaveTextContent(`${props.amount}`);
5555
});
5656
});
5757

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

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

7171
expect(activityAssetTickerText).toBeVisible();

packages/e2e-tests/src/features/HdWalletExtended.feature

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Feature: HD wallet - extended view
1818
Then I can see transaction <txNumber> has type "<txType>" and value "<txValue>"
1919
Examples:
2020
| txNumber | txType | txValue | Notes |
21-
| 1 | Sent | 17.00 | |
21+
| 1 | Sent | 17.19 | |
2222
| 2 | Received | 16.00 | Was received to not first address |
2323
| 3 | Received | 4.00 | Was received to first address |
2424
| 6 | Self Transaction | 0.17 | Was send to first address |

packages/e2e-tests/src/features/TransactionsExtended.part2.feature

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Feature: Transactions - Extended view
3434
And I save tx hash value "a21a3069e214f34ef32e4797865233f87195b753a4cfbca7bed2ccf4807d98d0"
3535
And I am on Transactions extended page
3636
And I wait for the transaction history to be loaded and all transactions to be confirmed
37-
When the Sent transaction is displayed with value: "24.79 tADA" and tokens count 1
37+
When the Sent transaction is displayed with value: "25.00 tADA" and tokens count 1
3838
When I click on a transaction: 1
3939
Then The Tx details are displayed as "core.activityDetails.sent" for ADA with value: 24.79 and wallet: "addr_test1qp7vynpwhsyjsqvyw9n8r4uy3uj5hu2arfy94vynvng6556hhqrnhndmg2pntqazt36v700x6kryqjhe75p58v65v6kszx7h3j" address
4040

packages/e2e-tests/src/features/WalletAddressPageExtended.feature

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ Feature: Wallet address page
7171
And The Transaction submitted screen is displayed in extended mode
7272
And I close the drawer by clicking close button
7373
And I navigate to Transactions extended page
74-
And the Sent transaction is displayed with value: "2.00 tADA" and tokens count 1
74+
And the Sent transaction is displayed with value: "2.17 tADA" and tokens count 1
7575
And I open wallet: "UnusedAddressWallet" in: extended mode
7676
And I click "Receive" button on page header
7777
And I click "Wallet Address" "Advanced mode" toggle

packages/e2e-tests/src/features/analytics/AnalyticsSendExtended.feature

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Feature: Analytics - Posthog - Sending - Extended View
3030
And I click "View transaction" button on submitted transaction page
3131
And Local storage unconfirmedTransaction contains tx with type: "internal"
3232
And I validate latest analytics single event "send | all done | view transaction | click"
33-
When the Sent transaction is displayed with value: "2.12 tADA" and tokens count 1
33+
When the Sent transaction is displayed with value: "2.30 tADA" and tokens count 1
3434
Then I validate latest analytics single event "send | transaction confirmed"
3535
And I validate that the "send | transaction confirmed" event includes property "tx_creation_type" with value "internal" in posthog
3636
And I validate that 7 analytics event(s) have been sent
@@ -62,7 +62,7 @@ Feature: Analytics - Posthog - Sending - Extended View
6262
And I wait 2000 milliseconds
6363
And I set up request interception for posthog analytics request(s)
6464
Then Local storage unconfirmedTransaction contains tx with type: "external"
65-
When the Sent transaction is displayed with value: "3.00 tADA" and tokens count 1
65+
When the Sent transaction is displayed with value: "3.17 tADA" and tokens count 1
6666
Then I validate latest analytics single event "send | transaction confirmed"
6767
And I validate that the "send | transaction confirmed" event includes property "tx_creation_type" with value "external" in posthog
6868
And I validate that 1 analytics event(s) have been sent

0 commit comments

Comments
 (0)