Skip to content

Commit

Permalink
Fixed chains potentially not having native tokens.
Browse files Browse the repository at this point in the history
  • Loading branch information
NoahSaso committed Sep 21, 2023
1 parent 3bc1062 commit cee28f1
Show file tree
Hide file tree
Showing 13 changed files with 50 additions and 23 deletions.
1 change: 1 addition & 0 deletions packages/i18n/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@
"metadataUpload": "Failed to upload metadata.",
"missingGovernanceTokenAddress": "Missing governance token address.",
"missingGovernanceTokenDenom": "Missing governance token denom.",
"missingNativeToken": "Missing native token.",
"mustBeMemberToCreateCompensationCycle": "You must be a member of the DAO to create a compensation cycle.",
"mustBeMemberToCreatePost": "You must be a member of the DAO to create a post.",
"mustBeMemberToCreateProposal": "You must be a member of the DAO to create a proposal.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export const makeCommunityPoolDepositAction: ActionMaker<
const useDefaults: UseDefaults<CommunityPoolDepositData> = () => ({
chainId: currentChainId,
amount: 100,
denom: nativeToken.denomOrAddress,
denom: nativeToken?.denomOrAddress || '',
})

const useTransformToCosmos: UseTransformToCosmos<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ export const ManageStakingComponent: ActionComponent<
nativeToken,
} = useChainContext()

if (!nativeToken) {
throw new Error(t('error.missingNativeToken'))
}

// Metadata for the given denom.
const minAmount = convertMicroDenomToDenomWithDecimals(
1,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { coin, parseCoins } from '@cosmjs/amino'
import { useCallback } from 'react'
import { useFormContext } from 'react-hook-form'
import { useTranslation } from 'react-i18next'

import {
nativeDelegationInfoSelector,
Expand Down Expand Up @@ -175,6 +176,7 @@ const useDecodedCosmosMsg: UseDecodedCosmosMsg<ManageStakingData> = (
}

const InnerComponent: ActionComponent = (props) => {
const { t } = useTranslation()
const { address: _address, context, chain } = useActionOptions()
const { watch } = useFormContext()

Expand All @@ -183,6 +185,10 @@ const InnerComponent: ActionComponent = (props) => {
nativeToken,
} = useChainContext()

if (!nativeToken) {
throw new Error(t('error.missingNativeToken'))
}

const address =
context.type === ActionContextType.Dao && currentChainId !== chain.chain_id
? context.info.polytoneProxies[currentChainId] || ''
Expand Down
4 changes: 2 additions & 2 deletions packages/stateful/actions/core/treasury/Spend/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ import {
getChainForChainName,
getIbcTransferInfoBetweenChains,
getIbcTransferInfoFromChainSource,
getNativeTokenForChainId,
isDecodedStargateMsg,
isValidBech32Address,
isValidContractAddress,
makeBankMessage,
makePolytoneExecuteMessage,
makeStargateMessage,
makeWasmMessage,
maybeGetNativeTokenForChainId,
objectMatchesStructure,
transformBech32Address,
} from '@dao-dao/utils'
Expand All @@ -61,7 +61,7 @@ const useDefaults: UseDefaults<SpendData> = () => {
toChainId: chainId,
to: walletAddress,
amount: 1,
denom: getNativeTokenForChainId(chainId).denomOrAddress,
denom: maybeGetNativeTokenForChainId(chainId)?.denomOrAddress || '',
}
}

Expand Down
4 changes: 4 additions & 0 deletions packages/stateful/components/WalletStakingModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ export const WalletStakingModal = (props: WalletStakingModalProps) => {
} = useChainContext()
const { address: walletAddress = '', getSigningCosmWasmClient } = useWallet()

if (!nativeToken) {
throw new Error(t('error.missingNativeToken'))
}

const { walletBalance, refreshBalances } = useWalletInfo()
// Refreshes validator balances.
const setRefreshValidatorBalances = useSetRecoilState(
Expand Down
12 changes: 6 additions & 6 deletions packages/stateful/components/dao/DaoTreasuryHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,12 @@ export const InnerDaoTreasuryHistory = ({
const lineGraphValues = useMemo(() => {
let runningTotal = convertMicroDenomToDenomWithDecimals(
nativeBalance.amount,
nativeToken.decimals
nativeToken?.decimals ?? 0
)

return (
transactions
.filter(({ denomLabel }) => denomLabel === nativeToken.symbol)
.filter(({ denomLabel }) => denomLabel === nativeToken?.symbol)
.map(({ amount, outgoing }) => {
let currentTotal = runningTotal
runningTotal -= (outgoing ? -1 : 1) * amount
Expand All @@ -183,8 +183,8 @@ export const InnerDaoTreasuryHistory = ({
)
}, [
nativeBalance.amount,
nativeToken.decimals,
nativeToken.symbol,
nativeToken?.decimals,
nativeToken?.symbol,
transactions,
])

Expand All @@ -199,9 +199,9 @@ export const InnerDaoTreasuryHistory = ({
<div className="max-w-lg">
<LineGraph
title={t('title.nativeBalanceOverTime', {
denomLabel: nativeToken.symbol,
denomLabel: nativeToken?.symbol ?? 'unknown',
}).toLocaleUpperCase()}
yTitle={nativeToken.symbol}
yTitle={nativeToken?.symbol || 'Unknown token'}
yValues={lineGraphValues}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ const ProposalDepositInput = ({
]
: []),
// Then native.
nativeToken,
...(nativeToken ? [nativeToken] : []),
// Then other CW20.
{
chainId,
Expand All @@ -171,7 +171,7 @@ const ProposalDepositInput = ({
},
// Then the chain assets.
...getChainAssets(chainId).filter(
({ denomOrAddress }) => denomOrAddress !== nativeToken.denomOrAddress
({ denomOrAddress }) => denomOrAddress !== nativeToken?.denomOrAddress
),
]
const selectedToken = availableTokens.find(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export const NewAttribute = ({
className="self-start"
onClick={() =>
appendToken({
denomOrAddress: nativeToken.denomOrAddress,
denomOrAddress: nativeToken?.denomOrAddress || '',
})
}
variant="ghost"
Expand Down
4 changes: 2 additions & 2 deletions packages/stateless/components/ChainProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { ReactNode } from 'react'

import {
getChainForChainId,
getNativeTokenForChainId,
getSupportedChainConfig,
maybeGetNativeTokenForChainId,
} from '@dao-dao/utils'

import { ChainContext } from '../hooks/useChainContext'
Expand All @@ -18,7 +18,7 @@ export const ChainProvider = ({ chainId, children }: ChainProviderProps) => (
value={{
chainId,
chain: getChainForChainId(chainId),
nativeToken: getNativeTokenForChainId(chainId),
nativeToken: maybeGetNativeTokenForChainId(chainId),
config: getSupportedChainConfig(chainId),
}}
>
Expand Down
10 changes: 4 additions & 6 deletions packages/stateless/components/inputs/TokenInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export const TokenInput = <
const selectedTokenDisplay = useMemo(
() =>
selectedToken ? (
<div className="flex flex-row items-center gap-2">
<div className="flex min-w-0 flex-row items-center gap-2">
<Tooltip
title={t('info.tokenOnChain', {
token: selectedToken.symbol,
Expand Down Expand Up @@ -161,7 +161,7 @@ export const TokenInput = <
</div>
</Tooltip>

<p>
<p className="min-w-[4rem] grow truncate text-left">
{readOnly &&
amount.toLocaleString(undefined, {
// Show as many decimals as possible (max is 20).
Expand Down Expand Up @@ -232,11 +232,9 @@ export const TokenInput = <
token.imageUrl || getFallbackImage(token.denomOrAddress),
...token,
rightNode: (
<p className="caption-text">
<p className="caption-text max-w-[5rem] truncate">
{allTokensOnSameChain
? token.denomOrAddress.startsWith('ibc/')
? token.denomOrAddress.slice(0, 9) + '...'
: token.denomOrAddress
? token.denomOrAddress
: getDisplayNameForChainId(token.chainId)}
</p>
),
Expand Down
8 changes: 6 additions & 2 deletions packages/types/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ import { CodeIdConfig, PolytoneConfig } from './utils'
export type IChainContext = {
chainId: string
chain: Chain
nativeToken: GenericToken
// Chain may not have a native token.
nativeToken?: GenericToken
// If defined, this is a supported chain.
config?: SupportedChainConfig
}

export type SupportedChainContext = Required<IChainContext>
// Require supported chain config.
export type SupportedChainContext = Omit<IChainContext, 'config'> & {
config: SupportedChainConfig
}

export interface Validator {
address: string
Expand Down
12 changes: 11 additions & 1 deletion packages/utils/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const cosmosValidatorToValidator = ({

export const getImageUrlForChainId = (chainId: string): string => {
// Use native token image if available.
const { imageUrl } = getNativeTokenForChainId(chainId)
const { imageUrl } = maybeGetNativeTokenForChainId(chainId) || {}
if (imageUrl) {
return imageUrl
}
Expand Down Expand Up @@ -184,6 +184,16 @@ export const getNativeTokenForChainId = (chainId: string): GenericToken => {
return cachedNativeTokens[chainId]!
}

export const maybeGetNativeTokenForChainId = (
chainId: string
): GenericToken | undefined => {
try {
return getNativeTokenForChainId(chainId)
} catch {
return undefined
}
}

const cachedTokens: Record<string, GenericToken | undefined> = {}
export const getTokenForChainIdAndDenom = (
chainId: string,
Expand Down

0 comments on commit cee28f1

Please sign in to comment.