Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adapt transactions #533

Merged
merged 6 commits into from
Nov 11, 2022
Merged
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@
"@dfinity/principal": "^0.9.3",
"@hookform/error-message": "^2.0.0",
"@psychedelic/dab-js": "1.4.12",
"@psychedelic/plug-controller": "0.24.9",
"@psychedelic/plug-controller": "0.25.0",
"@react-native-async-storage/async-storage": "^1.17.10",
"@react-native-clipboard/clipboard": "^1.11.1",
"@react-native-community/blur": "^4.2.0",
"@react-native-community/clipboard": "^1.5.1",
"@react-native-masked-view/masked-view": "^0.2.7",
"@react-navigation/bottom-tabs": "^6.4.0",
"@react-navigation/elements": "^1.3.6",
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/AccountInfo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Clipboard from '@react-native-community/clipboard';
import Clipboard from '@react-native-clipboard/clipboard';
import React, { useEffect, useState } from 'react';
import { View } from 'react-native';

Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Copy/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Clipboard from '@react-native-community/clipboard';
import Clipboard from '@react-native-clipboard/clipboard';
import { t } from 'i18next';
import React, { useEffect, useState } from 'react';
import { StyleProp, View, ViewStyle } from 'react-native';
Expand Down
10 changes: 6 additions & 4 deletions src/components/common/Toast/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export enum ToastTypes {

export interface ToastProps {
title: string;
message: string;
message?: string;
type: 'success' | 'error' | 'info';
id: string;
}
Expand Down Expand Up @@ -65,9 +65,11 @@ function Toast({ title, message, type, id }: ToastProps) {
<Close fill={Colors.White.Primary} height={20} />
</Touchable>
</View>
<Text type="caption" style={styles.message}>
{message}
</Text>
{message && (
<Text type="caption" style={styles.message}>
{message}
</Text>
)}
</LinearGradient>
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Toast/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ export default StyleSheet.create({
},
headerContainer: {
flexDirection: 'row',
marginBottom: 8,
alignItems: 'center',
justifyContent: 'space-between',
},
message: {
marginTop: 8,
color: Colors.White.Pure,
opacity: 0.8,
},
Expand Down
2 changes: 1 addition & 1 deletion src/components/common/Touchable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import scales from '@/utils/animationScales';

interface Props {
children?: React.ReactNode;
onPress?: () => void;
onPress?: (param?: any) => void;
onLongPress?: () => void;
hapticType?: HapticFeedbackTypes;
scale?: number;
Expand Down
11 changes: 9 additions & 2 deletions src/components/formatters/UsdFormat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ interface Props {
style?: StyleProp<TextStyle>;
decimalScale?: number;
suffix?: string;
numberOfLines?: number;
}

function UsdFormat({ value, style, decimalScale = 2, suffix }: Props) {
function UsdFormat({
value,
style,
decimalScale = 2,
suffix,
numberOfLines,
}: Props) {
return (
<NumberFormat
value={value}
Expand All @@ -23,7 +30,7 @@ function UsdFormat({ value, style, decimalScale = 2, suffix }: Props) {
suffix={suffix ? ` ${suffix}` : undefined}
renderText={(textValue: string) =>
textValue ? (
<Text type="body2" style={style}>
<Text numberOfLines={numberOfLines} type="body2" style={style}>
{textValue}
</Text>
) : null
Expand Down
6 changes: 3 additions & 3 deletions src/hooks/useCustomToast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ToastTypes } from '@/components/common/Toast';
function useCustomToast() {
const toast = useToast();

const showSuccess = useCallback((title: string, message: string) => {
const showSuccess = useCallback((title: string, message?: string) => {
toast.show(`${ToastTypes.success}-${title}`, {
data: {
type: ToastTypes.success,
Expand All @@ -16,7 +16,7 @@ function useCustomToast() {
});
}, []);

const showError = useCallback((title: string, message: string) => {
const showError = useCallback((title: string, message?: string) => {
toast.show(`${ToastTypes.error}-${title}`, {
data: {
type: ToastTypes.error,
Expand All @@ -26,7 +26,7 @@ function useCustomToast() {
});
}, []);

const showInfo = useCallback((title: string, message: string) => {
const showInfo = useCallback((title: string, message?: string) => {
toast.show(`${ToastTypes.info}-${title}`, {
data: {
type: ToastTypes.info,
Expand Down
43 changes: 12 additions & 31 deletions src/interfaces/redux.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import WalletConnect from '@walletconnect/client';

import { Nullable } from './general';
import { ICNSData } from './icns';
import { WCWhiteListItem } from './walletConnect';

Expand Down Expand Up @@ -53,40 +54,20 @@ export interface CanisterInfo {
symbol?: string;
}

interface Currency {
symbol: string;
decimals: number;
}

export interface TransactionDetails {
status: string; //check if this is correct
fee: {
amount: string;
currency: Currency;
};
from: string;
amount: string;
currency: Currency;
to: string;
caller: string;
}

export interface Transaction {
amount: string | number;
type: string; //TODO: Add types here SEND/RECEIVE. Check ACTIVITY_TYPES
symbol: string;
hash: string;
type: string;
to: string;
from: string;
date: Date;
image: string;
value?: string | number;
status?: number | string;
icon?: string;
canisterId?: string;
plug?: any;
canisterInfo?: CanisterInfo;
details?: TransactionDetails;
hash: string;
amount: Nullable<number | typeof NaN>;
value?: Nullable<number>;
status: number;
date: bigint;
symbol: string;
logo: string;
canisterId: string;
details?: { [key: string]: any };
canisterInfo?: Object;
Copy link
Contributor

Choose a reason for hiding this comment

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

what about the interface CanisterInfo that we have above?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I use the same one as in the Controller cuz otherwise i was getting problems with TS

}

export interface Asset {
Expand Down
24 changes: 4 additions & 20 deletions src/redux/slices/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Principal } from '@dfinity/principal';
import { Address } from '@psychedelic/plug-controller/dist/interfaces/contact_registry';
import { createAsyncThunk, createSlice, isAnyOf } from '@reduxjs/toolkit';

import { JELLY_CANISTER_ID } from '@/constants/canister';
import { ENABLE_NFTS } from '@/constants/nfts';
import {
CollectionInfo,
Expand Down Expand Up @@ -35,7 +34,6 @@ import {
DEFAULT_TRANSACTION,
formatContact,
formatContactForController,
formatTransaction,
mattgle marked this conversation as resolved.
Show resolved Hide resolved
TRANSACTION_STATUS,
} from '../utils';

Expand Down Expand Up @@ -184,25 +182,11 @@ export const getTransactions = createAsyncThunk<
try {
const { icpPrice } = params;
const instance = KeyRing.getInstance();
const currentWalletId = instance?.currentWalletId;
const state = await instance?.getState();
const currentWallet = state.wallets[currentWalletId];
const response = await instance?.getTransactions({});
let parsedTrx =
response?.transactions?.map(formatTransaction(icpPrice, currentWallet)) ||
[];

if (!ENABLE_NFTS) {
parsedTrx = parsedTrx.filter(
item =>
!(
item?.symbol === 'NFT' ||
item?.details.canisterId === JELLY_CANISTER_ID
)
);
}
const { transactions } = await instance?.getTransactions({
icpPrice,
});

return parsedTrx;
return transactions;
} catch (e: any) {
return rejectWithValue(e.message);
}
Expand Down
110 changes: 0 additions & 110 deletions src/redux/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@ import Flatted from 'flatted';
import { t } from 'i18next';

import { TOKEN_IMAGES, TOKENS } from '@/constants/assets';
import { ACTIVITY_STATUS } from '@/constants/business';
import {
KEYRING_KEYS_IN_STORAGE,
KEYRING_STORAGE_KEY,
} from '@/constants/keyring';
import { formatAssetBySymbol, parseToFloatAmount } from '@/utils/currencies';
import { validateAccountId, validatePrincipalId } from '@/utils/ids';
import { recursiveParseBigint } from '@/utils/objects';

import { clear } from './slices/keyring';
import {
Expand Down Expand Up @@ -82,113 +79,6 @@ export const getNewAccountData = async (dispatch, icpPrice) => {
dispatch(getContacts());
};

const parseTransactionObject = transactionObject => {
const { amount, currency, token, sonicData, canisterInfo } =
transactionObject;

const { decimals } = {
...currency,
...token,
...(sonicData?.token ?? {}),
...(canisterInfo?.tokenRegistryInfo?.details ?? {}),
};
// TODO: Decimals are currently not in DAB. Remove once they are added.
const parsedAmount = parseToFloatAmount(
amount,
decimals || TOKENS[sonicData?.token?.details?.symbol]?.decimals
);

return {
...transactionObject,
amount: parsedAmount,
};
};

const parseTransaction = transaction => {
const { details } = transaction;
const { fee } = details;

const parsedDetails = parseTransactionObject(details);
let parsedFee = fee;

if (fee instanceof Object && ('token' in fee || 'currency' in fee)) {
parsedFee = parseTransactionObject(fee);
}

return {
...transaction,
details: {
...parsedDetails,
fee: parsedFee,
},
};
};

const getTransactionSymbol = details => {
if (!details) {
return '';
}
if ('tokenRegistryInfo' in (details?.canisterInfo || [])) {
return details?.canisterInfo.tokenRegistryInfo.symbol;
}
if ('nftRegistryInfo' in (details?.canisterInfo || [])) {
return 'NFT';
}
return (
details?.currency?.symbol ??
details?.sonicData?.token?.details?.symbol ??
details?.details?.name ??
''
);
};

const getTransactionType = (type, isOwnTx) => {
if (!type) {
return '';
}
if (type.includes('transfer')) {
return isOwnTx ? 'SEND' : 'RECEIVE';
}
if (type.includes('Liquidity')) {
return `${type.includes('removeLiquidity') ? 'Remove' : 'Add'} Liquidity`;
}
return type.toUpperCase();
};

export const formatTransaction = (icpPrice, currentWallet) => trx => {
const { principal, accountId } = currentWallet;

let parsedTransaction = recursiveParseBigint(parseTransaction(trx));
const { details, hash, caller, timestamp } = parsedTransaction || {};
const isOwnTx = [principal, accountId].includes(caller);

const symbol = getTransactionSymbol(details);
const asset = formatAssetBySymbol(details?.amount, symbol, icpPrice);
const type = getTransactionType(parsedTransaction?.type, isOwnTx);

const transaction = {
amount: asset.amount,
value: asset.value,
icon: asset.icon,
type,
hash,
to: details?.to?.icns || details?.to?.principal,
from: details?.from?.icns || details?.from?.principal || caller,
date: new Date(timestamp),
status: ACTIVITY_STATUS[details?.status],
image: details?.canisterInfo?.icon || TOKEN_IMAGES[symbol] || '',
symbol,
canisterId: details?.canisterId,
plug: null,
canisterInfo: details?.canisterInfo,
details: {
...details,
caller,
},
};
return transaction;
};

export const formatContact = contact => {
const [id] = Object.values(contact.value);

Expand Down
2 changes: 1 addition & 1 deletion src/screens/flows/Deposit/components/IDDetails/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Clipboard from '@react-native-community/clipboard';
import Clipboard from '@react-native-clipboard/clipboard';
import React, { useEffect, useState } from 'react';

import CopiedToast from '@/commonComponents/CopiedToast';
Expand Down
10 changes: 4 additions & 6 deletions src/screens/flows/Send/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { getICPPrice } from '@/redux/slices/icp';
import { sendToken, setTransaction, transferNFT } from '@/redux/slices/user';
import { formatCollections, FormattedCollection } from '@/utils/assets';
import {
isOwnAddress,
validateAccountId,
validateICNSName,
validatePrincipalId,
Expand Down Expand Up @@ -186,20 +187,17 @@ function Send({ route }: ScreenProps<Routes.SEND>) {
}

const savedContact = contacts?.find(c => c.id === text);
const isOwnAddress =
text === currentWallet?.principal ||
text === currentWallet?.accountId ||
text === currentWallet?.icnsData?.reverseResolvedName;
const isOwn = isOwnAddress(text, currentWallet!);

if (savedContact && !isOwnAddress) {
if (savedContact && !isOwn) {
setReceiver({
...savedContact,
isValid: true,
});
scrollToTop();
} else {
const isValid =
!isOwnAddress && (validatePrincipalId(text) || validateAccountId(text));
!isOwn && (validatePrincipalId(text) || validateAccountId(text));
setReceiver({ id: text, isValid });
}
};
Expand Down
Loading