Skip to content

Commit

Permalink
feat(staking): drop "rewards" (mislabeled withdrawals) from activity,…
Browse files Browse the repository at this point in the history
… merge transformers
  • Loading branch information
refi93 committed Oct 10, 2023
1 parent c3fde72 commit 6ae38aa
Show file tree
Hide file tree
Showing 13 changed files with 203 additions and 326 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { getTransactionTotalOutput } from '../../utils/get-transaction-total-out
import { inspectTxValues } from '@src/utils/tx-inspection';
import { firstValueFrom } from 'rxjs';
import { getAssetsInformation } from '@src/utils/get-assets-information';
import { getRewardsAmount } from '@src/views/browser-view/features/activity/helpers';
import { MAX_POOLS_COUNT } from '@lace/staking';
import { TransactionType } from '@lace/core';

Expand Down Expand Up @@ -169,31 +168,14 @@ const getTransactionDetail =
transaction = {
...transaction,
pools: pools.map((pool) => ({
name: pool.metadata.name || '-',
ticker: pool.metadata.ticker || '-',
name: pool.metadata?.name || '-',
ticker: pool.metadata?.ticker || '-',
id: pool.id.toString()
}))
};
}
}

/*
as we need to divide the transaction that withdrawn rewards in to two records,
now we have a type rewards.
When the record is of type rewards we will need to calculate the amount of rewards withdrawn
and then adds this property rewards to the transaction information
*/
if (type === 'rewards') {
const rewards = getRewardsAmount(
tx?.body?.withdrawals,
walletInfo.addresses.map((addr) => addr.rewardAccount)
);
transaction = {
...transaction,
rewards: Wallet.util.lovelacesToAdaString(rewards)
};
}

set({ fetchingTransactionInfo: false });
return { tx: transaction, blocks, status, assetAmount, type };
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ const getWalletActivitiesObservable = async ({

/**
* 1. Listens for time settings
* 2. Passes it to hisorical transactions and pending transactions lists
* 2. Passes it to historical transactions and pending transactions lists
* 3. Emits both lists combined and sets current state for Zustand
*/
return combineLatest([eraSummaries$, pendingTransactions$, historicalTransactions$]).pipe(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ describe('testing tx-inspection utils', () => {
expect(getTxDirection({ type: 'incoming' })).toEqual(TxDirections.Incoming);
expect(getTxDirection({ type: 'rewards' })).toEqual(TxDirections.Outgoing);
expect(getTxDirection({ type: 'outgoing' })).toEqual(TxDirections.Outgoing);
expect(getTxDirection({ type: 'self-rewards' })).toEqual(TxDirections.Self);
expect(getTxDirection({ type: 'self' })).toEqual(TxDirections.Self);
});
});
Expand Down Expand Up @@ -258,7 +257,7 @@ describe('testing tx-inspection utils', () => {
] as Wallet.KeyManagement.GroupedAddress[]
});

expect(result).toBe('self-rewards');
expect(result).toBe('self');
});

test('is self', () => {
Expand Down
15 changes: 4 additions & 11 deletions apps/browser-extension-wallet/src/utils/tx-inspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,17 @@ const hasWalletStakeAddress = (
) => withdrawals.some((item) => item.stakeAddress === stakeAddress);

interface TxTypeProps {
type: TransactionType | 'self-rewards';
type: TransactionType;
}

export const getTxDirection = ({ type }: TxTypeProps): TxDirection => {
export const getTxDirection = ({ type }: TxTypeProps): TxDirections => {
switch (type) {
case 'incoming':
return TxDirections.Incoming;
case 'rewards':
return TxDirections.Outgoing;
case 'outgoing':
return TxDirections.Outgoing;
case 'self-rewards':
return TxDirections.Self;
case 'self':
return TxDirections.Self;
}
Expand All @@ -49,7 +47,7 @@ export const inspectTxType = ({
}: {
walletAddresses: Wallet.KeyManagement.GroupedAddress[];
tx: Wallet.Cardano.HydratedTx;
}): TransactionType | 'self-rewards' => {
}): Exclude<TransactionType, 'rewards'> => {
const { paymentAddresses, rewardAccounts } = walletAddresses.reduce(
(acc, curr) => ({
paymentAddresses: [...acc.paymentAddresses, curr.address],
Expand All @@ -74,26 +72,21 @@ export const inspectTxType = ({
inspectionProperties.totalWithdrawals > BigInt(0) &&
walletAddresses.some((addr) => hasWalletStakeAddress(tx.body.withdrawals, addr.rewardAccount));

if (inspectionProperties.sent.inputs.length > 0) {
if (inspectionProperties.sent.inputs.length > 0 || withRewardsWithdrawal) {
switch (true) {
case !!inspectionProperties.delegation[0]?.poolId:
return 'delegation';
case inspectionProperties.stakeKeyRegistration.length > 0:
return 'delegationRegistration';
case inspectionProperties.stakeKeyDeregistration.length > 0:
return 'delegationDeregistration';
case withRewardsWithdrawal && inspectionProperties.selfTransaction:
return 'self-rewards';
case withRewardsWithdrawal:
return 'rewards';
case inspectionProperties.selfTransaction:
return 'self';
default:
return 'outgoing';
}
}

if (withRewardsWithdrawal) return 'rewards';
return 'incoming';
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ let actualLovelacesToAdaString: any;
/* eslint-disable import/imports-first */
/* eslint-disable max-len */
/* eslint-disable no-magic-numbers */
import { pendingTxTransformer, getFormattedFiatAmount } from '../pending-tx-transformer';
import { pendingTxTransformer } from '../pending-tx-transformer';
import { Wallet } from '@lace/cardano';
import { cardanoCoin } from '@utils/constants';
import { TxCBOR } from '@cardano-sdk/core';
import { DEFAULT_TIME_FORMAT, formatTime } from '@src/utils/format-date';
import BigNumber from 'bignumber.js';
import { getFormattedFiatAmount } from '../common-tx-transformer';

jest.mock('@lace/cardano', () => {
const actual = jest.requireActual<any>('@lace/cardano');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ const mockGetFormattedAmount = jest.fn();
/* eslint-disable max-len */
/* eslint-disable no-magic-numbers */
/* eslint-disable import/imports-first */
import * as txTransformers from '../common-tx-transformer';
import * as txHistoryTransformers from '../tx-history-transformer';
import { Wallet } from '@lace/cardano';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { cardanoCoin } from '@src/utils/constants';
import * as txInspection from '@src/utils/tx-inspection';
import * as pendingTxTransformer from '../pending-tx-transformer';
import { TxDirection } from '@src/types';
import { AssetActivityItemProps } from '@lace/core';
import type { TxDirections } from '@src/types';

jest.mock('@lace/cardano', () => {
const actual = jest.requireActual<any>('@lace/cardano');
Expand Down Expand Up @@ -73,7 +72,12 @@ describe('Testing txHistoryTransformer function', () => {
invalidBefore: Wallet.Cardano.Slot(1),
invalidHereafter: Wallet.Cardano.Slot(2)
},
withdrawals: [{ quantity: BigInt(2) } as Wallet.Cardano.Withdrawal]
withdrawals: [
{
quantity: BigInt(2),
stakeAddress: Wallet.Cardano.RewardAccount('stake_test1uq7g7kqeucnqfweqzgxk3dw34e8zg4swnc7nagysug2mm4cm77jrx')
} as Wallet.Cardano.Withdrawal
]
},
witness: {
signatures: new Map()
Expand Down Expand Up @@ -105,8 +109,8 @@ describe('Testing txHistoryTransformer function', () => {
protocolParameters: { poolDeposit: 3, stakeKeyDeposit: 2 } as Wallet.ProtocolParameters,
cardanoCoin
});
expect(result.status).toBe('success');
expect(result.amount).toBe('20.00 ADA');
expect(result[0].status).toBe('success');
expect(result[0].amount).toBe('20.00 ADA');
});

test('should return parsed outgoing tx', async () => {
Expand All @@ -132,31 +136,21 @@ describe('Testing txHistoryTransformer function', () => {
protocolParameters: { poolDeposit: 3, stakeKeyDeposit: 2 } as Wallet.ProtocolParameters,
cardanoCoin
});
expect(result.status).toBe('success');
expect(result.amount).toBe('30.00 ADA');
expect(result[0].status).toBe('success');
expect(result[0].amount).toBe('30.00 ADA');
});

test('should return tx of reward type', async () => {
test('should return outgoing tx with withdrawal only as outgoing tx', async () => {
const direction = 'tx-direction';
const rewardsAmount = '10';
const formattedAmount = 'getFormattedAmount';
const formattedFiatAmount = 'getFormattedFiatAmount';
const transformedTx = {
date: 'date',
timestamp: 'timestamp'
};
mockGetFormattedAmount.mockReturnValueOnce(formattedAmount);
const getFormattedFiatAmountSpy = jest
.spyOn(pendingTxTransformer, 'getFormattedFiatAmount')
.spyOn(txTransformers, 'getFormattedFiatAmount')
.mockReturnValueOnce(formattedFiatAmount);
const txTransformerSpy = jest
.spyOn(pendingTxTransformer, 'txTransformer')
.mockReturnValueOnce(transformedTx as unknown as Omit<AssetActivityItemProps, 'onClick'>);
const inspectTxTypeSpy = jest.spyOn(txInspection, 'inspectTxType').mockReturnValueOnce('self-rewards');
const getTxDirectionSpy = jest.spyOn(txInspection, 'getTxDirection').mockReturnValueOnce(direction as TxDirection);
const getRewardsAmountSpy = jest
.spyOn(txHistoryTransformers, 'getRewardsAmount')
.mockReturnValueOnce(rewardsAmount);
const txTransformerSpy = jest.spyOn(txTransformers, 'txTransformer');
const inspectTxTypeSpy = jest.spyOn(txInspection, 'inspectTxType');
const getTxDirectionSpy = jest.spyOn(txInspection, 'getTxDirection').mockReturnValueOnce(direction as TxDirections);

const props = {
tx: txHistory,
Expand Down Expand Up @@ -186,12 +180,8 @@ describe('Testing txHistoryTransformer function', () => {
tx: props.tx
});
expect(getTxDirectionSpy).toBeCalledWith({
type: 'self-rewards'
type: 'outgoing'
});
expect(getRewardsAmountSpy).toBeCalledWith(
props.tx?.body?.withdrawals,
props.walletAddresses.map((addr) => addr.rewardAccount)
);
expect(txTransformerSpy).toBeCalledWith({
tx: props.tx,
walletAddresses: props.walletAddresses,
Expand All @@ -204,24 +194,12 @@ describe('Testing txHistoryTransformer function', () => {
direction,
date: '01 February 2022'
});
expect(result).toEqual([
{ ...transformedTx, type: 'self' },
{
type: 'rewards',
direction: 'Incoming',
amount: formattedAmount,
fiatAmount: formattedFiatAmount,
status: Wallet.TransactionStatus.SPENDABLE,
date: transformedTx.date,
assets: [],
timestamp: transformedTx.timestamp
}
]);
expect(result[0].status).toBe('success');
expect(result[0].type).toBe('outgoing');

txTransformerSpy.mockRestore();
inspectTxTypeSpy.mockRestore();
getTxDirectionSpy.mockRestore();
getFormattedFiatAmountSpy.mockRestore();
getRewardsAmountSpy.mockRestore();
});
});

This file was deleted.

Loading

0 comments on commit 6ae38aa

Please sign in to comment.