Skip to content

Flooring seconds in compoundInterest #124

@holyfuchs

Description

@holyfuchs

compoundInterest is calculating the interest rate based on floored seconds:

/// Fast exponentiation for UFix128 with a non-negative integer exponent (seconds).
/// Uses exponentiation-by-squaring with truncation at each multiply (fixed-point semantics)
access(all) view fun powUFix128(_ base: UFix128, _ expSeconds: UFix64): UFix128 {
if expSeconds == 0.0 { return 1.0 }
if base == 1.0 { return 1.0 }
var result: UFix128 = 1.0
var b = base
var e = expSeconds
// Floor the seconds to an integer count
var remaining = UInt64(e)
while remaining > 0 {
if remaining % 2 == 1 {
result = result * b
}
b = b * b
remaining = remaining / 2
}
return result
}

access(all) view fun compoundInterestIndex(
oldIndex: UFix128,
perSecondRate: UFix128,
elapsedSeconds: UFix64
): UFix128 {
// Exponentiation by squaring on UFix128 for performance and precision
let pow = FlowCreditMarketMath.powUFix128(perSecondRate, elapsedSeconds)
return oldIndex * pow
}

timestamp: UFix64
If getCurrentBlock().timestamp has a resolution below 1 second (utilizing the UFix), interacting with the contract every block will result in no interest accruing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions