Skip to content

Commit

Permalink
improve getter tools, don't export optional getters (#1574)
Browse files Browse the repository at this point in the history
  • Loading branch information
turbocrime authored Sep 4, 2024
1 parent 0b85eca commit a7ed0ab
Show file tree
Hide file tree
Showing 58 changed files with 444 additions and 284 deletions.
5 changes: 5 additions & 0 deletions .changeset/khaki-tables-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@penumbra-zone/getters': major
---

don't export optional getters
5 changes: 5 additions & 0 deletions .changeset/slow-seas-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@penumbra-zone/getters': major
---

improve getter type
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getDisplayDenomFromView, getEquivalentValues } from '@penumbra-zone/get
import { ValueViewComponent } from '@penumbra-zone/ui/components/ui/value';

export const EquivalentValues = ({ valueView }: { valueView?: ValueView }) => {
const equivalentValuesAsValueViews = (getEquivalentValues.optional()(valueView) ?? []).map(
const equivalentValuesAsValueViews = (getEquivalentValues.optional(valueView) ?? []).map(
asValueView,
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { EquivalentValues } from './equivalent-values';
import { Fragment } from 'react';
import { PagePath } from '../../metadata/paths';
import { Link } from 'react-router-dom';
import { getMetadataFromBalancesResponseOptional } from '@penumbra-zone/getters/balances-response';
import { getMetadataFromBalancesResponse } from '@penumbra-zone/getters/balances-response';
import { getAddressIndex } from '@penumbra-zone/getters/address-view';
import { BalancesByAccount, groupByAccount, useBalancesResponses } from '../../../state/shared';
import { AbridgedZQueryState } from '@penumbra-zone/zquery/src/types';
Expand All @@ -24,7 +24,7 @@ import { LineWave } from 'react-loader-spinner';
import { cn } from '@penumbra-zone/ui/lib/utils';

const getTradeLink = (balance: BalancesResponse): string => {
const metadata = getMetadataFromBalancesResponseOptional(balance);
const metadata = getMetadataFromBalancesResponse.optional(balance);
const accountIndex = getAddressIndex(balance.accountAddress).account;
const accountQuery = accountIndex ? `&account=${accountIndex}` : '';
return metadata ? `${PagePath.SWAP}?from=${metadata.symbol}${accountQuery}` : PagePath.SWAP;
Expand Down
4 changes: 2 additions & 2 deletions apps/minifront/src/components/shared/input-token.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useMemo } from 'react';
import { BalancesResponse } from '@penumbra-zone/protobuf/penumbra/view/v1/view_pb';
import { getDisplayDenomExponent } from '@penumbra-zone/getters/metadata';
import { getMetadataFromBalancesResponseOptional } from '@penumbra-zone/getters/balances-response';
import { getMetadataFromBalancesResponse } from '@penumbra-zone/getters/balances-response';
import { BalanceValueView } from '@penumbra-zone/ui/components/ui/balance-value-view';
import { cn } from '@penumbra-zone/ui/lib/utils';
import BalanceSelector from './selectors/balance-selector';
Expand Down Expand Up @@ -38,7 +38,7 @@ export default function InputToken({
loading,
}: InputTokenProps) {
const tokenExponent = useMemo(() => {
return getDisplayDenomExponent.optional()(getMetadataFromBalancesResponseOptional(selection));
return getDisplayDenomExponent.optional(getMetadataFromBalancesResponse.optional(selection));
}, [selection]);

const setInputToBalanceMax = () => {
Expand Down
12 changes: 6 additions & 6 deletions apps/minifront/src/components/shared/non-native-fee-warning.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const hasTokenBalance = ({
gasPrices: GasPrices[];
stakingAssetMetadata?: Metadata;
}): boolean => {
const account = getAddressIndex.optional()(source)?.account;
const account = getAddressIndex.optional(source)?.account;
if (typeof account === 'undefined') {
return false;
}
Expand All @@ -33,17 +33,17 @@ const hasTokenBalance = ({
const hasStakingToken = balancesResponses.some(
asset =>
getAssetIdFromValueView
.optional()(asset.balanceView)
?.equals(getAssetId.optional()(stakingAssetMetadata)) &&
getAddressIndex.optional()(asset)?.account === account,
.optional(asset.balanceView)
?.equals(getAssetId.optional(stakingAssetMetadata)) &&
getAddressIndex.optional(asset)?.account === account,
);

if (hasStakingToken) {
return false;
}

const accountAssets = balancesResponses.filter(
balance => getAddressIndex.optional()(balance)?.account === account,
balance => getAddressIndex.optional(balance)?.account === account,
);
// Finds the alt tokens in the user's account balances that can be used for fees
const hasAltTokens = accountAssets.some(balance => {
Expand All @@ -54,7 +54,7 @@ const hasTokenBalance = ({
}

return gasPrices.some(price =>
price.assetId?.equals(getAssetIdFromBalancesResponse.optional()(balance)),
price.assetId?.equals(getAssetIdFromBalancesResponse.optional(balance)),
);
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { BalanceOrMetadata, isBalance, isMetadata } from './helpers';
import { getAddressIndex } from '@penumbra-zone/getters/address-view';
import {
getMetadataFromBalancesResponse,
getMetadataFromBalancesResponseOptional,
} from '@penumbra-zone/getters/balances-response';
import { getMetadataFromBalancesResponse } from '@penumbra-zone/getters/balances-response';
import { useMemo } from 'react';
import { DialogClose } from '@penumbra-zone/ui/components/ui/dialog';
import { cn } from '@penumbra-zone/ui/lib/utils';
Expand All @@ -22,8 +19,8 @@ export const BalanceItem = ({ asset, value, onSelect }: BalanceItemProps) => {
const account = isBalance(asset) ? getAddressIndex(asset.accountAddress).account : undefined;
const metadataFromAsset = isMetadata(asset)
? asset
: getMetadataFromBalancesResponseOptional(asset);
const metadataFromValue = getMetadataFromBalancesResponse.optional()(value);
: getMetadataFromBalancesResponse.optional(asset);
const metadataFromValue = getMetadataFromBalancesResponse.optional(value);

const isSelected = useMemo(() => {
if (!value) {
Expand Down
12 changes: 6 additions & 6 deletions apps/minifront/src/components/shared/selectors/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BalancesResponse } from '@penumbra-zone/protobuf/penumbra/view/v1/view_
import { Metadata } from '@penumbra-zone/protobuf/penumbra/core/asset/v1/asset_pb';
import {
getAddressIndex,
getMetadataFromBalancesResponseOptional,
getMetadataFromBalancesResponse,
} from '@penumbra-zone/getters/balances-response';
import { useEffect } from 'react';

Expand All @@ -22,7 +22,7 @@ export const mergeBalancesAndAssets = (
): BalanceOrMetadata[] => {
const filteredAssets = assets.filter(asset => {
return !balances.some(balance => {
const balanceMetadata = getMetadataFromBalancesResponseOptional(balance);
const balanceMetadata = getMetadataFromBalancesResponse.optional(balance);
return balanceMetadata?.equals(asset);
});
});
Expand All @@ -43,10 +43,10 @@ export const useSyncSelectedBalance = ({
if (value) {
const matchedValue = balances?.find(balance => {
return (
getAddressIndex.optional()(balance)?.equals(getAddressIndex.optional()(value)) &&
getMetadataFromBalancesResponseOptional(balance)?.equals(
getMetadataFromBalancesResponseOptional(value),
)
getAddressIndex.optional(balance)?.equals(getAddressIndex.optional(value)) &&
getMetadataFromBalancesResponse
.optional(balance)
?.equals(getMetadataFromBalancesResponse.optional(value))
);
});
if (matchedValue && !matchedValue.equals(value)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getValueViewCaseFromBalancesResponse } from '@penumbra-zone/getters/bal
export const balanceBySearch =
(search: string) =>
(balancesResponse: BalancesResponse): boolean =>
getValueViewCaseFromBalancesResponse.optional()(balancesResponse) === 'knownAssetId' &&
getValueViewCaseFromBalancesResponse.optional(balancesResponse) === 'knownAssetId' &&
(getDisplayDenomFromView(balancesResponse.balanceView)
.toLocaleLowerCase()
.includes(search.toLocaleLowerCase()) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const ValidatorInfoComponent = ({
const showTooltips = useStore(state => !state.staking.loading);
const validator = getValidator(validatorInfo);
const identityKey = getIdentityKeyFromValidatorInfo(validatorInfo);
const state = getValidatorState.optional()(validatorInfo);
const state = getValidatorState.optional(validatorInfo);

return (
<TooltipProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ export const EstimatedOutputExplanation = () => {

const formattedAmount = formatAmount({
amount: estimatedOutput,
exponent: getDisplayDenomExponent.optional()(assetOut),
exponent: getDisplayDenomExponent.optional(assetOut),
});
const assetInSymbol = getSymbolFromValueView.optional()(assetIn?.balanceView);
const assetInSymbol = getSymbolFromValueView.optional(assetIn?.balanceView);

return (
<div className='text-xs'>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getMetadataFromBalancesResponseOptional } from '@penumbra-zone/getters/balances-response';
import { getMetadataFromBalancesResponse } from '@penumbra-zone/getters/balances-response';
import { AbridgedZQueryState } from '@penumbra-zone/zquery/src/types';
import { Box } from '@penumbra-zone/ui/components/ui/box';
import { CandlestickPlot } from '@penumbra-zone/ui/components/ui/candlestick-plot';
Expand All @@ -12,7 +12,7 @@ import { useStoreShallow } from '../../../utils/use-store-shallow';
import { Button } from '@penumbra-zone/ui/components/ui/button';

const priceHistorySelector = (state: AllSlices) => ({
startMetadata: getMetadataFromBalancesResponseOptional(state.swap.assetIn),
startMetadata: getMetadataFromBalancesResponse.optional(state.swap.assetIn),
endMetadata: state.swap.assetOut,
historyLimit: state.swap.priceHistory.historyLimit,
historyStart: state.swap.priceHistory.historyStart,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ const simulateSwapResultSelector = (state: AllSlices) => ({
value: {
amount: toBaseUnit(
new BigNumber(state.swap.amount || 0),
getDisplayDenomExponentFromValueView.optional()(state.swap.assetIn?.balanceView),
getDisplayDenomExponentFromValueView.optional(state.swap.assetIn?.balanceView),
),
metadata: getMetadata.optional()(state.swap.assetIn?.balanceView),
metadata: getMetadata.optional(state.swap.assetIn?.balanceView),
},
},
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export const Price = ({
const lastValueMetadata = metadataByAssetId[bech32mAssetId(outputValue.assetId)];

if (firstValueMetadata?.symbol && lastValueMetadata?.symbol) {
const inputDisplayDenomExponent = getDisplayDenomExponent.optional()(firstValueMetadata) ?? 0;
const outputDisplayDenomExponent = getDisplayDenomExponent.optional()(lastValueMetadata) ?? 0;
const inputDisplayDenomExponent = getDisplayDenomExponent.optional(firstValueMetadata) ?? 0;
const outputDisplayDenomExponent = getDisplayDenomExponent.optional(lastValueMetadata) ?? 0;
const formattedInputAmount = formatAmount({
amount: inputValue.amount,
exponent: inputDisplayDenomExponent,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { joinLoHiAmount } from '@penumbra-zone/types/amount';
import {
getAmount,
getBalanceView,
getMetadataFromBalancesResponseOptional,
getMetadataFromBalancesResponse,
} from '@penumbra-zone/getters/balances-response';
import { ArrowRight } from 'lucide-react';
import { useMemo } from 'react';
Expand Down Expand Up @@ -43,7 +43,7 @@ const getAssetOutBalance = (
getAddressIndex(assetIn.accountAddress),
assetOut,
);
const matchedBalance = getBalanceView.optional()(match);
const matchedBalance = getBalanceView.optional(match);
return matchedBalance ?? zeroValueView(assetOut);
};

Expand All @@ -70,10 +70,10 @@ export const TokenSwapInput = () => {
useStoreShallow(tokenSwapInputSelector);
const assetOutBalance = getAssetOutBalance(balancesResponses?.data, assetIn, assetOut);
const assetInExponent = useMemo(() => {
return getDisplayDenomExponent.optional()(getMetadataFromBalancesResponseOptional(assetIn));
return getDisplayDenomExponent.optional(getMetadataFromBalancesResponse.optional(assetIn));
}, [assetIn]);

const maxAmount = getAmount.optional()(assetIn);
const maxAmount = getAmount.optional(assetIn);
const maxAmountAsString = maxAmount ? joinLoHiAmount(maxAmount).toString() : undefined;

const setInputToBalanceMax = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getDisplayDenomFromView, getEquivalentValues } from '@penumbra-zone/get
import { ValueViewComponent } from '@penumbra-zone/ui/ValueViewComponent';

export const EquivalentValues = ({ valueView }: { valueView?: ValueView }) => {
const equivalentValuesAsValueViews = (getEquivalentValues.optional()(valueView) ?? []).map(
const equivalentValuesAsValueViews = (getEquivalentValues.optional(valueView) ?? []).map(
asValueView,
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { BalancesByAccount, groupByAccount, useBalancesResponses } from '../../.
import { shouldDisplay } from '../../../../fetchers/balances/should-display';
import { sortByPriorityScore } from '../../../../fetchers/balances/by-priority-score';
import { BalancesResponse } from '@penumbra-zone/protobuf/penumbra/view/v1/view_pb';
import { getMetadataFromBalancesResponseOptional } from '@penumbra-zone/getters/balances-response';
import { getMetadataFromBalancesResponse } from '@penumbra-zone/getters/balances-response';
import { PagePath } from '../../../metadata/paths';
import { getAddressIndex } from '@penumbra-zone/getters/address-view';
import { AbridgedZQueryState } from '@penumbra-zone/zquery/src/types';
Expand All @@ -19,7 +19,7 @@ import { ConditionalWrap } from '@penumbra-zone/ui/ConditionalWrap';
import { LayoutGroup } from 'framer-motion';

const getTradeLink = (balance: BalancesResponse): string => {
const metadata = getMetadataFromBalancesResponseOptional(balance);
const metadata = getMetadataFromBalancesResponse.optional(balance);
const accountIndex = getAddressIndex(balance.accountAddress).account;
const accountQuery = accountIndex ? `&account=${accountIndex}` : '';
return metadata ? `${PagePath.SWAP}?from=${metadata.symbol}${accountQuery}` : PagePath.SWAP;
Expand Down
4 changes: 2 additions & 2 deletions apps/minifront/src/fetchers/auction-infos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export const getAuctionInfos = async function* ({

const auction = DutchAuction.fromBinary(response.auction.value);

const inputAssetId = getInputAssetId.optional()(auction);
const outputAssetId = getOutputAssetId.optional()(auction);
const inputAssetId = getInputAssetId.optional(auction);
const outputAssetId = getOutputAssetId.optional(auction);

const inputMetadataPromise = inputAssetId
? penumbra.service(ViewService).assetMetadataById({ assetId: inputAssetId })
Expand Down
10 changes: 5 additions & 5 deletions apps/minifront/src/fetchers/balances/by-priority-score.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { BalancesResponse } from '@penumbra-zone/protobuf/penumbra/view/v1/view_pb';
import {
getMetadataFromBalancesResponseOptional,
getMetadataFromBalancesResponse,
getAmount,
getAddressIndex,
} from '@penumbra-zone/getters/balances-response';
import { multiplyAmountByNumber, joinLoHiAmount } from '@penumbra-zone/types/amount';

export const sortByPriorityScore = (a: BalancesResponse, b: BalancesResponse) => {
const aScore = getMetadataFromBalancesResponseOptional(a)?.priorityScore ?? 1n;
const bScore = getMetadataFromBalancesResponseOptional(b)?.priorityScore ?? 1n;
const aScore = getMetadataFromBalancesResponse.optional(a)?.priorityScore ?? 1n;
const bScore = getMetadataFromBalancesResponse.optional(b)?.priorityScore ?? 1n;

const aAmount = getAmount.optional()(a);
const bAmount = getAmount.optional()(b);
const aAmount = getAmount.optional(a);
const bAmount = getAmount.optional(b);

const aPriority = aAmount
? joinLoHiAmount(multiplyAmountByNumber(aAmount, Number(aScore)))
Expand Down
8 changes: 4 additions & 4 deletions apps/minifront/src/state/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { uint8ArrayToHex } from '@penumbra-zone/types/hex';
import { fromValueView } from '@penumbra-zone/types/amount';
import { BigNumber } from 'bignumber.js';
import {
getMetadataFromBalancesResponseOptional,
getMetadataFromBalancesResponse,
getValueViewCaseFromBalancesResponse,
} from '@penumbra-zone/getters/balances-response';
import { getDisplayDenomExponent } from '@penumbra-zone/getters/metadata';
Expand Down Expand Up @@ -201,8 +201,8 @@ export const isIncorrectDecimal = (
throw new Error('Missing balanceView');
}

const exponent = getDisplayDenomExponent.optional()(
getMetadataFromBalancesResponseOptional(asset),
const exponent = getDisplayDenomExponent.optional(
getMetadataFromBalancesResponse.optional(asset),
);
const fraction = amountInDisplayDenom.split('.')[1]?.length;
return typeof exponent !== 'undefined' && typeof fraction !== 'undefined' && fraction > exponent;
Expand All @@ -214,4 +214,4 @@ export const isValidAmount = (amount: string, assetIn?: BalancesResponse) =>
(!assetIn || !isIncorrectDecimal(assetIn, amount));

export const isKnown = (balancesResponse: BalancesResponse) =>
getValueViewCaseFromBalancesResponse.optional()(balancesResponse) === 'knownAssetId';
getValueViewCaseFromBalancesResponse.optional(balancesResponse) === 'knownAssetId';
2 changes: 1 addition & 1 deletion apps/minifront/src/state/ibc-out.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ export const filterBalancesPerChain = (
registryAssets: Metadata[],
stakingTokenMetadata?: Metadata,
): BalancesResponse[] => {
const penumbraAssetId = getAssetId.optional()(stakingTokenMetadata);
const penumbraAssetId = getAssetId.optional(stakingTokenMetadata);
const assetsWithMatchingChannel = registryAssets
.filter(a => {
const match = assetPatterns.ibc.capture(a.base);
Expand Down
2 changes: 1 addition & 1 deletion apps/minifront/src/state/send/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ const assembleRequest = ({ amount, feeTier, recipient, selection, memo }: SendSl
value: {
amount: toBaseUnit(
BigNumber(amount),
getDisplayDenomExponentFromValueView.optional()(selection?.balanceView),
getDisplayDenomExponentFromValueView.optional(selection?.balanceView),
),
assetId: getAssetIdFromValueView(selection?.balanceView),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const assembleScheduleRequest = async ({
duration,
}: Pick<SwapSlice, 'amount' | 'assetIn' | 'assetOut' | 'duration'> &
Pick<DutchAuctionSlice, 'minOutput' | 'maxOutput'>): Promise<TransactionPlannerRequest> => {
const source = getAddressIndex.optional()(assetIn);
const source = getAddressIndex.optional(assetIn);

return new TransactionPlannerRequest({
dutchAuctionScheduleActions: await getSubAuctions({
Expand Down
4 changes: 2 additions & 2 deletions apps/minifront/src/state/swap/dutch-auction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export const createDutchAuctionSlice = (): SliceCreator<DutchAuctionSlice> => (s
swap.dutchAuction.minOutput = '';
} else {
const minMinOutput = getSmallestPossibleAmountAboveZero(get().swap.assetOut);
const exponent = getDisplayDenomExponent.optional()(get().swap.assetOut) ?? 0;
const exponent = getDisplayDenomExponent.optional(get().swap.assetOut) ?? 0;
const minOutputAsBaseUnit = Number(minOutput) * 10 ** exponent;
const outputLimitAsDisplayUnit = (OUTPUT_LIMIT / 10 ** exponent).toString();

Expand All @@ -144,7 +144,7 @@ export const createDutchAuctionSlice = (): SliceCreator<DutchAuctionSlice> => (s
swap.dutchAuction.maxOutput = '';
} else {
const minMaxOutput = getSmallestPossibleAmountAboveZero(get().swap.assetOut);
const exponent = getDisplayDenomExponent.optional()(get().swap.assetOut) ?? 0;
const exponent = getDisplayDenomExponent.optional(get().swap.assetOut) ?? 0;
const maxOutputAsBaseUnit = Number(maxOutput) * 10 ** exponent;
const outputLimitAsDisplayUnit = (OUTPUT_LIMIT / 10 ** exponent).toString();

Expand Down
Loading

0 comments on commit a7ed0ab

Please sign in to comment.