Skip to content
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
2 changes: 1 addition & 1 deletion cadence/tests/auto_borrow_behavior_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ fun testAutoBorrowBehaviorWithTargetHealth() {

// Verify position health is at target
let health = getPositionHealth(pid: 0, beFailed: false)
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, health),
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, health, DEFAULT_UFIX128_VARIANCE),
message: "Expected health to be \(INT_TARGET_HEALTH), but got \(health)")

// Verify the user actually received the borrowed MOET in their Vault (draw-down sink)
Expand Down
12 changes: 6 additions & 6 deletions cadence/tests/funds_available_above_target_health_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fun testFundsAvailableAboveTargetHealthAfterDepositingWithPushFromHealthy() {
// assert expected starting point
let balanceAfterBorrow = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedBorrowAmount = (positionFundingAmount * flowCollateralFactor * flowStartPrice) / TARGET_HEALTH
Test.assert(equalWithinVariance(expectedBorrowAmount, balanceAfterBorrow),
Test.assert(equalWithinVariance(expectedBorrowAmount, balanceAfterBorrow, DEFAULT_UFIX_VARIANCE),
message: "Expected MOET balance to be ~\(expectedBorrowAmount), but got \(balanceAfterBorrow)")

let evts = Test.eventsOfType(Type<FlowALPEvents.Opened>())
Expand All @@ -113,10 +113,10 @@ fun testFundsAvailableAboveTargetHealthAfterDepositingWithPushFromHealthy() {
}
Test.assertEqual(positionFundingAmount, flowPositionBalance!.balance)

Test.assert(equalWithinVariance(expectedBorrowAmount, moetBalance!.balance),
Test.assert(equalWithinVariance(expectedBorrowAmount, moetBalance!.balance, DEFAULT_UFIX_VARIANCE),
message: "Expected borrow amount to be \(expectedBorrowAmount), but got \(moetBalance!.balance)")

Test.assert(equalWithinVariance(INT_TARGET_HEALTH, health),
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, health, DEFAULT_UFIX128_VARIANCE),
message: "Expected health to be \(INT_TARGET_HEALTH), but got \(health)")

log("[TEST] FLOW price set to \(flowStartPrice)")
Expand Down Expand Up @@ -297,7 +297,7 @@ fun testFundsAvailableAboveTargetHealthAfterDepositingWithoutPushFromOvercollate
log("[TEST] Depositing: \(depositAmount)")
log("[TEST] Expected Available: \(expectedAvailable)")
log("[TEST] Actual Available: \(actualAvailable)")
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable),
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable, DEFAULT_UFIX_VARIANCE),
message: "Values are not equal within variance - expected: \(expectedAvailable), actual: \(actualAvailable)")

log("..............................")
Expand All @@ -315,7 +315,7 @@ fun testFundsAvailableAboveTargetHealthAfterDepositingWithoutPushFromOvercollate
log("[TEST] Depositing: \(depositAmount)")
log("[TEST] Expected Available: \(expectedAvailable)")
log("[TEST] Actual Available: \(actualAvailable)")
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable),
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable, DEFAULT_UFIX_VARIANCE),
message: "Values are not equal within variance - expected: \(expectedAvailable), actual: \(actualAvailable)")

log("==============================")
Expand Down Expand Up @@ -354,6 +354,6 @@ fun runFundsAvailableAboveTargetHealthAfterDepositing(
log("[TEST] Depositing: \(depositAmount)")
log("[TEST] Expected Available: \(expectedAvailable)")
log("[TEST] Actual Available: \(actualAvailable)")
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable),
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable, DEFAULT_UFIX_VARIANCE),
message: "Values are not equal within variance - expected: \(expectedAvailable), actual: \(actualAvailable)")
}
14 changes: 7 additions & 7 deletions cadence/tests/funds_required_for_target_health_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ fun testFundsRequiredForTargetHealthAfterWithdrawingWithPushFromHealthy() {
// assert expected starting point
startingDebt = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedStartingDebt = (positionFundingAmount * flowCollateralFactor * flowStartPrice) / TARGET_HEALTH
Test.assert(equalWithinVariance(expectedStartingDebt, startingDebt),
Test.assert(equalWithinVariance(expectedStartingDebt, startingDebt, DEFAULT_UFIX_VARIANCE),
message: "Expected MOET balance to be ~\(expectedStartingDebt), but got \(startingDebt)")

var evts = Test.eventsOfType(Type<FlowALPEvents.Opened>())
Expand All @@ -102,7 +102,7 @@ fun testFundsRequiredForTargetHealthAfterWithdrawingWithPushFromHealthy() {
Test.assertEqual(rebalancedEvt.amount, startingDebt)

let health = getPositionHealth(pid: positionID, beFailed: false)
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, health),
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, health, DEFAULT_UFIX128_VARIANCE),
message: "Expected health to be \(INT_TARGET_HEALTH), but got \(health)")

log("[TEST] FLOW price set to \(flowStartPrice)")
Expand Down Expand Up @@ -283,7 +283,7 @@ fun testFundsRequiredForTargetHealthAfterWithdrawingWithPushFromOvercollateraliz
// assert expected starting point
startingDebt = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedStartingDebt = (positionFundingAmount * flowCollateralFactor * flowStartPrice) / TARGET_HEALTH
Test.assert(equalWithinVariance(expectedStartingDebt, startingDebt),
Test.assert(equalWithinVariance(expectedStartingDebt, startingDebt, DEFAULT_UFIX_VARIANCE),
message: "Expected MOET balance to be ~\(expectedStartingDebt), but got \(startingDebt)")

var evts = Test.eventsOfType(Type<FlowALPEvents.Opened>())
Expand All @@ -298,7 +298,7 @@ fun testFundsRequiredForTargetHealthAfterWithdrawingWithPushFromOvercollateraliz
Test.assertEqual(rebalancedEvt.amount, startingDebt)

let actualHealthBeforePriceIncrease = getPositionHealth(pid: positionID, beFailed: false)
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, actualHealthBeforePriceIncrease),
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, actualHealthBeforePriceIncrease, DEFAULT_UFIX128_VARIANCE),
message: "Expected health to be \(INT_TARGET_HEALTH), but got \(actualHealthBeforePriceIncrease)")

let priceIncrease = 0.25
Expand Down Expand Up @@ -438,7 +438,7 @@ fun testFundsRequiredForTargetHealthAfterWithdrawingWithPushFromUndercollaterali
// assert expected starting point
startingDebt = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedStartingDebt = (positionFundingAmount * flowCollateralFactor * flowStartPrice) / TARGET_HEALTH
Test.assert(equalWithinVariance(expectedStartingDebt, startingDebt),
Test.assert(equalWithinVariance(expectedStartingDebt, startingDebt, DEFAULT_UFIX_VARIANCE),
message: "Expected MOET balance to be ~\(expectedStartingDebt), but got \(startingDebt)")

var evts = Test.eventsOfType(Type<FlowALPEvents.Opened>())
Expand All @@ -453,7 +453,7 @@ fun testFundsRequiredForTargetHealthAfterWithdrawingWithPushFromUndercollaterali
Test.assertEqual(rebalancedEvt.amount, startingDebt)

let actualHealthBeforePriceIncrease = getPositionHealth(pid: positionID, beFailed: false)
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, actualHealthBeforePriceIncrease),
Test.assert(equalWithinVariance(INT_TARGET_HEALTH, actualHealthBeforePriceIncrease, DEFAULT_UFIX128_VARIANCE),
message: "Expected health to be \(INT_TARGET_HEALTH), but got \(actualHealthBeforePriceIncrease)")

let priceDecrease = 0.25
Expand Down Expand Up @@ -557,6 +557,6 @@ fun runFundsRequiredForTargetHealthAfterWithdrawing(
log("[TEST] Withdrawing: \(withdrawAmount)")
log("[TEST] Expected Required: \(ufixExpectedRequired)")
log("[TEST] Actual Required: \(actualRequired)")
Test.assert(equalWithinVariance(ufixExpectedRequired, actualRequired),
Test.assert(equalWithinVariance(ufixExpectedRequired, actualRequired, DEFAULT_UFIX_VARIANCE),
message: "Expected required funds to be \(ufixExpectedRequired), but got \(actualRequired)")
}
13 changes: 2 additions & 11 deletions cadence/tests/insurance_collection_formula_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,7 @@ fun test_collectInsurance_success_fullAmount() {
// With 10% annual debit rate over 1 year: debitIncome ≈ 615.38 * (1.10517091665 - 1) ≈ 64.72
// Insurance = debitIncome * 0.1 ≈ 6.472 MOET

// NOTE:
// We intentionally do not use `equalWithinVariance` with `defaultUFixVariance` here.
// The default variance is designed for deterministic math, but insurance collection
// depends on block timestamps, which can differ slightly between test runs.
// A larger, time-aware tolerance is required.
let tolerance = 0.001
let expectedCollectedAmount = 6.472
let diff = expectedCollectedAmount > collectedAmount
? expectedCollectedAmount - collectedAmount
: collectedAmount - expectedCollectedAmount

Test.assert(diff < tolerance, message: "Insurance collected should be around \(expectedCollectedAmount) but current \(collectedAmount)")
Test.assert(equalWithinVariance(expectedCollectedAmount, collectedAmount, 0.001),
message: "Insurance collected should be around \(expectedCollectedAmount) but current \(collectedAmount)")
}
29 changes: 7 additions & 22 deletions cadence/tests/insurance_collection_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -524,16 +524,9 @@ fun test_collectInsurance_midPeriodRateChange() {
let reservesAfterPhase1 = getReserveBalance(vaultIdentifier: FLOW_TOKEN_IDENTIFIER)
let collected_phase1 = reservesBefore_phase1 - reservesAfterPhase1

// NOTE:
// We intentionally do not use `equalWithinVariance` with `defaultUFixVariance` here.
// The default variance is designed for deterministic math, but insurance collection
// depends on block timestamps, which can differ slightly between test runs.
// A larger, time-aware tolerance is required.
let tolerance = 0.00001
var diff = expectedCollectedInsuranceAmountAfterPhase1 > insuranceAfterPhase1
? expectedCollectedInsuranceAmountAfterPhase1 - insuranceAfterPhase1
: insuranceAfterPhase1 - expectedCollectedInsuranceAmountAfterPhase1
Test.assert(diff < tolerance, message: "Insurance collected should be around \(expectedCollectedInsuranceAmountAfterPhase1) but current \(insuranceAfterPhase1)")
let expectedCollectedAmount = 6.472
Test.assert(equalWithinVariance(expectedCollectedInsuranceAmountAfterPhase1, insuranceAfterPhase1, 0.00001),
message: "Insurance collected should be around \(expectedCollectedInsuranceAmountAfterPhase1) but current \(insuranceAfterPhase1)")
Test.assertEqual(collected_phase1, insuranceAfterPhase1)

let reservesBefore_phase2 = getReserveBalance(vaultIdentifier: FLOW_TOKEN_IDENTIFIER)
Expand All @@ -559,19 +552,11 @@ fun test_collectInsurance_midPeriodRateChange() {

let insuranceAfterPhase2 = getInsuranceFundBalance()
let reservesAfterPhase2 = getReserveBalance(vaultIdentifier: FLOW_TOKEN_IDENTIFIER)

// NOTE:
// We intentionally do not use `equalWithinVariance` with `defaultUFixVariance` here.
// The default variance is designed for deterministic math, but insurance collection
// depends on block timestamps, which can differ slightly between test runs.
// A larger, time-aware tolerance is required.
let expectedCollectedInsuranceAmount= expectedCollectedInsuranceAmountAfterPhase1 + expectedCollectedInsuranceAmountAfterPhase2 // 5.25854589 + 10.51709179
diff = expectedCollectedInsuranceAmount > insuranceAfterPhase2
? expectedCollectedInsuranceAmount - insuranceAfterPhase2
: insuranceAfterPhase2 - expectedCollectedInsuranceAmount

Test.assert(diff < tolerance, message: "Insurance collected should be around \(expectedCollectedInsuranceAmount) but current \(insuranceAfterPhase2)")

let expectedCollectedInsuranceAmount= expectedCollectedInsuranceAmountAfterPhase1 + expectedCollectedInsuranceAmountAfterPhase2 // 5.25854589 + 10.51709179
Test.assert(equalWithinVariance(expectedCollectedInsuranceAmount, insuranceAfterPhase2, 0.00001),
message: "Insurance collected should be around \(expectedCollectedInsuranceAmount) but current \(insuranceAfterPhase2)")

// acumulative insurance fund must equal sum of both collections
let collected_phase2 = reservesBefore_phase2 - reservesAfterPhase2
Test.assertEqual(insuranceAfterPhase2, insuranceAfterPhase1 + collected_phase2)
Expand Down
2 changes: 1 addition & 1 deletion cadence/tests/phase0_pure_math_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ fun test_maxWithdraw_increasesDebtWhenNoCredit() {
let effColl: UFix128 = 80.0
let expected = effColl / 1.3
Test.assert(
ufix128EqualWithinVariance(expected, max),
ufix128EqualWithinVariance(expected, max, DEFAULT_UFIX128_VARIANCE),
message: "maxWithdraw debt increase mismatch"
)
}
Expand Down
13 changes: 2 additions & 11 deletions cadence/tests/stability_collection_formula_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,7 @@ fun test_collectStability_success_fullAmount() {
// With 10% annual debit rate over 1 year: interestIncome ≈ 615.38 * (1.10517091665 - 1) ≈ 64.72
// Stability = interestIncome * 0.1 ≈ 6.472 MOET

// NOTE:
// We intentionally do not use `equalWithinVariance` with `defaultUFixVariance` here.
// The default variance is designed for deterministic math, but insurance collection
// depends on block timestamps, which can differ slightly between test runs.
// A larger, time-aware tolerance is required.
let tolerance = 0.001
let expectedCollectedAmount = 6.472
let diff = expectedCollectedAmount > collectedAmount
? expectedCollectedAmount - collectedAmount
: collectedAmount - expectedCollectedAmount

Test.assert(diff < tolerance, message: "Stability collected should be around \(expectedCollectedAmount) but current \(collectedAmount)")
Test.assert(equalWithinVariance(expectedCollectedAmount, collectedAmount, 0.001),
message: "Stability collected should be around \(expectedCollectedAmount) but current \(collectedAmount)")
}
24 changes: 7 additions & 17 deletions cadence/tests/stability_collection_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -376,17 +376,9 @@ fun test_collectStability_midPeriodRateChange() {
let reservesAfterPhase1 = getReserveBalance(vaultIdentifier: FLOW_TOKEN_IDENTIFIER)
let collected_phase1 = reservesBefore_phase1 - reservesAfterPhase1

// NOTE:
// We intentionally do not use `equalWithinVariance` with `defaultUFixVariance` here.
// The default variance is designed for deterministic math, but stability collection
// depends on block timestamps, which can differ slightly between test runs.
// A larger, time-aware tolerance is required.
let tolerance = 0.00001
var diff = expectedStabilityAmountAfterPhase1 > stabilityAfterPhase1
? expectedStabilityAmountAfterPhase1 - stabilityAfterPhase1
: stabilityAfterPhase1 - expectedStabilityAmountAfterPhase1
Test.assert(diff < tolerance, message: "Stability collected should be around \(expectedStabilityAmountAfterPhase1) but current \(stabilityAfterPhase1)")

Test.assert(equalWithinVariance(expectedStabilityAmountAfterPhase1, stabilityAfterPhase1, 0.00001),
message: "Stability collected should be around \(expectedStabilityAmountAfterPhase1) but current \(stabilityAfterPhase1)")

// stability fund balance must equal what was withdrawn from reserves
// (no swap needed — stability is collected in the same token as the reserve)
Test.assertEqual(collected_phase1, stabilityAfterPhase1)
Expand All @@ -413,12 +405,10 @@ fun test_collectStability_midPeriodRateChange() {
let reservesAfterPhase2 = getReserveBalance(vaultIdentifier: FLOW_TOKEN_IDENTIFIER)

let expectedStabilityTotal = expectedStabilityAmountAfterPhase1 + expectedStabilityAmountAfterPhase2 // 2.62927294 + 10.51709179
diff = expectedStabilityTotal > stabilityAfterPhase2
? expectedStabilityTotal - stabilityAfterPhase2
: stabilityAfterPhase2 - expectedStabilityTotal
Test.assert(diff < tolerance, message: "Stability collected should be around \(expectedStabilityTotal) but current \(stabilityAfterPhase2)")

// acumulative stability fund must equal sum of both collections
Test.assert(equalWithinVariance(expectedStabilityTotal, stabilityAfterPhase2, 0.00001),
message: "Stability collected should be around \(expectedStabilityTotal) but current \(stabilityAfterPhase2)")

// cumulative stability fund must equal sum of both collections
let collected_phase2 = reservesBefore_phase2 - reservesAfterPhase2
Test.assertEqual(stabilityAfterPhase2, stabilityAfterPhase1 + collected_phase2)
Test.assert(collected_phase2 > collected_phase1, message: "Phase 2 collection should exceed phase 1 due to higher rate")
Expand Down
19 changes: 10 additions & 9 deletions cadence/tests/test_helpers.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -881,28 +881,29 @@ fun withdrawReserve(

/* --- Assertion Helpers --- */

access(all) fun equalWithinVariance(_ expected: AnyStruct, _ actual: AnyStruct): Bool {
access(all) fun equalWithinVariance(_ expected: AnyStruct, _ actual: AnyStruct, _ variance: AnyStruct): Bool {
let expectedType = expected.getType()
let actualType = actual.getType()
if expectedType == Type<UFix64>() && actualType == Type<UFix64>() {
return ufixEqualWithinVariance(expected as! UFix64, actual as! UFix64)
} else if expectedType == Type<UFix128>() && actualType == Type<UFix128>() {
return ufix128EqualWithinVariance(expected as! UFix128, actual as! UFix128)
let varianceType = actual.getType()
if expectedType == Type<UFix64>() && actualType == Type<UFix64>() && varianceType == Type<UFix64>() {
return ufixEqualWithinVariance(expected as! UFix64, actual as! UFix64, variance as! UFix64)
} else if expectedType == Type<UFix128>() && actualType == Type<UFix128>() && varianceType == Type<UFix128>(){
return ufix128EqualWithinVariance(expected as! UFix128, actual as! UFix128, variance as! UFix128)
}
panic("Expected and actual types do not match - expected: \(expectedType.identifier), actual: \(actualType.identifier)")
}

access(all) fun ufixEqualWithinVariance(_ expected: UFix64, _ actual: UFix64): Bool {
access(all) fun ufixEqualWithinVariance(_ expected: UFix64, _ actual: UFix64, _ variance: UFix64): Bool {
// return true if expected is within DEFAULT_UFIX_VARIANCE of actual, false otherwise and protect for underflow`
let diff = Fix64(expected) - Fix64(actual)
// take the absolute value of the difference without relying on .abs()
let absDiff: UFix64 = diff < 0.0 ? UFix64(-1.0 * diff) : UFix64(diff)
return absDiff <= DEFAULT_UFIX_VARIANCE
return absDiff <= variance
}

access(all) fun ufix128EqualWithinVariance(_ expected: UFix128, _ actual: UFix128): Bool {
access(all) fun ufix128EqualWithinVariance(_ expected: UFix128, _ actual: UFix128, _ variance: UFix128): Bool {
let absDiff: UFix128 = expected >= actual ? expected - actual : actual - expected
return absDiff <= DEFAULT_UFIX128_VARIANCE
return absDiff <= variance
}

/* --- Balance & Timestamp Helpers --- */
Expand Down