Skip to content

Commit

Permalink
use optional access instead of call
Browse files Browse the repository at this point in the history
  • Loading branch information
turbocrime committed Aug 21, 2024
1 parent d501174 commit bc5bfb2
Show file tree
Hide file tree
Showing 45 changed files with 82 additions and 84 deletions.
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 '@repo/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 @@ -22,7 +22,7 @@ import { shouldDisplay } from '../../../fetchers/balances/should-display';
import { sortByPriorityScore } from '../../../fetchers/balances/by-priority-score';

const getTradeLink = (balance: BalancesResponse): string => {
const metadata = getMetadataFromBalancesResponse.optional()(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: 1 addition & 3 deletions apps/minifront/src/components/shared/input-token.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ export default function InputToken({
loading,
}: InputTokenProps) {
const tokenExponent = useMemo(() => {
return getDisplayDenomExponent.optional()(
getMetadataFromBalancesResponse.optional()(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
Expand Up @@ -19,8 +19,8 @@ export const BalanceItem = ({ asset, value, onSelect }: BalanceItemProps) => {
const account = isBalance(asset) ? getAddressIndex(asset.accountAddress).account : undefined;
const metadataFromAsset = isMetadata(asset)
? asset
: getMetadataFromBalancesResponse.optional()(asset);
const metadataFromValue = getMetadataFromBalancesResponse.optional()(value);
: getMetadataFromBalancesResponse.optional(asset);
const metadataFromValue = getMetadataFromBalancesResponse.optional(value);

const isSelected = useMemo(() => {
if (!value) {
Expand Down
8 changes: 4 additions & 4 deletions apps/minifront/src/components/shared/selectors/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const mergeBalancesAndAssets = (
): BalanceOrMetadata[] => {
const filteredAssets = assets.filter(asset => {
return !balances.some(balance => {
const balanceMetadata = getMetadataFromBalancesResponse.optional()(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)) &&
getAddressIndex.optional(balance)?.equals(getAddressIndex.optional(value)) &&
getMetadataFromBalancesResponse
.optional()(balance)
?.equals(getMetadataFromBalancesResponse.optional()(value))
.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
Expand Up @@ -12,7 +12,7 @@ import { useStoreShallow } from '../../../utils/use-store-shallow';
import { Button } from '@repo/ui/components/ui/button';

const priceHistorySelector = (state: AllSlices) => ({
startMetadata: getMetadataFromBalancesResponse.optional()(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 @@ -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()(getMetadataFromBalancesResponse.optional()(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 '@repo/ui/ValueViewComponent';

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

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
8 changes: 4 additions & 4 deletions apps/minifront/src/fetchers/balances/by-priority-score.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import {
import { multiplyAmountByNumber, joinLoHiAmount } from '@penumbra-zone/types/amount';

export const sortByPriorityScore = (a: BalancesResponse, b: BalancesResponse) => {
const aScore = getMetadataFromBalancesResponse.optional()(a)?.priorityScore ?? 1n;
const bScore = getMetadataFromBalancesResponse.optional()(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
6 changes: 3 additions & 3 deletions apps/minifront/src/state/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,8 @@ export const isIncorrectDecimal = (
throw new Error('Missing balanceView');
}

const exponent = getDisplayDenomExponent.optional()(
getMetadataFromBalancesResponse.optional()(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 @@ -213,4 +213,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
4 changes: 2 additions & 2 deletions apps/minifront/src/state/swap/getters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getMetadata } from '@penumbra-zone/getters/value-view';
export const balancesResponseAndMetadataAreSameAsset = (
balancesResponse?: BalancesResponse,
metadata?: Metadata,
) => getMetadata.optional()(balancesResponse?.balanceView)?.equals(metadata);
) => getMetadata.optional(balancesResponse?.balanceView)?.equals(metadata);

export const getFirstBalancesResponseNotMatchingMetadata = (
balancesResponses: BalancesResponse[],
Expand Down Expand Up @@ -38,7 +38,7 @@ export const getBalanceByMatchingMetadataAndAddressIndex = (
metadata: Metadata,
) => {
return balances.find(balance => {
const balanceViewMetadata = getMetadataFromBalancesResponse.optional()(balance);
const balanceViewMetadata = getMetadataFromBalancesResponse.optional(balance);

return (
getAddressIndex(balance.accountAddress).account === addressIndex.account &&
Expand Down
4 changes: 2 additions & 2 deletions apps/minifront/src/state/swap/query-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export const getSwapQueryParams = (): SwapQueryParams => {
* Sets the swap query parameters in the URL hash based on the store state
*/
export const setSwapQueryParams = (state: AllSlices): void => {
const fromSymbol = getMetadataFromBalancesResponse.optional()(state.swap.assetIn)?.symbol;
const fromSymbol = getMetadataFromBalancesResponse.optional(state.swap.assetIn)?.symbol;
const toSymbol = state.swap.assetOut?.symbol;
const accountIndex = getAddressIndex.optional()(state.swap.assetIn)?.account;
const accountIndex = getAddressIndex.optional(state.swap.assetIn)?.account;

const searchParams = new URLSearchParams();
if (fromSymbol) {
Expand Down
4 changes: 2 additions & 2 deletions apps/minifront/src/state/swap/swap-balances-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const getAssetIn = (state: AllSlices, from?: string, account?: number) => {

if (from) {
const matchingBalancesResponse = filteredSwappableBalancesResponses.find(
balance => getMetadataFromBalancesResponse.optional()(balance)?.symbol === from,
balance => getMetadataFromBalancesResponse.optional(balance)?.symbol === from,
);
if (matchingBalancesResponse) {
return matchingBalancesResponse;
Expand Down Expand Up @@ -73,7 +73,7 @@ const getAssetOut = (state: AllSlices, to?: string, assetIn?: BalancesResponse)
return state.swap.assetOut;
}

if (getMetadataFromBalancesResponse.optional()(assetIn)?.equals(swappableAssets[0])) {
if (getMetadataFromBalancesResponse.optional(assetIn)?.equals(swappableAssets[0])) {
return swappableAssets[1];
}

Expand Down
2 changes: 1 addition & 1 deletion docs/adrs/001-getters.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ If we want to allow `undefined`, we can add a call to `.optional()`:
required because we called `.optional()`. Otherwise, TypeScript would have
guaranteed that the return value of `getAddressIndex()` was an actual
`AddressIndex`. */}
{getAddressIndex.optional()(addressView)?.account}
{getAddressIndex.optional(addressView)?.account}
</span>
</div>
```
Expand Down
2 changes: 1 addition & 1 deletion packages/getters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ At this point, it's worth mentioning that getters are _required by default_. If
What if the value you're getting _is_ optional, though? What if you don't want your getter to throw if either the value it's passed, or the value it returns, is `undefined`? That's what the `.optional()` property on the getter is for:

```tsx
const addressView = getAddressView.optional()(memoView)
const addressView = getAddressView.optional(memoView)

<div>
{addressView && <AddressViewComponent addressView={addressView} />}
Expand Down
4 changes: 2 additions & 2 deletions packages/perspective/src/plan/view-action-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,8 @@ export const viewActionPlan =
});

case 'actionDutchAuctionSchedule': {
const inputAssetId = getInputAssetId.optional()(actionPlan.action.value.description);
const outputAssetId = getOutputAssetId.optional()(actionPlan.action.value.description);
const inputAssetId = getInputAssetId.optional(actionPlan.action.value.description);
const outputAssetId = getOutputAssetId.optional(actionPlan.action.value.description);
const [inputMetadata, outputMetadata] = await Promise.all([
inputAssetId ? await denomMetadataByAssetId(inputAssetId) : undefined,
outputAssetId ? await denomMetadataByAssetId(outputAssetId) : undefined,
Expand Down
2 changes: 1 addition & 1 deletion packages/services/src/view-service/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ class BalancesAggregator {
* of the equivalent value and the `amount` of the `ValueView`.
*/
private async aggregateEquivalentValues(valueView: ValueView, toAdd: SpendableNoteRecord) {
const assetId = getAssetIdFromRecord.optional()(toAdd);
const assetId = getAssetIdFromRecord.optional(toAdd);
if (!assetId?.inner) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { status } from '../status.js';
import { appParameters } from '../app-parameters.js';

export const isUnbondingTokenBalance = (balancesResponse: PartialMessage<BalancesResponse>) => {
const display = getDisplayFromBalancesResponse.optional()(new BalancesResponse(balancesResponse));
const display = getDisplayFromBalancesResponse.optional(new BalancesResponse(balancesResponse));
return display ? assetPatterns.unbondingToken.matches(display) : false;
};

Expand Down Expand Up @@ -40,7 +40,7 @@ export const getIsClaimable = async (
return false;
}

const display = getDisplayFromBalancesResponse.optional()(new BalancesResponse(balancesResponse));
const display = getDisplayFromBalancesResponse.optional(new BalancesResponse(balancesResponse));
if (!display) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const unbondingTokensByAddressIndex: Impl['unbondingTokensByAddressIndex'
}

const regexResult = assetPatterns.unbondingToken.capture(
getDisplayFromBalancesResponse.optional()(new BalancesResponse(balancesResponse)) ?? '',
getDisplayFromBalancesResponse.optional(new BalancesResponse(balancesResponse)) ?? '',
);
if (!regexResult) {
throw new Error('expected delegation token identity key not present');
Expand Down
Loading

0 comments on commit bc5bfb2

Please sign in to comment.