Skip to content

Commit 3a1b1cd

Browse files
committed
Further Edits to Flow Action docs.
1 parent 36da601 commit 3a1b1cd

File tree

3 files changed

+187
-174
lines changed

3 files changed

+187
-174
lines changed

docs/blockchain-development-tutorials/forte/fixed-point-128-bit-math.md

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@ sidebar_label: DeFi Math Utils
1818

1919
# High-Precision Fixed-Point 128 Bit Math
2020

21-
Dealing with decimals is a notorious issue for most developers on other chains, especially when working with DeFi. Blockchains are deterministic systems and floating-point arithmetic is non-deterministic across different compilers and architectures, this is why blockchains use fixed-point arithmetic via integers (scaling numbers by a fixed factor). The issue with this is that these fixed-point integers tend to be very imprecise when using various mathematical operations on them. The more operations you apply to these numbers, the more imprecise these numbers become. However [`DeFiActionsMathUtils`] provides a standardized library for high-precision mathematical operations in DeFi applications on Flow. The contract extends Cadence's native 8-decimal precision (`UFix64`) to 24 decimals using `UInt128` for intermediate calculations, ensuring accuracy in complex financial computations while maintaining deterministic results across the network.
21+
## Overview
22+
Dealing with decimals is a notorious issue for most developers on other chains, especially when working with decentralized finance (DeFi). Blockchains are deterministic systems and floating-point arithmetic is non-deterministic across different compilers and architectures, which is why blockchains use fixed-point arithmetic via integers (scaling numbers by a fixed factor).
23+
24+
The issue with this is that these fixed-point integers tend to be very imprecise when using various mathematical operations on them. The more operations you apply to these numbers, the more imprecise these numbers become. However [`DeFiActionsMathUtils`] provides a standardized library for high-precision mathematical operations in DeFi applications on Flow. The contract extends Cadence's native 8-decimal precision (`UFix64`) to 24 decimals using `UInt128` for intermediate calculations, ensuring accuracy in complex financial computations while maintaining deterministic results across the network.
2225

2326
Through integration of this math utility library, developers can ensure that their DeFi protocols perform precise calculations for liquidity pools, yield farming, token swaps, and other financial operations without accumulating rounding errors.
2427

2528
:::info
2629

27-
While this documentation focuses on DeFi use cases, these mathematical utilities can be used for any application requiring high-precision decimal arithmetic beyond the native 8-decimal limitation of `UFix64`.
30+
While this documentation focuses on DeFi use cases, you can use these mathematical utilities for any application requiring high-precision decimal arithmetic beyond the native 8-decimal limitation of `UFix64`.
2831

2932
:::
3033

@@ -51,15 +54,15 @@ let output = afterFee * price // More precision lost
5154
let finalAmount = output / someRatio // Even more precision lost
5255
```
5356

54-
After 3-4 sequential operations, the cumulative rounding error can be significant, especially when dealing with large amounts. Assuming a rounding error with 8 decimals (1.234567885 rounds up to 1.23456789, causing a rounding error of 0.000000005), then after 100 operations with this error and dealing with 1 million dollars USDF, the protocol is losing $0.5 in revenue from this lack of precision. This might not seem like a lot, but if we consider the TVL of Aave, which is around 40 billion USD, then that loss results in $20,000 USD!
57+
After three-to-four sequential operations, significant cumulative rounding errors can occur, especially when dealing with large amounts. Assuming a rounding error with eight decimals (1.234567885 rounds up to 1.23456789, causing a rounding error of 0.000000005), then after 100 operations with this error and dealing with one million dollars USDF, the protocol loses $0.5 in revenue from this lack of precision. This might not seem like a lot, but if we consider the TVL of Aave, which is around 40 billion USD, then that loss results in $20,000 USD!
5558

5659
## The Solution: 24-Decimal Precision
5760

58-
[`DeFiActionsMathUtils`] solves this by using `UInt128` to represent fixed-point numbers with 24 decimal places (scaling factor of 10^24). This provides 16 additional decimal places for intermediate calculations, dramatically reducing precision loss.
61+
[`DeFiActionsMathUtils`] solves this with `UInt128` to represent fixed-point numbers with 24 decimal places (scaling factor of 10^24). This provides 16 additional decimal places for intermediate calculations, dramatically reducing precision loss.
5962

6063
:::Warning
6164

62-
Note: There is still some precision loss occurring, but it is orders of magnitud smaller than with 8 decimals.
65+
There is still some precision loss occurring, but it is much smaller than with eight decimals.
6366

6467
:::
6568

@@ -101,7 +104,7 @@ These constants ensure consistent scaling across all operations.
101104

102105
## Rounding Modes
103106

104-
Smart rounding is the strategic selection of rounding strategies based on the financial context of your calculation. After performing high-precision calculations at 24 decimals, the final results must be converted back to `UFix64` (8 decimals), and how you handle this conversion can protect your protocol from losses, ensure fairness to users, and reduce systematic bias.
107+
Smart rounding is the strategic selection of rounding strategies based on the financial context of your calculation. After performing high-precision calculations at 24 decimals, you must convert the final results back to `UFix64` (8 decimals). How you handle this conversion can protect your protocol from losses, ensure fairness to users, and reduce systematic bias.
105108

106109
[`DeFiActionsMathUtils`] provides four rounding modes, each optimized for specific financial scenarios:
107110

@@ -123,10 +126,10 @@ access(all) enum RoundingMode: UInt8 {
123126

124127
### When to Use Each Mode
125128

126-
**RoundDown** - Choose this when calculating user payouts, withdrawals, or rewards. By rounding down, your protocol retains any fractional amounts, protecting against losses from accumulated rounding errors. This is the conservative choice when funds leave your protocol.
129+
**RoundDown** - Choose this when you calculate user payouts, withdrawals, or rewards. When you round down, your protocol retains any fractional amounts, which protects against losses from accumulated rounding errors. This is the conservative choice when funds leave your protocol.
127130

128131
```cadence
129-
// When calculating how much to pay out to users
132+
// When you calculate how much to pay out to users
130133
let userReward = DeFiActionsMathUtils.toUFix64RoundDown(calculatedReward)
131134
```
132135

@@ -144,7 +147,7 @@ let protocolFee = DeFiActionsMathUtils.toUFix64RoundUp(calculatedFee)
144147
let displayValue = DeFiActionsMathUtils.toUFix64Round(calculatedValue)
145148
```
146149

147-
**RoundEven** - Select this for scenarios involving many repeated calculations where you want to minimize systematic bias. Also known as "[banker's rounding]", this mode rounds ties (exactly 0.5) to the nearest even number, which statistically balances out over many operations, making it ideal for large-scale distributions or statistical calculations.
150+
**RoundEven** - Select this for scenarios with many repeated calculations where you want to minimize systematic bias. Also known as "[banker's rounding]", this mode rounds ties (exactly 0.5) to the nearest even number, which statistically balances out over many operations, making it ideal for large-scale distributions or statistical calculations.
148151

149152
```cadence
150153
// For repeated operations where bias matters
@@ -462,7 +465,7 @@ access(all) view fun assertWithinUFix64Bounds(_ value: UInt128) {
462465

463466
## Best Practices
464467

465-
Always Use High Precision for Intermediate Calculations
468+
Always Use High Precision for Intermediate Calculations.
466469

467470
**❌ Low precision (loses ~$0.50 per 1M USDC):**
468471

@@ -512,15 +515,15 @@ access(all) fun swap(inputAmount: UFix64) {
512515

513516
## Key takeaways
514517

515-
- Use high precision (24 decimals) for all intermediate calculations
516-
- Convert to `UFix64` only for final results
517-
- Choose appropriate rounding modes based on your use case
518-
- Always validate inputs and test edge cases
519-
- Document your rounding decisions for maintainability
518+
- Use high precision (24 decimals) for all intermediate calculations.
519+
- Convert to `UFix64` only for final results.
520+
- Choose appropriate rounding modes based on your use case.
521+
- Always validate inputs and test edge cases.
522+
- Document your rounding decisions for maintainability.
520523

521524
## Conclusion
522525

523-
[`DeFiActionsMathUtils`] gives Flow developers a significant advantage in building DeFi applications. With 24-decimal precision, it is orders of magnitude more accurate than typical blockchain implementations (which use 6-18 decimals). The standardized library eliminates the need to build custom math implementations.
526+
[`DeFiActionsMathUtils`] gives Flow developers a significant advantage in building DeFi applications. With 24-decimal precision, it is much more accurate than typical blockchain implementations (which use 6-18 decimals). The standardized library eliminates the need to build custom math implementations.
524527

525528
The simple **convert → calculate → convert back** pattern, combined with strategic rounding modes and built-in overflow protection, means you can focus on your protocol's business logic instead of low-level precision handling. At scale, this protection prevents thousands of dollars in losses from accumulated rounding errors.
526529

0 commit comments

Comments
 (0)