Skip to content

Commit

Permalink
replace even mooooore NumberInput with HugeDecimalInput
Browse files Browse the repository at this point in the history
  • Loading branch information
NoahSaso committed Oct 2, 2024
1 parent 78048ae commit 7fbf3ec
Show file tree
Hide file tree
Showing 64 changed files with 620 additions and 728 deletions.
20 changes: 18 additions & 2 deletions packages/math/HugeDecimal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,20 @@ export class HugeDecimal {
return this.value.toJSON()
}

toNumber() {
return this.value.toNumber()
/**
* Returns the value of this HugeDecimal instance as a JavaScript primitive
* number.
*
* Pass `truncateDecimals` to truncate to a specific number of decimal places.
* Leaving it undefined will preserve all existing decimal places.
*
* @param truncateDecimals whether or not to truncate the decimal places
* @returns a number
*/
toNumber(truncateDecimals?: number) {
return truncateDecimals !== undefined
? Number(this.toFixed(truncateDecimals))
: this.value.toNumber()
}

/**
Expand Down Expand Up @@ -171,6 +183,10 @@ export class HugeDecimal {
return this.value.isZero()
}

isNaN() {
return this.value.isNaN()
}

lt(n: HugeDecimal.Value) {
return this.value.lt(valueToBigNumber(n))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ export const AuthzGrantRevokeComponent: ActionComponent<
className="mt-2 self-start"
onClick={() =>
appendCoin({
amount: 1,
amount: '1',
denom: nativeToken.denomOrAddress,
decimals: nativeToken.decimals,
})
Expand Down Expand Up @@ -467,7 +467,7 @@ export const AuthzGrantRevokeComponent: ActionComponent<
className="mt-2 self-start"
onClick={() =>
appendCoin({
amount: 1,
amount: '1',
denom: nativeToken.denomOrAddress,
decimals: nativeToken.decimals,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,9 @@ export class AuthzGrantRevokeAction extends ActionBase<AuthzGrantRevokeData> {
callsRemaining: BigInt(calls),
// MaxFundsLimit
// CombinedLimit
amounts: funds.map(({ denom, amount, decimals }) => ({
amount: HugeDecimal.fromHumanReadable(amount, decimals).toString(),
denom,
})),
amounts: funds.map(({ denom, amount, decimals }) =>
HugeDecimal.fromHumanReadable(amount, decimals).toCoin(denom)
),
})

let authorization: Any | undefined
Expand Down Expand Up @@ -381,7 +380,7 @@ export class AuthzGrantRevokeAction extends ActionBase<AuthzGrantRevokeData> {
return {
denom,
amount:
HugeDecimal.from(amount).toHumanReadableNumber(decimals),
HugeDecimal.from(amount).toHumanReadableString(decimals),
decimals,
}
}) ?? [],
Expand Down Expand Up @@ -422,7 +421,7 @@ export class AuthzGrantRevokeAction extends ActionBase<AuthzGrantRevokeData> {
return {
denom,
amount:
HugeDecimal.from(amount).toHumanReadableNumber(decimals),
HugeDecimal.from(amount).toHumanReadableString(decimals),
decimals,
}
}) ?? [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export type AuthzGrantRevokeData = {
contract: string
funds: {
denom: string
amount: number
amount: string
// Will multiply `amount` by 10^decimals when generating the message.
decimals: number
}[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ActionComponent } from '@dao-dao/types/actions'

export type CommunityPoolDepositData = {
chainId: string
amount: number
amount: string
denom: string
_error?: string
}
Expand All @@ -26,7 +26,7 @@ export const CommunityPoolDepositComponent: ActionComponent<
> = ({ fieldNamePrefix, isCreating, errors, options: { tokens } }) => {
const { t } = useTranslation()

const { register, watch, setValue } =
const { register, watch, setValue, getValues } =
useFormContext<CommunityPoolDepositData>()

const spendChainId = watch((fieldNamePrefix + 'chainId') as 'chainId')
Expand All @@ -40,9 +40,7 @@ export const CommunityPoolDepositComponent: ActionComponent<
token.chainId === spendChainId && token.denomOrAddress === spendDenom
)
const selectedDecimals = selectedToken?.token.decimals ?? 0
const selectedBalance = HugeDecimal.from(
selectedToken?.balance ?? 0
).toHumanReadableNumber(selectedDecimals)
const selectedBalance = HugeDecimal.from(selectedToken?.balance ?? 0)

// A warning if the denom was not found in the treasury or the amount is too
// high. We don't want to make this an error because often people want to
Expand All @@ -53,10 +51,10 @@ export const CommunityPoolDepositComponent: ActionComponent<
? undefined
: !selectedToken
? t('error.unknownDenom', { denom: spendDenom })
: spendAmount > selectedBalance
: selectedBalance.toHumanReadable(selectedDecimals).lt(spendAmount)
? t('error.insufficientFundsWarning', {
amount: selectedBalance.toLocaleString(undefined, {
maximumFractionDigits: selectedDecimals,
amount: selectedBalance.toInternationalizedHumanReadableString({
decimals: selectedDecimals,
}),
tokenSymbol: symbol,
})
Expand All @@ -69,6 +67,7 @@ export const CommunityPoolDepositComponent: ActionComponent<
amount={{
watch,
setValue,
getValues,
register,
fieldName: (fieldNamePrefix + 'amount') as 'amount',
error: errors?.amount,
Expand All @@ -91,11 +90,11 @@ export const CommunityPoolDepositComponent: ActionComponent<
description:
t('title.balance') +
': ' +
HugeDecimal.from(balance)
.toHumanReadableNumber(token.decimals)
.toLocaleString(undefined, {
maximumFractionDigits: token.decimals,
}),
HugeDecimal.from(
balance
).toInternationalizedHumanReadableString({
decimals: token.decimals,
}),
})),
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { coins } from '@cosmjs/stargate'
import { useFormContext } from 'react-hook-form'

import { HugeDecimal } from '@dao-dao/math'
Expand Down Expand Up @@ -84,7 +83,7 @@ export class CommunityPoolDepositAction extends ActionBase<CommunityPoolDepositD

this.defaults = {
chainId: options.chain.chain_id,
amount: 100,
amount: '100',
denom: options.chainContext.nativeToken?.denomOrAddress || '',
}
}
Expand Down Expand Up @@ -115,10 +114,10 @@ export class CommunityPoolDepositAction extends ActionBase<CommunityPoolDepositD
typeUrl: MsgFundCommunityPool.typeUrl,
value: MsgFundCommunityPool.fromPartial({
depositor,
amount: coins(
HugeDecimal.fromHumanReadable(amount, token.decimals).toString(),
denom
),
amount: HugeDecimal.fromHumanReadable(
amount,
token.decimals
).toCoins(denom),
}),
},
})
Expand Down Expand Up @@ -154,7 +153,7 @@ export class CommunityPoolDepositAction extends ActionBase<CommunityPoolDepositD

return {
chainId,
amount: HugeDecimal.from(amount).toHumanReadableNumber(decimals),
amount: HugeDecimal.from(amount).toHumanReadableString(decimals),
denom,
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export type ConfigureRebalancerData = {
maxLimit?: number
minBalance?: {
denom: string
amount: number
amount: string
}
targetOverrideStrategy: TargetOverrideStrategy
}
Expand Down Expand Up @@ -237,10 +237,12 @@ export const ConfigureRebalancerComponent: ActionComponent<
amount={{
watch,
setValue,
getValues,
register,
fieldName: (fieldNamePrefix +
`tokens.${index}.percent`) as `tokens.${number}.percent`,
error: errors?.tokens?.[index]?.percent,
numericValue: true,
min: 0.01,
max: 100,
step: 0.01,
Expand Down Expand Up @@ -339,7 +341,7 @@ export const ConfigureRebalancerComponent: ActionComponent<
? undefined
: {
denom: tokens[0]?.denom ?? '',
amount: 1,
amount: '1',
}
)
}
Expand All @@ -357,6 +359,7 @@ export const ConfigureRebalancerComponent: ActionComponent<
amount={{
watch,
setValue,
getValues,
register,
fieldName: (fieldNamePrefix +
'minBalance.amount') as 'minBalance.amount',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,26 @@ guide](https://github.com/DA0-DA0/dao-dao-ui/wiki/Bulk-importing-actions).
```json
{
"chainId": "<CHAIN ID>",
...
"trustee": "<TRUSTEE ADDRESS>",
"baseDenom": "<BASE DENOM>",
"tokens": [
{
"denom": "<DENOM>",
"percent": <PERCENT>
},
...
],
"pid": {
"kp": <KP>,
"ki": <KI>,
"kd": <KD>
},
"maxLimit": <MAX LIMIT>,
"minBalance": {
"denom": "<DENOM>",
"amount": "<AMOUNT>"
} | undefined,
"targetOverrideStrategy": "<proportional | priority>"
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ export class ConfigureRebalancerAction extends ActionBase<ConfigureRebalancerDat
denom: minBalanceTarget.denom,
amount: HugeDecimal.from(
minBalanceTarget.min_balance
).toHumanReadableNumber(minBalanceToken.decimals),
).toHumanReadableString(minBalanceToken.decimals),
}
: undefined,
targetOverrideStrategy:
Expand Down Expand Up @@ -682,7 +682,7 @@ export class ConfigureRebalancerAction extends ActionBase<ConfigureRebalancerDat
denom: minBalanceTarget.denom,
amount: HugeDecimal.from(
minBalanceTarget.min_balance
).toHumanReadableNumber(minBalanceToken.decimals),
).toHumanReadableString(minBalanceToken.decimals),
}
: undefined,
targetOverrideStrategy: data.target_override_strategy || 'proportional',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,7 @@ export class CreateRewardDistributionAction extends ActionBase<CreateRewardDistr
}: any): CreateRewardDistributionData {
return {
...data,
// Ensure initialFunds is a string.
initialFunds: HugeDecimal.from(initialFunds).toString(),
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export type CreateValenceAccountData = {
chainId: string
funds: {
denom: string
amount: number
amount: string
// Will multiply `amount` by 10^decimals when generating the message.
decimals: number
}[]
Expand Down Expand Up @@ -133,7 +133,7 @@ export const CreateValenceAccountComponent: ActionComponent<
className="self-start"
onClick={() =>
appendCoin({
amount: 1,
amount: '1',
denom: nativeToken.denomOrAddress,
decimals: nativeToken.decimals,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export class CreateValenceAccountAction extends ActionBase<CreateValenceAccountD
funds: [
{
denom: 'untrn',
amount: 10,
amount: '10',
decimals: 6,
},
],
Expand Down Expand Up @@ -199,18 +199,17 @@ export class CreateValenceAccountAction extends ActionBase<CreateValenceAccountD
)
}

const convertedFunds = funds.map(({ denom, amount, decimals }) => ({
denom,
amount: HugeDecimal.fromHumanReadable(amount, decimals).toString(),
}))
const convertedFunds = funds.map(({ denom, amount, decimals }) =>
HugeDecimal.fromHumanReadable(amount, decimals).toCoin(denom)
)

// Add service fee to funds.
if (serviceFee && serviceFee.amount !== '0') {
const existing = convertedFunds.find((f) => f.denom === serviceFee.denom)
if (existing) {
existing.amount = (
BigInt(existing.amount) + BigInt(serviceFee.amount)
).toString()
existing.amount = HugeDecimal.from(existing.amount)
.plus(serviceFee.amount)
.toString()
} else {
convertedFunds.push({
denom: serviceFee.denom,
Expand Down Expand Up @@ -279,7 +278,7 @@ export class CreateValenceAccountAction extends ActionBase<CreateValenceAccountD

return {
denom,
amount: HugeDecimal.from(amount).toHumanReadableNumber(
amount: HugeDecimal.from(amount).toHumanReadableString(
token.decimals
),
decimals: token.decimals,
Expand Down
5 changes: 3 additions & 2 deletions packages/stateful/actions/core/actions/Execute/Component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export type ExecuteData = {
message: string
funds: {
denom: string
amount: number
amount: string
// Will multiply `amount` by 10^decimals when generating the message.
decimals: number
}[]
Expand All @@ -58,7 +58,7 @@ export const ExecuteComponent: ActionComponent<ExecuteOptions> = ({
const { context } = useActionOptions()
const { chain_id: chainId, bech32_prefix: bech32Prefix } = useChain()

const { register, control, watch, setValue } = useFormContext()
const { register, control, watch, setValue, getValues } = useFormContext()
const {
fields: coins,
append: appendCoin,
Expand Down Expand Up @@ -192,6 +192,7 @@ export const ExecuteComponent: ActionComponent<ExecuteOptions> = ({
amount={{
watch,
setValue,
getValues,
register,
fieldName: fieldNamePrefix + 'funds.0.amount',
error: errors?.funds?.[0]?.amount,
Expand Down
Loading

0 comments on commit 7fbf3ec

Please sign in to comment.