Repository navigation
feat: add Amount class for type-safe monetary operations - #62
Merged
Merged
Conversation
Problem:
- BigInt(asset.amount) throws when amount contains decimals
- No clear distinction between raw (smallest unit) and formatted values
- Easy to make mistakes when handling monetary values
Solution:
- Add Amount class with immutable design
- Factory methods: fromRaw(), fromFormatted(), parse() (auto-detect)
- Comparison: gt(), lt(), eq(), gte(), lte()
- Arithmetic: add(), sub(), mul(), div()
- Conversion: toRawString(), toFormatted(), toNumber()
- Helper: amountFromAsset() for smart parsing
Usage:
```ts
// From chain data (raw)
const balance = Amount.fromRaw('1000000000000000000', 18)
// From user input (formatted)
const input = Amount.fromFormatted('1.5', 18)
// Auto-detect (handles both)
const amount = Amount.parse(asset.amount, asset.decimals)
// Compare and operate
if (input.gt(balance)) throw new Error('Insufficient balance')
const remaining = balance.sub(input)
```
Fixes SendPage BigInt error with '102531.02649070'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
问题
BigInt(asset.amount)在asset.amount包含小数时抛出错误:根本原因:没有清晰区分 raw(最小单位)和 formatted(带小数)值。
解决方案
添加
Amount类,封装金额操作:设计原则
Amount.parse()自动判断 raw/formattedAPI
变更
src/types/amount.ts- Amount 类实现src/types/amount.test.ts- 35 个测试用例src/hooks/use-send.logic.ts- 使用 Amount 类修复 BUG长期收益
新开发者只需使用
Amount类,无需关心底层的 raw/formatted 区别,从根本上避免此类 BUG。