Skip to content

Commit

Permalink
Merge pull request #500 from Peersyst/dev
Browse files Browse the repository at this point in the history
1.1.6 Release
  • Loading branch information
AdriaCarrera authored Mar 15, 2023
2 parents dbeeb1d + 2a6a7d8 commit 66947b0
Show file tree
Hide file tree
Showing 18 changed files with 156 additions and 72 deletions.
22 changes: 8 additions & 14 deletions src/module/common/service/CkbSdkService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class CKBSDKService {
chain: Chain,
mnemonic: string,
walletState?: WalletState,
onSync?: (walletState: WalletState) => Promise<void>,
onSync?: (walletState?: WalletState) => Promise<void>,
onSyncStart?: () => void,
) {
this.connectionService = chain === "testnet" ? testnetConnectionService : mainnetConnectionService;
Expand All @@ -71,7 +71,12 @@ export class CKBSDKService {

static getFullTransactionFromTransaction(transaction: Transaction): FullTransaction {
if ([TransactionType.RECEIVE_TOKEN, TransactionType.SEND_TOKEN].includes(transaction.type) && transaction.scriptType) {
return { ...transaction, token: getTokenTypeFromScript(transaction.scriptType).tokenName };
const tokenType = getTokenTypeFromScript(transaction.scriptType);
return {
...transaction,
token: tokenType.tokenName,
tokenType,
};
}
return transaction;
}
Expand All @@ -89,19 +94,8 @@ export class CKBSDKService {
}

getTransactions(): FullTransaction[] {
const fullTxs: FullTransaction[] = [];
const transactions = this.wallet.getTransactions();
for (const tx of transactions) {
if ([TransactionType.RECEIVE_TOKEN, TransactionType.SEND_TOKEN].includes(tx.type) && tx.scriptType) {
const tokenIndex = getTokenIndexTypeFromScript(tx.scriptType);
if (tokenIndex !== -1) {
fullTxs.push({ ...tx, token: getTokenTypeFromIndex(tokenIndex).tokenName });
}
} else {
fullTxs.push(tx);
}
}
return fullTxs;
return transactions.map((tx) => CKBSDKService.getFullTransactionFromTransaction(tx));
}

async getTransaction(txHash: string): Promise<FullTransaction> {
Expand Down
4 changes: 3 additions & 1 deletion src/module/common/service/CkbSdkService.types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DAOUnlockableAmount, FeeRate, Nft, Transaction } from "ckb-peersyst-sdk";
import { TokenType } from "module/token/types";

export type Chain = "mainnet" | "testnet";

Expand Down Expand Up @@ -37,5 +38,6 @@ export interface WithdrawOrUnlockParams {
}

export interface FullTransaction extends Transaction {
token?: string;
token?: string; //CKB or tokenName
tokenType?: TokenType;
}
2 changes: 1 addition & 1 deletion src/module/dao/component/core/DAOAccountCard/DAOCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const DAOCard = ({ wallet, style }: WalletComponentCardProps) => {
const { data: { estimated_apc = "0.0000" } = {}, isLoading: loadingDao } = useGetDaoInfo();
const { data: { freeBalance = 0 } = {}, isLoading: balanceLoading } = useGetBalance();

const loading = daoBalanceLoading || loadingDao || balanceLoading;
const loading = daoBalanceLoading || loadingDao || balanceLoading || wallet.synchronizingCells;

return (
<WalletCard wallet={wallet} style={style} nameVariant="body2Light">
Expand Down
3 changes: 1 addition & 2 deletions src/module/sdk/core/assets/nft.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export interface MNft {
total: number;
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export enum NftTypes {
nrc721 = "nrc721",
Expand Down Expand Up @@ -150,7 +150,6 @@ export class NftService {
nodeUrl: this.connection.getCKBUrl(),
indexerUrl: this.connection.getIndexerUrl(),
});
this.logger.info("NftService initialized");
} else if (!this.nftSdk) {
while (!this.nftSdk) {
await sleep(100);
Expand Down
42 changes: 41 additions & 1 deletion src/module/sdk/core/transaction.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface Transaction {
blockHash?: string;
blockNumber?: number;
timestamp?: Date;
tokenAmount?: number;
}

export enum TransactionStatus {
Expand Down Expand Up @@ -127,11 +128,13 @@ export class TransactionService {
let amount = 0;
let complexAmount = 0;
let inputType = null;
let inputData = null;
let isRealSender = false;
for (let i = 0; i < lumosTx.transaction.inputs.length; i += 1) {
const input = lumosTx.transaction.inputs[i];
const inputTx = await this.connection.getTransactionFromHash(input.previous_output.tx_hash);
const output = inputTx.transaction.outputs[parseInt(input.previous_output.index, 16)];
const outputIdx = parseInt(input.previous_output.index, 16);
const output = inputTx.transaction.outputs[outputIdx];
const inputAddress = this.connection.getAddressFromLock(output.lock);
inputs.push({
quantity: parseInt(output.capacity, 16) / 100000000,
Expand All @@ -148,6 +151,14 @@ export class TransactionService {
codeHash: output.type.code_hash,
hashType: output.type.hash_type,
};
const data = inputTx.transaction.outputs_data[outputIdx];
if (data && data !== "0x") {
if (data.length === 34) {
inputData = Number(utils.readBigUInt128LE(data));
} else if (data.length === 18) {
inputData = Number(utils.readBigUInt64LE(data));
}
}
}
}
if (address === inputAddress) {
Expand All @@ -156,14 +167,21 @@ export class TransactionService {
}

let outputIndex = null;
const tokensDestinationsIndex: number[] = [];
let receiveAmount = 0;
let tokenAmount: undefined | number = undefined;
const outputs: DataRow[] = lumosTx.transaction.outputs.map((output, index) => {
const outputAddress = this.connection.getAddressFromLock(output.lock);
if (allAddresses.includes(outputAddress)) {
amount += parseInt(output.capacity, 16) / 100000000;
if (output.type) {
outputIndex = index;
}
} else if (output.type) {
const outputScriptType = { args: output.type.args, codeHash: output.type.code_hash, hashType: output.type.hash_type };
if (TransactionService.isScriptTypeScript(outputScriptType, this.connection.getConfig().SCRIPTS.SUDT!)) {
tokensDestinationsIndex.push(index);
}
}
if (inputAddresses.includes(outputAddress)) {
complexAmount += parseInt(output.capacity, 16) / 100000000;
Expand Down Expand Up @@ -210,6 +228,11 @@ export class TransactionService {
scriptType = outputType!;
if (TransactionService.isScriptTypeScript(scriptType, this.connection.getConfig().SCRIPTS.SUDT!)) {
type = !isReceive ? TransactionType.SEND_TOKEN : TransactionType.RECEIVE_TOKEN;
if (type === TransactionType.RECEIVE_TOKEN) {
tokenAmount = data || 0;
} else {
tokenAmount = tokensDestinationsIndex.reduce((acc, outputIndex) => (acc += outputs[outputIndex].data || 0), 0);
}
} else if (TransactionService.isScriptTypeScript(scriptType, this.connection.getConfig().SCRIPTS.DAO!)) {
if (data === 0) {
type = TransactionType.DEPOSIT_DAO;
Expand All @@ -227,6 +250,9 @@ export class TransactionService {
scriptType = inputType!;
if (TransactionService.isScriptTypeScript(scriptType, this.connection.getConfig().SCRIPTS.SUDT!)) {
type = !isReceive ? TransactionType.SEND_TOKEN : TransactionType.RECEIVE_TOKEN;
if (inputData) {
tokenAmount = inputData;
}
} else if (await this.nftService.isScriptNftScript(scriptType)) {
type = !isReceive ? TransactionType.SEND_NFT : TransactionType.RECEIVE_NFT;
} else {
Expand All @@ -242,6 +268,7 @@ export class TransactionService {
type: type!,
scriptType: scriptType!,
amount,
tokenAmount,
};
if (lumosTx.tx_status.block_hash) {
const header = await this.connection.getBlockHeaderFromHash(lumosTx.tx_status.block_hash);
Expand Down Expand Up @@ -429,9 +456,19 @@ export class TransactionService {
}

if (changeCapacity > BigInt(0)) {
let splitFlag = false;

changeCell.cell_output.capacity = "0x" + changeCapacity.toString(16);
if (changeAmount > 0) {
changeCell.data = utils.toBigUInt128LE(changeAmount.toString());

const changeCellMin = helpers.minimalCellCapacityCompatible(changeCell).toBigInt();
const changeCellNoSudtMin = helpers.minimalCellCapacityCompatible(changeCellWithoutSudt).toBigInt();
if (changeCapacity >= changeCellMin + changeCellNoSudtMin) {
changeCell.cell_output.capacity = "0x" + changeCellMin.toString(16);
changeCellWithoutSudt.cell_output.capacity = "0x" + (changeCapacity - changeCellMin).toString(16);
splitFlag = true;
}
}

txSkeleton = txSkeleton.update("outputs", (outputs) => outputs.push(changeCell));
Expand All @@ -443,6 +480,9 @@ export class TransactionService {
});
});
}
if (splitFlag) {
txSkeleton = txSkeleton.update("outputs", (outputs) => outputs.push(changeCellWithoutSudt));
}
}

return txSkeleton;
Expand Down
14 changes: 9 additions & 5 deletions src/module/sdk/core/wallet.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ export class WalletService {
private lastHashBlock!: string;
private accountCellsMap: cellMapI = {};
private accountTransactionMap: transactionMapI = {};
private onSync!: (walletState: WalletState) => Promise<void>;
private onSync!: (walletState?: WalletState) => Promise<void>;
private onSyncStart!: () => void;
private synchronizing = false;

constructor(
connectionService: ConnectionService,
mnemo: string,
walletState?: WalletState,
onSync?: (walletState: WalletState) => Promise<void>,
onSync?: (walletState?: WalletState) => Promise<void>,
onSyncStart?: () => void,
) {
if (!WalletService.validateMnemonic(mnemo)) {
Expand Down Expand Up @@ -190,11 +190,16 @@ export class WalletService {
}
}

if (this.onSync) this.onSync();
const allAddresses = this.getAllAddresses();
for (let i = 0; i < keysArr.length && i < lumosTxsArr.length && i < addressesArr.length; i += 1) {
const address = addressesArr[i];
const promises = lumosTxsArr[i].map((tx) => this.transactionService.getTransactionFromLumosTx(tx, address, allAddresses));
const transactions = await Promise.all(promises);
const transactions: Transaction[] = [];

for (const tx of lumosTxsArr[i]) {
const finalTx = await this.transactionService.getTransactionFromLumosTx(tx, address, allAddresses);
transactions.push(finalTx);
}

// Update transactions
const currentTxs: Transaction[] = this.accountTransactionMap[keysArr[i]] || [];
Expand Down Expand Up @@ -331,7 +336,6 @@ export class WalletService {

getTransactions(): Transaction[] {
const sortedTxs = [...Object.values(this.accountTransactionMap)].flat(1).sort((txa, txb) => txa.blockNumber! - txb.blockNumber!);

// Remove equal transactions
for (let i = 0; i < sortedTxs.length; i += 1) {
let j = i + 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@ import { Col, Typography } from "@peersyst/react-native-components";
import TransactionLabel from "module/transaction/component/display/TransactionLabel/TransactionLabel";
import TransactionAmount from "module/transaction/component/display/TransactionAmount/TransactionAmount";
import { FullTransaction } from "module/common/service/CkbSdkService.types";
import { TransactionType } from "ckb-peersyst-sdk";
import useFormatDate from "module/common/hook/useFormatDate";

export interface TransactionDetailsHeaderProps {
transaction: FullTransaction;
}

const TransactionDetailsHeader = ({ transaction }: TransactionDetailsHeaderProps): JSX.Element => {
const { type, amount, token, timestamp } = transaction;
const showAmount = type !== TransactionType.SEND_NFT && type !== TransactionType.RECEIVE_NFT;
const { type, timestamp } = transaction;
const formatDate = useFormatDate();
const formattedDate = formatDate(timestamp);

Expand All @@ -21,7 +19,7 @@ const TransactionDetailsHeader = ({ transaction }: TransactionDetailsHeaderProps
<TransactionIcon type={type} />
<Col gap={5} alignItems="center">
<TransactionLabel variant="body1Strong" transaction={transaction} numberOfLines={2} textAlign="center" />
{showAmount && <TransactionAmount variant="body1Strong" type={type} amount={amount} units={token ?? "token"} />}
<TransactionAmount variant="body1Strong" transaction={transaction} />
{timestamp && <Typography variant="body4Regular">{formattedDate}</Typography>}
</Col>
</Col>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import EmptyTransactionsList from "../../feedback/EmptyTransactionsList/EmptyTra

const TransactionsList = (): JSX.Element => {
const { data = [], isLoading, refetch } = useGetTransactions({ filter: (tx) => isSupportedTransaction(tx.type) });

return (
<MainList
onRefresh={refetch}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,36 @@ import Balance from "module/wallet/component/display/Balance/Balance";
import { BalanceProps } from "module/wallet/component/display/Balance/Balance.types";
import { FullTransaction } from "module/common/service/CkbSdkService.types";
import transactionTypeToBalanceAction from "./utils/transactionTypeToBalanceAction";
import { BNToNumber } from "module/common/utils/BalanceOperations/utils/BNtoNumber";
import { TransactionType } from "ckb-peersyst-sdk";

export interface TransactionAmountProps extends Omit<BalanceProps, "action" | "balance"> {
type: FullTransaction["type"];
amount: BalanceProps["balance"];
transaction: FullTransaction;
}

const TransactionAmount = ({ type, amount, ...rest }: TransactionAmountProps): JSX.Element => {
const TransactionAmount = ({ transaction, ...rest }: TransactionAmountProps): JSX.Element => {
const { type, token, amount, tokenAmount, tokenType } = transaction;
const action = transactionTypeToBalanceAction(type);
const isPrimary = action === "add";
return <Balance action={action} balance={amount} color={isPrimary ? "primary" : "text"} {...rest} />;
const finalAmount = tokenType ? BNToNumber(tokenAmount || 0, tokenType.decimals) : amount;
const showAmount =
(type !== TransactionType.SEND_NFT && type !== TransactionType.RECEIVE_NFT) || (tokenType && tokenAmount === undefined);
const decimals = tokenType ? Math.min(Math.min(finalAmount.toString().split(".")[1]?.length, tokenType.decimals), 6) : undefined;

return (
<>
{showAmount && (
<Balance
options={{ maximumFractionDigits: decimals, minimumFractionDigits: decimals }}
action={action}
units={token || "token"}
balance={finalAmount}
color={isPrimary ? "primary" : "text"}
{...rest}
/>
)}
</>
);
};

export default TransactionAmount;
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ const TransactionCard = ({ transaction }: TransactionCardProps): JSX.Element =>
const { showModal } = useModal();
const { fiat } = useRecoilValue(settingsState);
const { convertBalance } = useCkbConversion();
const { timestamp, amount, type, token = "token", status } = transaction;
const showAmount = type !== TransactionType.SEND_NFT && type !== TransactionType.RECEIVE_NFT;
const { timestamp, amount, type, status } = transaction;
const showFiat = type === TransactionType.SEND_NATIVE_TOKEN || type === TransactionType.RECEIVE_NATIVE_TOKEN;
const formatDate = useFormatDate();
const formattedDate = formatDate(timestamp);
const amountInFiat = convertBalance(amount.toString());
Expand All @@ -32,15 +32,7 @@ const TransactionCard = ({ transaction }: TransactionCardProps): JSX.Element =>
<Col flex={1}>
<Row justifyContent="space-between">
<TransactionLabel variant="body3Regular" transaction={transaction} numberOfLines={1} style={{ flex: 1 }} />
{showAmount && (
<TransactionAmount
variant="body3Regular"
type={type}
amount={amount}
units={token}
style={{ maxWidth: "50%" }}
/>
)}
<TransactionAmount variant="body3Regular" transaction={transaction} style={{ maxWidth: "50%" }} />
</Row>
<Row justifyContent="space-between" alignItems="center">
{timestamp ? (
Expand All @@ -53,7 +45,7 @@ const TransactionCard = ({ transaction }: TransactionCardProps): JSX.Element =>
{status !== TransactionStatusEnum.COMMITTED ? (
<TransactionStatusIndicator status={status} />
) : (
showAmount && (
showFiat && (
<Balance
options={{ maximumFractionDigits: 2, minimumFractionDigits: 2 }}
action="round"
Expand Down
2 changes: 1 addition & 1 deletion src/module/transaction/query/useGetTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const useGetTransactions = ({ index, filter }: UseGetTransactionsOptions = {}) =
return filter
? [...uncommitedTransactions, ...filteredTransacations].filter(filter)
: [...uncommitedTransactions, ...filteredTransacations];
}, [uncommitedTransactions, transactions, filter]);
}, [uncommitedTransactions, transactions.length, filter]);

return {
data: txs,
Expand Down
4 changes: 2 additions & 2 deletions src/module/wallet/component/core/AccountCard/AccountCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import AccountCardButtons from "module/wallet/component/core/AccountCard/Account
import useCkbConversion from "module/common/hook/useCkbConversion";

const AccountCard = ({ wallet, style }: WalletComponentCardProps): JSX.Element => {
const { index, synchronizing } = wallet;
const { index, synchronizingCells } = wallet;
const { fiat } = useRecoilValue(settingsState);
const { data: { freeBalance = 0 } = {}, isLoading: isBalanceLoading } = useGetBalance(index);
const [showFiat, setCurrencyMode] = useState<boolean>(false);
const { value: balanceInFiat } = useCkbConversion(freeBalance.toString(), fiat);

const isLoading = synchronizing || isBalanceLoading;
const isLoading = synchronizingCells || isBalanceLoading;

const changeCurrencyMode = () => {
impactAsync(ImpactFeedbackStyle.Medium);
Expand Down
Loading

0 comments on commit 66947b0

Please sign in to comment.