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

Release/warm bustling meerkat #3592

Merged
merged 14 commits into from
Apr 26, 2023
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
32 changes: 22 additions & 10 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ module.exports = {
browser: true,
context: true,
},
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
plugins: ['react', 'react-hooks', '@typescript-eslint', 'deprecation'],
rules: {
// This rule helps highlight areas of the code that use deprecated
Expand All @@ -41,25 +47,31 @@ module.exports = {
message: avoidWindowOpenMsg,
},
],
'@typescript-eslint/no-floating-promises': [1],
'@typescript-eslint/no-unnecessary-type-assertion': [0],
'@typescript-eslint/no-floating-promises': ['warn'],
'@typescript-eslint/no-unnecessary-type-assertion': ['warn'],

'@typescript-eslint/no-unsafe-assignment': [0],
'@typescript-eslint/no-unsafe-return': [0],
'@typescript-eslint/no-unsafe-call': [0],
'@typescript-eslint/no-unsafe-member-access': [0],
'@typescript-eslint/ban-types': [0],
'@typescript-eslint/restrict-template-expressions': [0],
'@typescript-eslint/explicit-module-boundary-types': [0],
'@typescript-eslint/no-unnecessary-type-constraint': ['off'],
'@typescript-eslint/no-non-null-asserted-optional-chain': ['off'],
'@typescript-eslint/no-explicit-any': ['off'],
'@typescript-eslint/no-meaningless-void-operator': 'error',
'@typescript-eslint/ban-types': ['error'],
'@typescript-eslint/no-unnecessary-condition': 'warn',
'@typescript-eslint/consistent-type-definitions': ['error', 'interface'],
'no-warning-comments': [0],
'react/function-component-definition': 'error',

'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': [
'error',
{
additionalHooks: 'useRecoilCallback',
},
],
'react-hooks/exhaustive-deps': ['error'],

'react/function-component-definition': 'error',
'react/display-name': 'off',
'react/prop-types': 'off',
'react/no-unescaped-entities': 'off',
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
},
Expand Down
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@
"@scure/bip32": "1.3.0",
"@scure/bip39": "1.2.0",
"@scure/btc-signer": "0.5.1",
"@segment/analytics-next": "1.49.2",
"@segment/analytics-next": "1.51.5",
"@sentry/react": "7.35.0",
"@sentry/tracing": "7.35.0",
"@stacks/auth": "6.1.1",
Expand All @@ -164,6 +164,7 @@
"@tanstack/react-query-devtools": "4.24.4",
"@tanstack/react-query-persist-client": "4.24.4",
"@tippyjs/react": "4.2.6",
"@typescript-eslint/eslint-plugin": "5.59.0",
"@vkontakte/vk-qr": "2.0.13",
"@zondax/ledger-stacks": "1.0.3",
"are-passive-events-supported": "1.1.1",
Expand Down Expand Up @@ -220,7 +221,7 @@
"@babel/core": "7.20.12",
"@babel/preset-react": "7.18.6",
"@babel/preset-typescript": "7.18.6",
"@btckit/types": "0.0.13",
"@btckit/types": "0.0.16",
"@emotion/babel-plugin": "11.10.5",
"@emotion/babel-preset-css-prop": "11.10.0",
"@emotion/cache": "11.10.5",
Expand All @@ -232,7 +233,6 @@
"@schemastore/web-manifest": "0.0.5",
"@sentry/webpack-plugin": "1.20.0",
"@stacks/connect-react": "22.0.1",
"@stacks/eslint-config": "1.2.0",
"@stacks/prettier-config": "0.0.10",
"@stacks/stacks-blockchain-api-types": "6.3.4",
"@swc-node/jest": "1.5.6",
Expand Down Expand Up @@ -265,6 +265,7 @@
"@types/webextension-polyfill": "0.10.0",
"@types/webpack": "5.28.0",
"@types/zxcvbn": "4.4.1",
"@typescript-eslint/parser": "5.59.0",
"@vitest/coverage-istanbul": "0.28.3",
"audit-ci": "6.6.1",
"babel-loader": "9.1.2",
Expand All @@ -285,7 +286,7 @@
"dotenv-webpack": "8.0.1",
"esbuild": "0.17.5",
"esbuild-loader": "2.21.0",
"eslint-plugin-deprecation": "1.3.3",
"eslint-plugin-deprecation": "1.4.1",
"eslint-plugin-react": "7.32.2",
"eslint-plugin-react-hooks": "4.6.0",
"file-loader": "6.2.0",
Expand Down
37 changes: 18 additions & 19 deletions src/app/common/hooks/analytics/use-analytics.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { useMemo } from 'react';
import { useEffect, useMemo } from 'react';
import { useLocation } from 'react-router-dom';

import {
EventParams,
PageParams,
} from '@segment/analytics-next/dist/types/core/arguments-resolver';

import { IS_TEST_ENV } from '@shared/environment';
import { IS_TEST_ENV, SEGMENT_WRITE_KEY } from '@shared/environment';
import { logger } from '@shared/logger';
import { analytics } from '@shared/utils/analytics';
import { analytics, initAnalytics } from '@shared/utils/analytics';

import { flow, origin } from '@app/common/initial-search-params';
import { useWalletType } from '@app/common/use-wallet-type';
Expand All @@ -25,13 +25,20 @@ function isHiroApiUrl(url: string) {
return /^https:\/\/.*\.stacks.co/.test(url);
}

export function useInitalizeAnalytics() {
const hasUserDeclinedAnalytics = useHasUserExplicitlyDeclinedAnalytics();

useEffect(() => {
if (hasUserDeclinedAnalytics || !SEGMENT_WRITE_KEY || IS_TEST_ENV) return;
initAnalytics();
}, [hasUserDeclinedAnalytics]);
}

export function useAnalytics() {
const currentNetwork = useCurrentNetworkState();
const location = useLocation();
const { walletType } = useWalletType();

const hasDeclined = useHasUserExplicitlyDeclinedAnalytics();

return useMemo(() => {
const defaultProperties = {
network: currentNetwork.name.toLowerCase(),
Expand All @@ -48,37 +55,29 @@ export function useAnalytics() {
};

return {
async identify(properties: object) {
return analytics.identify(properties).catch(logger.error);
},

async page(...args: PageParams) {
const [category, name, properties, options, ...rest] = args;
const prop = { ...defaultProperties, ...properties };
const opts = { ...defaultOptions, ...options };
logger.info(`Analytics page view: ${name}`, properties);

if (!analytics) return;
if (hasDeclined) return;
if (IS_TEST_ENV) return;
if (typeof name === 'string' && isIgnoredPath(name)) return;

return analytics.page(category, name, prop, opts, ...rest).catch(logger.error);
},

async track(...args: EventParams) {
const [eventName, properties, options, ...rest] = args;
const prop = { ...defaultProperties, ...properties };
const opts = { ...defaultOptions, ...options };
logger.info(`Analytics event: ${eventName}`, properties);

if (!analytics) return;
if (hasDeclined) return;
if (IS_TEST_ENV) return;

return analytics.track(eventName, prop, opts, ...rest).catch(logger.error);
},
};
}, [
currentNetwork.chain.stacks.url,
currentNetwork.name,
location.pathname,
walletType,
hasDeclined,
]);
}, [currentNetwork.chain.stacks.url, currentNetwork.name, location.pathname, walletType]);
}
16 changes: 10 additions & 6 deletions src/app/common/hooks/balance/use-total-balance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@ import { baseCurrencyAmountInQuote } from '@app/common/money/calculate-money';
import { i18nFormatCurrency } from '@app/common/money/format-money';
import { useNativeSegwitBalance } from '@app/query/bitcoin/balance/bitcoin-balances.query';
import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCurrentStacksAccountAnchoredBalances } from '@app/query/stacks/balance/stx-balance.hooks';
import { useCurrentBtcNativeSegwitAccountAddressIndexZero } from '@app/store/accounts/blockchain/bitcoin/native-segwit-account.hooks';
import { useAnchoredStacksAccountBalances } from '@app/query/stacks/balance/stx-balance.hooks';

export function useTotalBalance() {
interface UseTotalBalanceArgs {
btcAddress: string;
stxAddress: string;
}

export function useTotalBalance({ btcAddress, stxAddress }: UseTotalBalanceArgs) {
// get market data
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const stxMarketData = useCryptoCurrencyMarketData('STX');

// get stx balance
const { data: balances } = useCurrentStacksAccountAnchoredBalances();
const { data: balances, isLoading } = useAnchoredStacksAccountBalances(stxAddress);

// get btc balance
const btcAddress = useCurrentBtcNativeSegwitAccountAddressIndexZero();
const btcBalance = useNativeSegwitBalance(btcAddress);

return useMemo(() => {
Expand All @@ -30,6 +33,7 @@ export function useTotalBalance() {
return {
totalBalance,
totalUsdBalance: i18nFormatCurrency(totalBalance),
isLoading,
};
}, [btcBalance, balances, btcMarketData, stxMarketData]);
}, [btcBalance, balances, btcMarketData, stxMarketData, isLoading]);
}
11 changes: 6 additions & 5 deletions src/app/common/hooks/use-scroll-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,28 @@ declare global {
// tslint:disable-next-line: interface-name
interface Window {
__useScrollLockStyle: string | undefined | null;
__useScrollLockInstances: Set<{}> | undefined | null;
__useScrollLockInstances: Set<Record<string, unknown>> | undefined | null;
}
}

let instances: Set<{}> = new Set();
let instances: Set<Record<string, unknown>> = new Set();

if (typeof window !== 'undefined') {
// this is necessary because we may share instances of this file on a page so we store these globally
window.__useScrollLockInstances = window.__useScrollLockInstances || new Set<{}>();
window.__useScrollLockInstances =
window.__useScrollLockInstances || new Set<Record<string, unknown>>();
instances = window.__useScrollLockInstances;
}

const registerInstance = (instance: {}) => {
const registerInstance = (instance: Record<string, unknown>) => {
if (instances.size === 0) {
setBodyOverflow(true);
}

instances.add(instance);
};

const unregisterInstance = (instance: {}) => {
const unregisterInstance = (instance: Record<string, unknown>) => {
instances.delete(instance);

if (instances.size === 0) {
Expand Down
4 changes: 3 additions & 1 deletion src/app/common/theme-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { createContext, useContext, useEffect, useState } from 'react';

import { noop } from '@shared/utils';

import { store } from '@app/store';
import { settingsActions } from '@app/store/settings/settings.actions';
import { useUserSelectedTheme } from '@app/store/settings/settings.selectors';
Expand All @@ -25,7 +27,7 @@ const ThemeContext = createContext<{
// These values are not used, but are set to satisfy the context's value type.
theme: 'light',
userSelectedTheme: 'system',
setUserSelectedTheme: () => {},
setUserSelectedTheme: noop,
});

const getSystemTheme = () =>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// https://github.com/argvil19/bitcoin-transaction-size-calculator/blob/master/index.js
import BigNumber from 'bignumber.js';

type InputScriptTypes =
| 'p2pkh'
Expand Down Expand Up @@ -84,7 +85,7 @@ export class BtcSizeFeeEstimator {
return 3;
} else if (length < 4294967295) {
return 5;
} else if (length < 18446744073709551615) {
} else if (new BigNumber(length).isLessThan('18446744073709551615')) {
return 9;
} else {
throw new Error('Invalid let int');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,52 @@ import { useCallback } from 'react';

import * as btc from '@scure/btc-signer';

import { BitcoinSendFormValues } from '@shared/models/form.model';
import { logger } from '@shared/logger';
import { Money } from '@shared/models/money.model';

import { btcToSat } from '@app/common/money/unit-conversion';
import { determineUtxosForSpend } from '@app/common/transactions/bitcoin/coinselect/local-coin-selection';
import { useGetUtxosByAddressQuery } from '@app/query/bitcoin/address/utxos-by-address.query';
import { useBitcoinLibNetworkConfig } from '@app/store/accounts/blockchain/bitcoin/bitcoin-keychain';
import {
useCurrentAccountNativeSegwitSigner,
useCurrentBitcoinNativeSegwitAddressIndexPublicKeychain,
useCurrentBtcNativeSegwitAccountAddressIndexZero,
useSignBitcoinNativeSegwitTx,
} from '@app/store/accounts/blockchain/bitcoin/native-segwit-account.hooks';

interface GenerateBitcoinTxValues {
amount: Money;
recipient: string;
}

export function useGenerateSignedBitcoinTx() {
const currentAccountBtcAddress = useCurrentBtcNativeSegwitAccountAddressIndexZero();
const { data: utxos } = useGetUtxosByAddressQuery(currentAccountBtcAddress);
const currentAddressIndexKeychain = useCurrentBitcoinNativeSegwitAddressIndexPublicKeychain();
const signTx = useSignBitcoinNativeSegwitTx();
const createSigner = useCurrentAccountNativeSegwitSigner();
const networkMode = useBitcoinLibNetworkConfig();

return useCallback(
(values: BitcoinSendFormValues, feeRate: number) => {
(values: GenerateBitcoinTxValues, feeRate: number) => {
if (!utxos) return;
if (!feeRate) return;
if (!createSigner) return;

try {
const signer = createSigner(0);

const tx = new btc.Transaction();

const { inputs, outputs, fee } = determineUtxosForSpend({
utxos,
recipient: values.recipient,
amount: btcToSat(values.amount).toNumber(),
amount: values.amount.amount.toNumber(),
feeRate,
});

// eslint-disable-next-line no-console
console.log('coinselect', { inputs, outputs, fee });
logger.info('coinselect', { inputs, outputs, fee });

if (!inputs) throw new Error('No inputs to sign');
if (!outputs) throw new Error('No outputs to sign');
if (!inputs.length) throw new Error('No inputs to sign');
if (!outputs.length) throw new Error('No outputs to sign');

if (outputs.length > 2)
throw new Error('Address reuse mode: wallet should have max 2 outputs');
Expand All @@ -66,15 +73,22 @@ export function useGenerateSignedBitcoinTx() {
}
tx.addOutputAddress(values.recipient, BigInt(output.value), networkMode);
});
signTx(tx);
signer.sign(tx);
tx.finalize();

return { hex: tx.hex, fee };
} catch (e) {
// eslint-disable-next-line no-console
console.log('Error signing bitcoin transaction', e);
return null;
}
},
[currentAccountBtcAddress, currentAddressIndexKeychain?.publicKey, networkMode, signTx, utxos]
[
createSigner,
currentAccountBtcAddress,
currentAddressIndexKeychain?.publicKey,
networkMode,
utxos,
]
);
}
2 changes: 1 addition & 1 deletion src/app/common/utils/counter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function createCounter(startPosition: number = 0) {
export function createCounter(startPosition = 0) {
let count = startPosition;
return {
getValue() {
Expand Down
4 changes: 3 additions & 1 deletion src/app/common/utils/use-interval.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useEffect, useRef } from 'react';

import { noop } from '@shared/utils';

export function useInterval(callback: () => void, delay: number | null) {
const savedCallback = useRef(() => {});
const savedCallback = useRef(noop);

// Remember the latest callback.
useEffect(() => {
Expand Down
Loading