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

fix: support asset transfers for decimal values over the safe number value #382

Open
wants to merge 1 commit into
base: test-algosdk-v3
Choose a base branch
from
Open
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
40 changes: 20 additions & 20 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -193,5 +193,8 @@
],
"semantic-release-export-data"
]
},
"overrides": {
"ws@>7.0.0 <7.5.9": "7.5.10"
}
}
6 changes: 3 additions & 3 deletions src/features/abi-methods/mappers/form-schema-mappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export const abiTypeToFormFieldSchema = (type: algosdk.ABIType, isOptional: bool
return bigIntSchema(isOptional ? uintSchema.optional() : uintSchema)
}
if (type instanceof algosdk.ABIByteType) {
const uintSchema = z.number().min(0).max(255, `Value must be less than or equal to 255`)
return numberSchema(isOptional ? uintSchema.optional() : uintSchema)
const byteSchema = z.number().min(0).max(255, `Value must be less than or equal to 255`)
return numberSchema(isOptional ? byteSchema.optional() : byteSchema)
}
if (type instanceof algosdk.ABIBoolType) {
const boolSchema = z
Expand Down Expand Up @@ -76,7 +76,7 @@ export const abiTypeToFormFieldSchema = (type: algosdk.ABIType, isOptional: bool

export const abiReferenceTypeToFormFieldSchema = (type: algosdk.ABIReferenceType): z.ZodTypeAny => {
if (type === algosdk.ABIReferenceType.asset || type === algosdk.ABIReferenceType.application) {
return numberSchema(z.number().min(0))
return bigIntSchema(z.bigint().min(0n))
}
if (type === algosdk.ABIReferenceType.account) {
return addressFieldSchema
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, useEffect } from 'react'
import { useCreateAppInterfaceStateMachine } from '../../data'
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { zfd } from 'zod-form-data'
import { z } from 'zod'
import { Card, CardContent } from '@/features/common/components/card'
Expand All @@ -17,7 +17,7 @@ import { useLoadableAppInterfacesAtom } from '../../data'
const schema = zfd.formData({
application: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' })),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' })),
exists: z.boolean().optional(),
appInterfaceExists: z.boolean().optional(),
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { CancelButton } from '@/features/forms/components/cancel-button'
import { Form } from '@/features/forms/components/form'
import { FormActions } from '@/features/forms/components/form-actions'
import { SubmitButton } from '@/features/forms/components/submit-button'
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { useCallback, useMemo } from 'react'
import { z } from 'zod'
import { zfd } from 'zod-form-data'
Expand Down Expand Up @@ -38,10 +38,10 @@ const formSchema = zfd.formData({
)
.max(4)
),
assets: zfd.repeatable(z.array(z.object({ id: z.string(), assetId: numberSchema(z.bigint().min(0n)) })).max(8)),
applications: zfd.repeatable(z.array(z.object({ id: z.string(), applicationId: numberSchema(z.bigint().min(0n)) })).max(8)),
assets: zfd.repeatable(z.array(z.object({ id: z.string(), assetId: bigIntSchema(z.bigint().min(0n)) })).max(8)),
applications: zfd.repeatable(z.array(z.object({ id: z.string(), applicationId: bigIntSchema(z.bigint().min(0n)) })).max(8)),
boxes: zfd.repeatable(
z.array(z.object({ id: z.string(), applicationId: numberSchema(z.bigint().min(0n)), boxName: zfd.text(z.string().optional()) })).max(8)
z.array(z.object({ id: z.string(), applicationId: bigIntSchema(z.bigint().min(0n)), boxName: zfd.text(z.string().optional()) })).max(8)
),
})

Expand Down
28 changes: 28 additions & 0 deletions src/features/forms/data/common.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Decimal from 'decimal.js'
import { z } from 'zod'
import { zfd } from 'zod-form-data'

Expand All @@ -19,3 +20,30 @@ export const numberSchema = <TSchema extends z.ZodTypeAny>(schema: TSchema) =>
.transform((val) => (val != null ? Number(val) : undefined))
.pipe(schema)
)

// This is a little different to the others above, as zod doesn't have a decimal type
// It's not perfect, however does the job for our current use case.
export const decimalSchema = (params: Parameters<typeof z.coerce.string>[0]) =>
zfd.text(
z.coerce
.string(params)
.optional()
.superRefine((data, ctx) => {
if (!data) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: params?.required_error || 'Required',
})
}

if (data && data.startsWith('-')) {
ctx.addIssue({
code: z.ZodIssueCode.too_small,
minimum: 0,
inclusive: true,
type: 'number',
})
}
})
.transform((val) => (val != null ? new Decimal(val) : undefined))
)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema, decimalSchema } from '@/features/forms/data/common'
import { addressFieldSchema, commonSchema, receiverFieldSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -33,7 +33,7 @@ const formSchema = z
clawbackTarget: addressFieldSchema,
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(),
unitName: z.string().optional(),
clawback: z.string().optional(),
Expand All @@ -53,7 +53,7 @@ const formSchema = z
})
}
}),
amount: numberSchema(z.number({ required_error: 'Required', invalid_type_error: 'Required' })),
amount: decimalSchema({ required_error: 'Required', invalid_type_error: 'Required' }),
})
.superRefine((data, ctx) => {
if (data.asset.clawback && data.sender && data.sender.resolvedAddress && data.sender.resolvedAddress !== data.asset.clawback) {
Expand Down Expand Up @@ -189,7 +189,7 @@ export function AssetClawbackTransactionBuilder({ mode, transaction, onSubmit, o
sender: data.sender,
receiver: data.receiver,
clawbackTarget: data.clawbackTarget,
amount: data.amount,
amount: data.amount!,
fee: data.fee,
validRounds: data.validRounds,
note: data.note,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { commonSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -31,7 +31,7 @@ const formSchema = {
...senderFieldSchema,
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(),
manager: z.string().optional(),
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { addressFieldSchema, commonSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -32,7 +32,7 @@ const formSchema = z
frozen: z.string(),
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(),
unitName: z.string().optional(),
freeze: z.string().optional(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { commonSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -29,7 +29,7 @@ const formSchema = {
...senderFieldSchema,
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(),
unitName: z.string().optional(),
clawback: z.string().optional(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { addressFieldSchema, commonSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -30,7 +30,7 @@ const formSchema = {
closeRemainderTo: addressFieldSchema,
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(),
unitName: z.string().optional(),
clawback: z.string().optional(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema } from '@/features/forms/data/common'
import { commonSchema, optionalAddressFieldSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -29,7 +29,7 @@ const formSchema = z
...senderFieldSchema,
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(), // This field is used to determine if an asset has been resolved
unitName: z.string().optional(),
manager: z.string().optional(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { numberSchema } from '@/features/forms/data/common'
import { bigIntSchema, decimalSchema } from '@/features/forms/data/common'
import { commonSchema, receiverFieldSchema, senderFieldSchema } from '../data/common'
import { z } from 'zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
Expand Down Expand Up @@ -32,7 +32,7 @@ const formSchema = {
...receiverFieldSchema,
asset: z
.object({
id: numberSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
id: bigIntSchema(z.bigint({ required_error: 'Required', invalid_type_error: 'Required' }).min(1n)),
decimals: z.number().optional(),
unitName: z.string().optional(),
clawback: z.string().optional(),
Expand All @@ -46,7 +46,7 @@ const formSchema = {
})
}
}),
amount: numberSchema(z.number({ required_error: 'Required', invalid_type_error: 'Required' }).min(0)),
amount: decimalSchema({ required_error: 'Required' }),
}

const formData = zfd.formData(formSchema)
Expand Down Expand Up @@ -163,7 +163,7 @@ export function AssetTransferTransactionBuilder({ mode, transaction, activeAccou
asset: data.asset,
sender: data.sender,
receiver: data.receiver,
amount: data.amount,
amount: data.amount!,
fee: data.fee,
validRounds: data.validRounds,
note: data.note,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from '@algorandfoundation/algokit-utils/types/composer'
import { base64ToBytes } from '@/utils/base64-to-bytes'
import { Buffer } from 'buffer'
import Decimal from 'decimal.js'

export const asAlgosdkTransactions = async (transaction: BuildTransactionResult): Promise<algosdk.Transaction[]> => {
if (transaction.type === BuildableTransactionType.Payment || transaction.type === BuildableTransactionType.AccountClose) {
Expand Down Expand Up @@ -176,8 +177,14 @@ export const asAssetTransferTransactionParams = (
| BuildAssetClawbackTransactionResult
): AssetTransferParams => {
invariant(transaction.asset.decimals !== undefined, 'Asset decimals is required')

const amount = 'amount' in transaction && transaction.amount > 0 ? BigInt(transaction.amount * 10 ** transaction.asset.decimals) : 0n
let amount = 0n
if ('amount' in transaction && transaction.amount.gt(0)) {
const convertedAmount = transaction.amount.mul(new Decimal(10).pow(transaction.asset.decimals))
if (!convertedAmount.isInteger()) {
throw new Error('Asset transfer failed to convert to the lowest unit')
}
amount = BigInt(convertedAmount.toString())
}
return {
sender: transaction.sender.resolvedAddress,
receiver: 'receiver' in transaction ? transaction.receiver.resolvedAddress : transaction.sender.resolvedAddress,
Expand Down
5 changes: 3 additions & 2 deletions src/features/transaction-wizard/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import React from 'react'
import { Nfd } from '@/features/nfd/data/types'
import { Arc56Contract } from '@algorandfoundation/algokit-utils/types/app-arc56'
import { AbiFormItemValue } from '@/features/abi-methods/models'
import Decimal from 'decimal.js'

export enum BuildableTransactionType {
// pay
Expand Down Expand Up @@ -137,7 +138,7 @@ export type BuildAssetTransferTransactionResult = CommonBuildTransactionResult &
}
type: BuildableTransactionType.AssetTransfer
receiver: AddressOrNfd
amount: number
amount: Decimal
}

export type BuildAssetOptInTransactionResult = CommonBuildTransactionResult & {
Expand Down Expand Up @@ -171,7 +172,7 @@ export type BuildAssetClawbackTransactionResult = CommonBuildTransactionResult &
type: BuildableTransactionType.AssetClawback
receiver: AddressOrNfd
clawbackTarget: AddressOrNfd
amount: number
amount: Decimal
}

export type BuildAssetCreateTransactionResult = CommonBuildTransactionResult & {
Expand Down
30 changes: 29 additions & 1 deletion src/utils/as-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,32 @@ export const normaliseAlgoSdkData = (obj: unknown): unknown => {
return obj
}

export const asJson = (value: unknown) => JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2)
const toNumber = (value: number | bigint) => {
if (typeof value === 'number') return value

if (value > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error(`Cannot convert ${value} to a Number as it is larger than the maximum safe integer the Number type can hold.`)
} else if (value < BigInt(Number.MIN_SAFE_INTEGER)) {
throw new Error(`Cannot convert ${value} to a Number as it is smaller than the minimum safe integer the Number type can hold.`)
}
return Number(value)
}

const defaultJsonValueReplacer = (_key: string, value: unknown) => {
if (typeof value === 'bigint') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not so sure about bigint can be serialised to either string or number ... I think I prefer it to be always string.

try {
return toNumber(value)
} catch {
return value.toString()
}
}
return value
}

export const asJson = (
value: unknown,
replacer: (key: string, value: unknown) => unknown = defaultJsonValueReplacer,
space?: string | number
) => {
return JSON.stringify(value, replacer, space)
}
Loading