diff --git a/AGENTS.md b/AGENTS.md index 3d845b48..8e8d87d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,7 +166,7 @@ contracts. The addresses emitted by the deploy script are authoritative. preconditions are the first lines a reader sees. - **Doc comments.** Every public entrypoint has one, in OpenZeppelin's style: a one-line summary, then `# Arguments` with units (asset base units, share base - units, WAD prices, seconds or ledgers), `# Errors`, `# Events` and + units, 14-decimal prices, seconds or ledgers), `# Errors`, `# Events` and `# Authorization`. Every error variant's doc says when it happens. Keep them short: they are stored in the Wasm as part of the contract spec, which keeps 1,024 bytes of each doc and drops the rest without a warning. diff --git a/app-lib/format.test.ts b/app-lib/format.test.ts index 054cd797..8273ae74 100644 --- a/app-lib/format.test.ts +++ b/app-lib/format.test.ts @@ -151,12 +151,12 @@ describe("formatExact", () => { describe("formatExact with a minimum fraction width", () => { it("pads a short price to the minimum", () => { - const value = 11n * 10n ** 17n + const value = 11n * 10n ** 13n expect(formatExact(value as Price, PRICE_DECIMALS, 4)).toBe("1.1000") }) it("keeps every significant digit beyond the minimum", () => { - const value = 1_041_234_560_000_000_000n + const value = 104_123_456_000_000n expect(formatExact(value as Price, PRICE_DECIMALS, 4)).toBe("1.04123456") }) }) @@ -226,7 +226,7 @@ describe("formatDayMonth", () => { }) it("rejects a Price formatted with AMOUNT_DECIMALS at compile time", () => { - const price = 1_000000000000000000n as Price + const price = 1_00000000000000n as Price // @ts-expect-error a Price must be formatted with PRICE_DECIMALS, not AMOUNT_DECIMALS expect(typeof formatUnits(price, AMOUNT_DECIMALS)).toBe("string") }) diff --git a/app-lib/format.ts b/app-lib/format.ts index 1522c824..999a52f0 100644 --- a/app-lib/format.ts +++ b/app-lib/format.ts @@ -81,7 +81,9 @@ export function networkStatus( } export const AMOUNT_DECIMALS = 7 as const -export const PRICE_DECIMALS = 18 as const +export const PRICE_DECIMALS = 14 as const +/** A share price of one asset base unit per share base unit. */ +export const PRICE_SCALE = 10n ** BigInt(PRICE_DECIMALS) export type Decimals = typeof AMOUNT_DECIMALS | typeof PRICE_DECIMALS declare const scale: unique symbol @@ -89,7 +91,7 @@ declare const scale: unique symbol export type Scaled = bigint & { readonly [scale]: D } /** Asset units and share counts, scaled by `AMOUNT_DECIMALS`. */ export type Amount = Scaled -/** WAD share price, scaled by `PRICE_DECIMALS`. */ +/** Share price, scaled by `PRICE_DECIMALS`. */ export type Price = Scaled /** diff --git a/app/src/components/admin/ConfigurationSection.test.tsx b/app/src/components/admin/ConfigurationSection.test.tsx index b9c98f4c..accc1ae7 100644 --- a/app/src/components/admin/ConfigurationSection.test.tsx +++ b/app/src/components/admin/ConfigurationSection.test.tsx @@ -1,3 +1,4 @@ +import { PRICE_SCALE } from "@stellar-scaffold/app-lib" import { act, fireEvent, render, screen, within } from "@testing-library/react" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { type Grant } from "../../hooks/useAdminAuthority" @@ -75,7 +76,6 @@ const CUSTODIAN = "CACAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAINCW" const COMPLIANCE = "CACQKBIFAUCQKBIFAUCQKBIFAUCQKBIFAUCQKBIFAUCQKBIFAUCQLC2U" const VERIFIER = "CADAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMSST" const DAY = 86_400n -const PRICE_ONE = 10n ** 18n const grantOf = (role: string): Grant => ({ role, @@ -103,8 +103,8 @@ const READY: ConfigurationState = { cooldown: 3_600n, maxUpBps: 1_000, maxDownBps: 500, - min: PRICE_ONE / 2n, - max: 2n * PRICE_ONE, + min: PRICE_SCALE / 2n, + max: 2n * PRICE_SCALE, }, compliance: COMPLIANCE, identityVerifier: VERIFIER, @@ -370,8 +370,8 @@ describe("ConfigurationSection", () => { cooldown_secs: 3_600n, max_up_bps: 500, max_down_bps: 500, - min_answer: PRICE_ONE / 2n, - max_answer: 2n * PRICE_ONE, + min_answer: PRICE_SCALE / 2n, + max_answer: 2n * PRICE_SCALE, }, oracleAdmin, ) diff --git a/app/src/components/admin/CycleSection.test.tsx b/app/src/components/admin/CycleSection.test.tsx index 20c1e10e..1636fa3e 100644 --- a/app/src/components/admin/CycleSection.test.tsx +++ b/app/src/components/admin/CycleSection.test.tsx @@ -1,4 +1,4 @@ -import { type Amount, type Price } from "@stellar-scaffold/app-lib" +import { type Amount, type Price, PRICE_SCALE } from "@stellar-scaffold/app-lib" import { act, fireEvent, render, screen, within } from "@testing-library/react" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { type ActivateWindDownStatus } from "../../hooks/useActivateWindDown" @@ -108,7 +108,7 @@ vi.mock("../../hooks/useDepositBalance", () => ({ })) const amount = (whole: bigint) => (whole * 10_000_000n) as Amount -const price = (whole: bigint) => (whole * 10n ** 18n) as Price +const price = (whole: bigint) => (whole * PRICE_SCALE) as Price const sealed: EpochRecord = { id: 4n, @@ -540,7 +540,7 @@ describe("CycleSection", () => { expect(attestMock.submit).toHaveBeenCalledWith( { - price: 1_040_000_000_000_000_000n, + price: 104_000_000_000_000n, freshness: 86_400n, proofHash: PROOF_HASH, proofUri: "https://example.com/nav.pdf", diff --git a/app/src/components/vault/transactionCopy/cycle.test.tsx b/app/src/components/vault/transactionCopy/cycle.test.tsx index 0c94a0bb..48c8f9de 100644 --- a/app/src/components/vault/transactionCopy/cycle.test.tsx +++ b/app/src/components/vault/transactionCopy/cycle.test.tsx @@ -179,7 +179,7 @@ describe("TransactionModal, pricing an epoch", () => { it("shows the share price the vault settled at once confirmed, to four places", () => { renderFulfillEpochModal({ status: "confirmed", - sharePrice: 1_250_000_000_000_000_000n as Price, + sharePrice: 125_000_000_000_000n as Price, hash: "b".repeat(64), }) diff --git a/app/src/hooks/useAttest.test.ts b/app/src/hooks/useAttest.test.ts index 4bdef0ab..a9c30372 100644 --- a/app/src/hooks/useAttest.test.ts +++ b/app/src/hooks/useAttest.test.ts @@ -30,7 +30,7 @@ vi.mock("../config/clients", () => ({ })) const attestation = { - price: 1_040_000_000_000_000_000n as Price, + price: 104_000_000_000_000n as Price, freshness: 86_400n, proofHash: "ab".repeat(32), proofUri: "https://example.com/nav.pdf", diff --git a/app/src/hooks/useCycleState.test.ts b/app/src/hooks/useCycleState.test.ts index ca0dfdcf..cbfb4d35 100644 --- a/app/src/hooks/useCycleState.test.ts +++ b/app/src/hooks/useCycleState.test.ts @@ -7,6 +7,7 @@ import { type NavReport, type OracleState, type Price, + PRICE_SCALE, } from "@stellar-scaffold/app-lib" import { waitFor } from "@testing-library/react" import { beforeEach, describe, expect, it, vi } from "vitest" @@ -76,7 +77,7 @@ const unreadable = { kind: "unreadable" } as const const report: NavReport = { expires_at: 1_700_136_000n, - nav_per_share: 10n ** 18n, + nav_per_share: PRICE_SCALE, accepted_at: 1_700_050_000n, proof_hash: Buffer.alloc(32, 0xab), proof_uri: "https://example.com/nav.pdf", @@ -87,8 +88,8 @@ const config = { cooldown_secs: 3_600n, max_up_bps: 500, max_down_bps: 500, - min_answer: 5n * 10n ** 17n, - max_answer: 2n * 10n ** 18n, + min_answer: PRICE_SCALE / 2n, + max_answer: 2n * PRICE_SCALE, } const state = (tag: OracleState["tag"]): ContractRead => @@ -98,7 +99,7 @@ describe("toOracle", () => { it("carries the report, the limits and no NAV pause while the price is valid", () => { expect(toOracle(state("Valid"), value(report), value(config))).toEqual({ state: "valid", - price: (10n ** 18n) as Price, + price: PRICE_SCALE as Price, attestedAt: 1_700_050_000n, expiresAt: 1_700_136_000n, proof: { hash: "ab".repeat(32), uri: "https://example.com/nav.pdf" }, @@ -109,8 +110,8 @@ describe("toOracle", () => { cooldown: 3_600n, maxUpBps: 500, maxDownBps: 500, - min: 5n * 10n ** 17n, - max: 2n * 10n ** 18n, + min: PRICE_SCALE / 2n, + max: 2n * PRICE_SCALE, }, }) }) diff --git a/app/src/hooks/useEpochHistory.test.ts b/app/src/hooks/useEpochHistory.test.ts index b153d825..c392e7cd 100644 --- a/app/src/hooks/useEpochHistory.test.ts +++ b/app/src/hooks/useEpochHistory.test.ts @@ -27,7 +27,7 @@ const fulfilled: EpochInfo = { status: { tag: "Fulfilled", values: undefined }, total_deposited: 200_0000000n, total_shares_redeeming: 20_0000000n, - share_price: 1_500_000_000_000_000_000n, + share_price: 150_000_000_000_000n, closed_at: 1_700_000_000n, priceable_at: 1_700_003_600n, } @@ -106,7 +106,7 @@ describe("fetchEpochHistory", () => { status: "Fulfilled", totalDeposited: 200_0000000n, totalSharesRedeeming: 20_0000000n, - sharePrice: 1_500_000_000_000_000_000n as Price, + sharePrice: 150_000_000_000_000n as Price, closedAt: 1_700_000_000n, priceableAt: 1_700_003_600n, }, diff --git a/app/src/hooks/useFulfillEpoch.test.ts b/app/src/hooks/useFulfillEpoch.test.ts index 4043fb8f..c0a44149 100644 --- a/app/src/hooks/useFulfillEpoch.test.ts +++ b/app/src/hooks/useFulfillEpoch.test.ts @@ -17,7 +17,7 @@ vi.mock("../config/clients", () => ({ })) const epochId = 4n -const sharePrice = 1_250_000_000_000_000_000n +const sharePrice = 125_000_000_000_000n const renderFulfillEpoch = () => renderWithWallet(useFulfillEpoch) diff --git a/app/src/hooks/useInvestorRequests.test.ts b/app/src/hooks/useInvestorRequests.test.ts index 79adcb69..72fa8421 100644 --- a/app/src/hooks/useInvestorRequests.test.ts +++ b/app/src/hooks/useInvestorRequests.test.ts @@ -67,7 +67,7 @@ const fulfilledEpoch: EpochInfo = { status: { tag: "Fulfilled", values: undefined }, total_deposited: 200_0000000n, total_shares_redeeming: 20_0000000n, - share_price: 1_500_000_000_000_000_000n, + share_price: 150_000_000_000_000n, closed_at: 1_700_000_000n, priceable_at: 1_700_003_600n, } diff --git a/app/src/hooks/useNavPrice.test.ts b/app/src/hooks/useNavPrice.test.ts index 3d5f55c6..6036fb17 100644 --- a/app/src/hooks/useNavPrice.test.ts +++ b/app/src/hooks/useNavPrice.test.ts @@ -31,7 +31,7 @@ const paused: ContractRead = { const unreadableState: ContractRead = { kind: "unreadable" } const report: NavReport = { - nav_per_share: 1500000000000000000n, + nav_per_share: 150000000000000n, expires_at: 1800000000n, accepted_at: 1757900000n, proof_hash: Buffer.alloc(32, 0xab), diff --git a/app/src/pages/VaultPreview.test.tsx b/app/src/pages/VaultPreview.test.tsx index ff0ae46a..09723ce3 100644 --- a/app/src/pages/VaultPreview.test.tsx +++ b/app/src/pages/VaultPreview.test.tsx @@ -6,6 +6,7 @@ import { networkPassphrase, PRICE_DECIMALS, type Price, + PRICE_SCALE, shortAddress, } from "@stellar-scaffold/app-lib" import type * as AppLib from "@stellar-scaffold/app-lib" @@ -73,7 +74,7 @@ const { 1n, { status: { tag: "Fulfilled" }, - share_price: 1_000000000000000000n, + share_price: 1_00000000000000n, priceable_at: 1_700_003_600n, }, ], @@ -195,8 +196,6 @@ const defaultCancelRedeemImpl = async ({ } } -const WAD_SCALE = 1_000000000000000000n - const defaultClaimDepositImpl = async ({ epoch_id, }: { @@ -207,7 +206,7 @@ const defaultClaimDepositImpl = async ({ const sharePrice = mockRequests.epochs.get(epoch_id)?.share_price ?? 0n const shares = request !== undefined && sharePrice > 0n - ? (request.amount * WAD_SCALE) / sharePrice + ? (request.amount * PRICE_SCALE) / sharePrice : 0n return { simulation: undefined, @@ -235,7 +234,7 @@ const defaultClaimRedeemImpl = async ({ const request = mockRequests.redeems.get(epoch_id) const sharePrice = mockRequests.epochs.get(epoch_id)?.share_price ?? 0n const assets = - request !== undefined ? (request.shares * sharePrice) / WAD_SCALE : 0n + request !== undefined ? (request.shares * sharePrice) / PRICE_SCALE : 0n return { simulation: undefined, signAndSend: async ({ @@ -320,7 +319,7 @@ afterEach(() => { resetMockRequests() }) -const price = 1500000000000000000n as Price +const price = 150000000000000n as Price const attestedAt = 1757900000n vi.mock("../config/contracts", () => { @@ -376,7 +375,7 @@ vi.mock("../config/clients", () => { state: async () => ({ result: { tag: "Valid", values: undefined } }), latest: async () => ({ result: { - nav_per_share: 1500000000000000000n, + nav_per_share: 150000000000000n, expires_at: 1800000000n, accepted_at: 1757900000n, proof_hash: Buffer.alloc(32, 0xab), @@ -1488,7 +1487,7 @@ describe("VaultPreview", () => { mockRequests.currentEpoch = readyDepositEpoch mockRequests.epochs.set(readyDepositEpoch, { status: { tag: "Fulfilled" }, - share_price: 1_000000000000000000n, + share_price: 1_00000000000000n, priceable_at: 1_700_003_600n, }) mockRequests.deposits.set(readyDepositEpoch, { @@ -1594,7 +1593,7 @@ describe("VaultPreview", () => { mockRequests.currentEpoch = 4n mockRequests.epochs.set(4n, { status: { tag: "Fulfilled" }, - share_price: 1_000000000000000000n, + share_price: 1_00000000000000n, priceable_at: 1_700_003_600n, }) mockRequests.deposits.set(4n, { amount: 150_0000000n, claimed: false }) @@ -1718,7 +1717,7 @@ describe("VaultPreview", () => { mockRequests.currentEpoch = readyRedeemEpoch mockRequests.epochs.set(readyRedeemEpoch, { status: { tag: "Fulfilled" }, - share_price: 1_000000000000000000n, + share_price: 1_00000000000000n, priceable_at: 1_700_003_600n, }) mockRequests.redeems.set(readyRedeemEpoch, { @@ -1764,7 +1763,7 @@ describe("VaultPreview", () => { mockRequests.currentEpoch = epoch mockRequests.epochs.set(epoch, { status: { tag: "Fulfilled" }, - share_price: 1_000000000000000000n, + share_price: 1_00000000000000n, priceable_at: 1_700_003_600n, }) mockRequests.redeems.set(epoch, { shares: 952380952n, claimed: false }) diff --git a/app/src/pages/configuration.test.ts b/app/src/pages/configuration.test.ts index b1b7dd72..c0c6027c 100644 --- a/app/src/pages/configuration.test.ts +++ b/app/src/pages/configuration.test.ts @@ -1,4 +1,4 @@ -import { type Amount } from "@stellar-scaffold/app-lib" +import { type Amount, PRICE_SCALE } from "@stellar-scaffold/app-lib" import { describe, expect, it } from "vitest" import { type Grant } from "../hooks/useAdminAuthority" import { type ConfigurationState } from "../hooks/useConfigurationState" @@ -16,7 +16,6 @@ const CUSTODIAN = "CACAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAINCW" const COMPLIANCE = "CACQKBIFAUCQKBIFAUCQKBIFAUCQKBIFAUCQKBIFAUCQKBIFAUCQLC2U" const VERIFIER = "CADAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMBQGAYDAMSST" const DAY = 86_400n -const PRICE_ONE = 10n ** 18n const grantOf = (role: string, overrides: Partial = {}): Grant => ({ role, @@ -47,8 +46,8 @@ const ready = ( cooldown: 3_600n, maxUpBps: 1_000, maxDownBps: 500, - min: PRICE_ONE / 2n, - max: 2n * PRICE_ONE, + min: PRICE_SCALE / 2n, + max: 2n * PRICE_SCALE, }, compliance: COMPLIANCE, identityVerifier: VERIFIER, @@ -639,8 +638,8 @@ describe("toConfigurationActions", () => { cooldown_secs: 3_600n, max_up_bps: 500, max_down_bps: 500, - min_answer: PRICE_ONE / 2n, - max_answer: 2n * PRICE_ONE, + min_answer: PRICE_SCALE / 2n, + max_answer: 2n * PRICE_SCALE, }) }) diff --git a/app/src/pages/cycle.test.ts b/app/src/pages/cycle.test.ts index 5d55f12e..80bcd2a5 100644 --- a/app/src/pages/cycle.test.ts +++ b/app/src/pages/cycle.test.ts @@ -2,6 +2,7 @@ import { type Amount, type ChainEvent, type Price, + PRICE_SCALE, } from "@stellar-scaffold/app-lib" import { describe, expect, it } from "vitest" import { @@ -43,7 +44,7 @@ const activityOf = (events: ChainEvent[]) => const NOW = 1_700_100_000n const amount = (whole: bigint) => (whole * 10_000_000n) as Amount -const price = (whole: bigint) => (whole * 10n ** 18n) as Price +const price = (whole: bigint) => (whole * PRICE_SCALE) as Price const sealed: EpochRecord = { id: 4n, @@ -1102,7 +1103,7 @@ describe("toCycleActions, attesting", () => { expect(attest?.fields?.[0]?.invalid).toBe(false) }) - it.each(["abc", "1.2.3", "1.0000000000000000001"])( + it.each(["abc", "1.2.3", "1.000000000000001"])( "marks %j as invalid and keeps the conditions open", (input) => { const attest = attestOf(input) @@ -1122,7 +1123,7 @@ describe("toCycleActions, attesting", () => { "Within the allowed move": true, ...proofConditions, }) - expect(attest?.price).toBe(1_040_000_000_000_000_000n) + expect(attest?.price).toBe(104_000_000_000_000n) expect(attest?.freshness).toBe(86_400n) expect(attest?.outcome).toBe( "Records 1.0400 as the share price, valid for 1d.", @@ -1185,14 +1186,14 @@ describe("toCycleActions, attesting", () => { it("caps a rise at the largest allowed, letting an equal move through", () => { expect(conditionsOf(attestOf("1.05"))["Within the allowed move"]).toBe(true) expect( - conditionsOf(attestOf("1.050000000000000001"))["Within the allowed move"], + conditionsOf(attestOf("1.05000000000001"))["Within the allowed move"], ).toBe(false) }) it("caps a fall at the largest allowed, letting an equal move through", () => { expect(conditionsOf(attestOf("0.9"))["Within the allowed move"]).toBe(true) expect( - conditionsOf(attestOf("0.899999999999999999"))["Within the allowed move"], + conditionsOf(attestOf("0.89999999999999"))["Within the allowed move"], ).toBe(false) }) diff --git a/app/src/pages/governance.test.ts b/app/src/pages/governance.test.ts index 38494ff8..97d05c91 100644 --- a/app/src/pages/governance.test.ts +++ b/app/src/pages/governance.test.ts @@ -1212,8 +1212,8 @@ describe("oracle timelock", () => { cooldown_secs: 3_600n, max_up_bps: 1_000, max_down_bps: 500, - min_answer: 900_000_000_000_000_000n, - max_answer: 1_100_000_000_000_000_000n, + min_answer: 90_000_000_000_000n, + max_answer: 110_000_000_000_000n, }, ], }, diff --git a/app/src/pages/pendingChanges.test.ts b/app/src/pages/pendingChanges.test.ts index ee086b23..50a0eb08 100644 --- a/app/src/pages/pendingChanges.test.ts +++ b/app/src/pages/pendingChanges.test.ts @@ -69,8 +69,8 @@ describe("describeChange", () => { cooldown_secs: 3_600n, max_up_bps: 1_000, max_down_bps: 250, - min_answer: 500_000_000_000_000_000n, - max_answer: 2_000_000_000_000_000_000n, + min_answer: 50_000_000_000_000n, + max_answer: 200_000_000_000_000n, }, ], }, diff --git a/app/src/pages/sign.test.ts b/app/src/pages/sign.test.ts index 4fdac756..6db97cd8 100644 --- a/app/src/pages/sign.test.ts +++ b/app/src/pages/sign.test.ts @@ -144,8 +144,8 @@ describe("describePending", () => { cooldown_secs: 3_600n, max_up_bps: 500, max_down_bps: 250, - min_answer: 500_000_000_000_000_000n, - max_answer: 2_000_000_000_000_000_000n, + min_answer: 50_000_000_000_000n, + max_answer: 200_000_000_000_000n, }, account, ]), @@ -167,7 +167,7 @@ describe("describePending", () => { describePending( pending(addresses.oracle, "attest", [ { - nav_per_share: 1_050_000_000_000_000_000n, + nav_per_share: 105_000_000_000_000n, expires_at: 1_800_000_000n, proof_hash: Buffer.alloc(32, 0xab), proof_uri: "https://example.com/nav.pdf", @@ -193,7 +193,7 @@ describe("describePending", () => { const { args } = describePending( pending(addresses.oracle, "attest", [ { - nav_per_share: 1_050_000_000_000_000_000n, + nav_per_share: 105_000_000_000_000n, expires_at: 1_800_000_000n, proof_hash: Buffer.alloc(32, 0xab), proof_uri: "", @@ -500,8 +500,8 @@ describe("describePending", () => { cooldown_secs: 3_600n, max_up_bps: 500, max_down_bps: 250, - min_answer: 500_000_000_000_000_000n, - max_answer: 2_000_000_000_000_000_000n, + min_answer: 50_000_000_000_000n, + max_answer: 200_000_000_000_000n, }, ], "propose-oracle-config", @@ -906,7 +906,7 @@ describe("toModalProps", () => { const description = describePending( pending(addresses.oracle, "attest", [ { - nav_per_share: 1_050_000_000_000_000_000n, + nav_per_share: 105_000_000_000_000n, expires_at: 1_800_000_000n, proof_hash: Buffer.alloc(32, 0xab), proof_uri: "", diff --git a/app/src/pages/vaultMetrics.test.ts b/app/src/pages/vaultMetrics.test.ts index cbf6cc4c..4b6d1f19 100644 --- a/app/src/pages/vaultMetrics.test.ts +++ b/app/src/pages/vaultMetrics.test.ts @@ -160,7 +160,7 @@ describe("toAuthorityRows", () => { describe("toPriceMetric", () => { const attestedAt = BigInt(Date.UTC(2026, 8, 16) / 1000) const expiresAt = BigInt(Date.UTC(2026, 8, 20) / 1000) - const price = 1500000000000000000n as Price + const price = 150000000000000n as Price it("renders the attested price and attestation date when valid", () => { const nav: NavClassification = { status: "valid", price, attestedAt } diff --git a/app/src/pages/vaultRequests.test.ts b/app/src/pages/vaultRequests.test.ts index aa20e63a..5c1c64c8 100644 --- a/app/src/pages/vaultRequests.test.ts +++ b/app/src/pages/vaultRequests.test.ts @@ -35,7 +35,7 @@ const deposit: InvestorRequest = { epochId: 1n, side: "deposit", epochStatus: fulfilled, - sharePrice: price(2_000_000_000_000_000_000n), + sharePrice: price(200_000_000_000_000n), amount: amount(100_0000000n), claimed: false, priceableAt: 1_700_003_600n, @@ -46,7 +46,7 @@ const redeem: InvestorRequest = { epochId: 2n, side: "redeem", epochStatus: fulfilled, - sharePrice: price(2_000_000_000_000_000_000n), + sharePrice: price(200_000_000_000_000n), amount: amount(100_0000000n), claimed: false, priceableAt: 1_700_003_600n, @@ -86,7 +86,7 @@ describe("assignStage", () => { const validNav = (attestedAt: bigint): NavClassification => ({ status: "valid", - price: price(1_000_000_000_000_000_000n), + price: price(100_000_000_000_000n), attestedAt, }) @@ -332,7 +332,7 @@ describe("toRequestEntriesByStage", () => { epochId: 3n, side: "deposit", epochStatus: fulfilled, - sharePrice: price(2_000_000_000_000_000_000n), + sharePrice: price(200_000_000_000_000n), } const result = toRequestEntriesByStage( { requests: [], archived: [archived], unreadable: [] }, @@ -362,7 +362,7 @@ describe("toRequestEntriesByStage", () => { const uneven: InvestorRequest = { ...deposit, amount: amount(10000199999n), - sharePrice: price(2_100000000000000000n), + sharePrice: price(2_10000000000000n), } const result = toRequestEntriesByStage( { requests: [uneven], archived: [], unreadable: [] }, diff --git a/app/src/pages/vaultRequests.ts b/app/src/pages/vaultRequests.ts index 21d866b9..ca310de2 100644 --- a/app/src/pages/vaultRequests.ts +++ b/app/src/pages/vaultRequests.ts @@ -4,6 +4,7 @@ import { formatDayMonth, formatExact, type Price, + PRICE_SCALE, } from "@stellar-scaffold/app-lib" import { type RequestAction, @@ -55,8 +56,6 @@ export type LoadedRequests = { export type EntriesByStage = Record -const WAD = 10n ** 18n - const stageTone: Record = { waiting: "pending", ready: "claimable", @@ -80,8 +79,8 @@ export const owedAmount = ( price: Price, ): Amount => (side === "deposit" - ? (amount * WAD) / price - : (amount * price) / WAD) as Amount + ? (amount * PRICE_SCALE) / price + : (amount * price) / PRICE_SCALE) as Amount const hasValidPrice = (price: Price): boolean => price > 0n diff --git a/contracts/async-vault/src/lib.rs b/contracts/async-vault/src/lib.rs index 20168eb3..49b4e75b 100644 --- a/contracts/async-vault/src/lib.rs +++ b/contracts/async-vault/src/lib.rs @@ -768,7 +768,8 @@ impl AsyncVault { } /// An epoch: its status, deposits in asset base units, redemptions in share - /// base units, price in WAD, and close and pricing times in seconds. + /// base units, price at 14 decimals, and close and pricing times in + /// seconds. /// /// # Arguments /// @@ -1047,9 +1048,9 @@ impl AsyncVault { } /// Prices a sealed epoch at the feed's standing report and returns the - /// share price in WAD: asset base units per share base unit. Open to - /// anyone once the notice has run and a report accepted after the close - /// is valid. + /// share price at 14 decimals: asset base units per share base unit. + /// Open to anyone once the notice has run and a report accepted after the + /// close is valid. /// /// # Arguments /// diff --git a/contracts/async-vault/src/pricing.rs b/contracts/async-vault/src/pricing.rs index d5ca6107..eec202d4 100644 --- a/contracts/async-vault/src/pricing.rs +++ b/contracts/async-vault/src/pricing.rs @@ -1,6 +1,6 @@ use soroban_sdk::Env; -use stellar_contract_utils::math::{i128_fixed_point::checked_mul_div_floor, wad::WAD_SCALE}; -use strata_bindings::OracleFeedClient; +use stellar_contract_utils::math::i128_fixed_point::checked_mul_div_floor; +use strata_bindings::{OracleFeedClient, PRICE_SCALE}; use crate::error::VaultError; use crate::keys::DataKey; @@ -9,9 +9,9 @@ use crate::state; /// Defines the pricing interface for epoch share price resolution and conversions. /// A deployment or vault variant selects or implements a scheme conforming to this trait. pub trait PricingScheme { - /// Resolves the share price an epoch would take now, in WAD scale (18 - /// decimals), or a VaultError if invalid. Cancellation calls it too, to - /// decide whether a price is readable, so it must not write state. + /// Resolves the share price an epoch would take now, at `PRICE_DECIMALS`, + /// or a VaultError if invalid. Cancellation calls it too, to decide + /// whether a price is readable, so it must not write state. fn resolve_share_price(e: &Env) -> Result; /// Converts asset amount to share amount at `share_price`, rounding down @@ -20,7 +20,7 @@ pub trait PricingScheme { if share_price <= 0 { return Err(VaultError::InvalidSharePrice); } - checked_mul_div_floor(e, &assets, &WAD_SCALE, &share_price) + checked_mul_div_floor(e, &assets, &PRICE_SCALE, &share_price) .ok_or(VaultError::AmountTooLarge) } @@ -30,7 +30,7 @@ pub trait PricingScheme { if share_price <= 0 { return Err(VaultError::InvalidSharePrice); } - checked_mul_div_floor(e, &shares, &share_price, &WAD_SCALE) + checked_mul_div_floor(e, &shares, &share_price, &PRICE_SCALE) .ok_or(VaultError::AmountTooLarge) } } diff --git a/contracts/async-vault/src/state.rs b/contracts/async-vault/src/state.rs index c137978c..2d6684e3 100644 --- a/contracts/async-vault/src/state.rs +++ b/contracts/async-vault/src/state.rs @@ -28,7 +28,7 @@ pub struct EpochInfo { pub status: EpochStatus, pub total_deposited: i128, pub total_shares_redeeming: i128, - /// Assets per share, WAD-scaled: 1.0 is `WAD_SCALE`. + /// Assets per share at 14 decimals: 1.0 is `PRICE_SCALE`. pub share_price: i128, /// Ledger time the epoch closed. Zero while it is open. pub closed_at: u64, diff --git a/contracts/async-vault/src/test/cancel.rs b/contracts/async-vault/src/test/cancel.rs index 0328c782..8fdfe93d 100644 --- a/contracts/async-vault/src/test/cancel.rs +++ b/contracts/async-vault/src/test/cancel.rs @@ -58,7 +58,7 @@ fn a_priced_epoch_is_not_cancellable() { let epoch = f.vault.request_deposit(&inv, &400); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); refused( @@ -73,7 +73,7 @@ fn cancelling_without_a_request_finds_no_request_once_a_price_is_known() { let stranger = Address::generate(&f.e); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); refused( f.vault.try_cancel_deposit(&stranger, &epoch), VaultError::RequestNotFound, @@ -158,7 +158,7 @@ fn pricing_an_epoch_makes_its_deposits_deployable() { let epoch = f.vault.request_deposit(&inv, &400); let before = f.vault.free_reserve(); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); assert_eq!(f.vault.cancellable_escrow(), 0); @@ -174,7 +174,7 @@ fn a_deposit_that_mints_nothing_is_refunded_at_claim() { let epoch = f.vault.request_deposit(&inv, &1); f.close_epoch(); - f.attest(wad(4)); + f.attest(price(4)); f.vault.fulfill_epoch(&epoch); // 1 asset at 4.0 mints zero shares. @@ -190,7 +190,7 @@ fn a_redemption_that_pays_nothing_returns_the_shares_at_claim() { let epoch = f.vault.request_redeem(&holder, &1); f.close_epoch(); - f.attest(wad(4) / 10); + f.attest(price(4) / 10); f.vault.fulfill_epoch(&epoch); // 1 share at 0.4 pays zero assets. @@ -205,7 +205,7 @@ fn a_delisted_holders_redemption_that_pays_nothing_settles_without_waiting() { let epoch = f.vault.request_redeem(&holder, &1); f.close_epoch(); - f.attest(wad(4) / 10); + f.attest(price(4) / 10); f.vault.fulfill_epoch(&epoch); // 1 share at 0.4 pays zero assets. @@ -233,7 +233,7 @@ fn a_dust_refund_never_takes_committed_money() { f.vault.request_deposit(&dust, &1); f.vault.request_redeem(&holder, &200); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); // Move every free unit out, leaving only what the redeemer is owed. @@ -267,7 +267,7 @@ fn cancelling_is_never_blocked_by_what_the_vault_owes() { f.vault.request_redeem(&holder, &200); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); // A fresh deposit into the open epoch, with the vault fully committed. @@ -287,7 +287,7 @@ fn an_open_epoch_cancels_with_a_healthy_feed() { let f = setup(); let inv = f.investor(1_000); - f.attest(wad(2)); + f.attest(price(2)); let epoch = f.vault.request_deposit(&inv, &400); assert_eq!(f.vault.cancel_deposit(&inv, &epoch), 400); @@ -302,7 +302,7 @@ fn a_sealed_epoch_cannot_be_cancelled_while_it_can_be_priced() { let epoch = f.vault.request_deposit(&inv, &400); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); refused( f.vault.try_cancel_deposit(&inv, &epoch), @@ -321,7 +321,7 @@ fn a_sealed_epoch_cancels_once_the_feed_goes_stale() { let f = setup(); let inv = f.investor(1_000); - f.attest(wad(2)); + f.attest(price(2)); let epoch = f.vault.request_deposit(&inv, &400); f.close_epoch(); @@ -354,7 +354,7 @@ fn a_paused_vault_reopens_cancellation_of_an_epoch_it_could_price() { let epoch = f.vault.request_deposit(&first, &400); f.vault.request_deposit(&second, &400); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); refused( f.vault.try_cancel_deposit(&first, &epoch), VaultError::PriceAvailable, @@ -378,7 +378,7 @@ fn cancellation_reopens_when_the_price_that_closed_it_expires() { let inv = f.investor(1_000); let epoch = f.vault.request_deposit(&inv, &400); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); refused( f.vault.try_cancel_deposit(&inv, &epoch), VaultError::PriceAvailable, diff --git a/contracts/async-vault/src/test/clawback.rs b/contracts/async-vault/src/test/clawback.rs index 87891509..1a309a69 100644 --- a/contracts/async-vault/src/test/clawback.rs +++ b/contracts/async-vault/src/test/clawback.rs @@ -64,7 +64,7 @@ fn a_priced_redemption_waits_while_the_issuer_has_taken_the_escrow() { let exit = f.close_epoch(); let c = f.investor(1_000); f.vault.request_deposit(&c, &300); - f.fulfill_epoch_at(exit, wad(2)); + f.fulfill_epoch_at(exit, price(2)); f.claw_back(300); refused( @@ -82,7 +82,7 @@ fn a_refund_below_one_share_waits_while_the_issuer_has_taken_the_escrow() { let f = setup(); let dust = f.investor(1_000); f.vault.request_deposit(&dust, &1); - let priced = f.fulfill_epoch(wad(2)); + let priced = f.fulfill_epoch(price(2)); let pending = f.investor(1_000); f.vault.request_deposit(&pending, &100); f.claw_back(2); @@ -118,7 +118,7 @@ fn pricing_ignores_a_shortfall_and_mints_the_full_deposit() { let a = f.investor(1_000); f.vault.request_deposit(&a, &100); f.claw_back(40); - let epoch = f.fulfill_epoch(wad(1)); + let epoch = f.fulfill_epoch(price(1)); assert_eq!(f.vault.claim_deposit(&a, &epoch), 100); assert_eq!(f.vault.liquid_reserve(), 60); diff --git a/contracts/async-vault/src/test/compliance.rs b/contracts/async-vault/src/test/compliance.rs index 2dc23f1a..2e737e9c 100644 --- a/contracts/async-vault/src/test/compliance.rs +++ b/contracts/async-vault/src/test/compliance.rs @@ -47,7 +47,7 @@ fn relisting_after_pricing_lets_the_claim_through() { let f = setup(); let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.identity.allow(&investor, &false); f.identity.allow(&investor, &true); @@ -62,7 +62,7 @@ fn a_holder_delisted_after_pricing_is_paid_through_a_wind_down() { let f = setup(); let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.cancellable_escrow(), 0); assert_eq!(f.vault.pending_mint_shares(), 200); f.identity.allow(&investor, &false); @@ -98,7 +98,7 @@ fn a_compliance_module_that_refuses_the_mint_blocks_a_priced_claim() { let f = setup(); let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let module = f.e.register(RefusesEveryMint, ()); f.add_compliance_module(ComplianceHook::CanCreate, &module); @@ -120,7 +120,7 @@ fn an_unbound_compliance_swap_is_refused_and_every_move_goes_on() { let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &100); f.vault.request_redeem(&holder, &4); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let unbound = ComplianceClient::new(&f.e, &f.e.register(Compliance, (f.admin.clone(),))); unbound.bind_vault(&f.vault.address); @@ -173,7 +173,7 @@ fn a_delisted_holder_can_still_claim_their_exit() { let f = setup(); let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.identity.allow(&user, &false); @@ -211,7 +211,7 @@ fn a_delisted_holder_cannot_cancel_redemption_back_to_shares() { assert_eq!(f.shares(&user), 300); // Exit proceeds through cash claim once fulfilled - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_redeem(&user, &epoch), 400); assert_eq!(f.balance(&user), 400); } @@ -224,7 +224,7 @@ fn a_frozen_holder_is_paid_only_after_the_freeze_lifts() { f.share.set_address_frozen(&user, &true, &f.compliance); refused(f.vault.try_cancel_redeem(&user, &epoch), VaultError::Frozen); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); refused(f.vault.try_claim_redeem(&user, &epoch), VaultError::Frozen); assert_eq!(f.vault.committed(), 400); assert_eq!(f.shares(&user), 300); @@ -318,7 +318,7 @@ fn a_frozen_investor_is_not_minted_until_unfrozen() { let f = setup(); let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.share.set_address_frozen(&investor, &true, &f.compliance); refused(f.vault.try_claim_deposit(&investor, &1), VaultError::Frozen); @@ -335,7 +335,7 @@ fn a_frozen_investors_zero_share_refund_is_held() { let f = setup(); let investor = f.investor(10); let epoch = f.vault.request_deposit(&investor, &1); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.share.set_address_frozen(&investor, &true, &f.compliance); refused( @@ -396,7 +396,7 @@ fn a_frozen_holder_does_not_get_a_worthless_exit_back() { let f = setup(); let user = f.holder(1); let epoch = f.vault.request_redeem(&user, &1); - f.fulfill_epoch(WAD_SCALE / 2); + f.fulfill_epoch(PRICE_SCALE / 2); f.share.set_address_frozen(&user, &true, &f.compliance); refused(f.vault.try_claim_redeem(&user, &epoch), VaultError::Frozen); @@ -409,7 +409,7 @@ fn a_frozen_holder_is_not_moved_into_the_exit_queue() { let f = setup(); let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.identity.allow(&investor, &false); f.share.set_address_frozen(&investor, &true, &f.compliance); diff --git a/contracts/async-vault/src/test/controls.rs b/contracts/async-vault/src/test/controls.rs index 75af02cb..2aa7e96a 100644 --- a/contracts/async-vault/src/test/controls.rs +++ b/contracts/async-vault/src/test/controls.rs @@ -79,7 +79,7 @@ fn a_paused_vault_still_lets_investors_claim() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.pause(&f.guardian); assert_eq!(f.vault.claim_deposit(&user, &1), 200); @@ -103,7 +103,7 @@ fn a_paused_vault_still_pays_redemptions() { let f = setup(); let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.pause(&f.guardian); assert_eq!(f.vault.claim_redeem(&user, &epoch), 400); @@ -114,7 +114,7 @@ fn a_paused_vault_still_funds_and_deploys_to_custodian() { let f = setup(); let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.pause(&f.guardian); let free = f.vault.free_reserve(); @@ -136,7 +136,7 @@ fn a_paused_vault_still_funds_and_deploys_to_custodian() { fn a_paused_vault_does_not_fulfill_epochs() { let f = setup(); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.pause(&f.guardian); assert_eq!( @@ -145,7 +145,7 @@ fn a_paused_vault_does_not_fulfill_epochs() { ); f.vault.unpause(&f.admin); - assert_eq!(f.vault.fulfill_epoch(&1), wad(2)); + assert_eq!(f.vault.fulfill_epoch(&1), price(2)); } #[test] @@ -195,7 +195,7 @@ fn a_token_pause_leaves_deposits_exits_and_cancellations_open() { assert_eq!(f.vault.cancel_redeem(&leaver, &epoch), 100); assert_eq!(f.shares(&leaver), 500); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_deposit(&depositor, &epoch), 200); assert_eq!(f.shares(&depositor), 200); assert_eq!(f.vault.claim_redeem(&redeemer, &epoch), 400); @@ -267,12 +267,12 @@ fn a_cooldown_holds_the_standing_price() { f.advance(60); assert_eq!( f.oracle - .try_attest(&nav_input(&f.e, wad(1), 1_000_000), &f.attester), + .try_attest(&nav_input(&f.e, price(1), 1_000_000), &f.attester), Err(Ok(nav_oracle::OracleError::CooldownActive.into())) ); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(2)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(2)); } #[test] @@ -292,7 +292,7 @@ fn a_cooldown_delays_pricing_until_the_attester_can_post() { // valuation younger than its close and waits. assert_eq!( f.oracle - .try_attest(&nav_input(&f.e, wad(1), 1_000_000), &f.attester), + .try_attest(&nav_input(&f.e, price(1), 1_000_000), &f.attester), Err(Ok(nav_oracle::OracleError::CooldownActive.into())) ); refused( @@ -303,10 +303,10 @@ fn a_cooldown_delays_pricing_until_the_attester_can_post() { // Once the cooldown lapses the attester posts and the epoch prices at the // new number, not the one standing when it closed. f.advance(3_600); - f.attest(wad(1)); + f.attest(price(1)); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(1)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(1)); } #[test] diff --git a/contracts/async-vault/src/test/conversions.rs b/contracts/async-vault/src/test/conversions.rs index afcfe785..d2f59ad4 100644 --- a/contracts/async-vault/src/test/conversions.rs +++ b/contracts/async-vault/src/test/conversions.rs @@ -8,7 +8,7 @@ fn a_fractional_share_price_is_representable() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(3 * WAD_SCALE / 2); + f.fulfill_epoch(3 * PRICE_SCALE / 2); assert_eq!(f.vault.claim_deposit(&user, &1), 266); assert_eq!(f.shares(&user), 266); @@ -20,7 +20,7 @@ fn conversion_rounds_down_in_the_vaults_favour() { let user = f.investor(1_000); f.vault.request_deposit(&user, &401); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_deposit(&user, &1), 200); assert_eq!(f.balance(&f.vault.address), 401); @@ -33,9 +33,9 @@ fn a_deposit_too_large_for_an_i128_product_still_converts() { let amount = 10i128.pow(30); f.vault.request_deposit(&whale, &amount); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); - assert!(amount.checked_mul(WAD_SCALE).is_none()); + assert!(amount.checked_mul(PRICE_SCALE).is_none()); assert_eq!(f.vault.claim_deposit(&whale, &1), 5 * 10i128.pow(29)); } @@ -65,14 +65,14 @@ fn conversion_arithmetic_holds_its_rounding_direction() { shares in 0i128..=1_000_000_000_000_000i128, price in 1i128..=1_000_000_000_000_000i128, )| { - let assets = checked_mul_div_floor(&env, &shares, &price, &WAD_SCALE).unwrap(); + let assets = checked_mul_div_floor(&env, &shares, &price, &PRICE_SCALE).unwrap(); // The vault never pays out more than the exact rational amount. - prop_assert!(assets * WAD_SCALE <= shares * price); + prop_assert!(assets * PRICE_SCALE <= shares * price); // And never less than it has to: the floor is tight. - prop_assert!((assets + 1) * WAD_SCALE > shares * price); + prop_assert!((assets + 1) * PRICE_SCALE > shares * price); // Depositing and redeeming straight back never manufactures value. - let back = checked_mul_div_floor(&env, &assets, &WAD_SCALE, &price).unwrap(); + let back = checked_mul_div_floor(&env, &assets, &PRICE_SCALE, &price).unwrap(); prop_assert!(back <= shares); }); } @@ -87,8 +87,8 @@ fn deposit_and_redeem_round_trip_never_manufactures_assets() { assets in 0i128..=1_000_000_000_000_000_000_000_000_000_000i128, price in 1i128..=1_000_000_000_000_000_000_000_000_000_000i128, )| { - if let Some(shares) = checked_mul_div_floor(&env, &assets, &WAD_SCALE, &price) { - if let Some(back_assets) = checked_mul_div_floor(&env, &shares, &price, &WAD_SCALE) { + if let Some(shares) = checked_mul_div_floor(&env, &assets, &PRICE_SCALE, &price) { + if let Some(back_assets) = checked_mul_div_floor(&env, &shares, &price, &PRICE_SCALE) { // Invariant: round-trip through shares can never yield more assets than started. prop_assert!(back_assets <= assets); } @@ -105,8 +105,8 @@ fn redeem_and_deposit_round_trip_never_manufactures_shares() { shares in 0i128..=1_000_000_000_000_000_000_000_000_000_000i128, price in 1i128..=1_000_000_000_000_000_000_000_000_000_000i128, )| { - if let Some(assets) = checked_mul_div_floor(&env, &shares, &price, &WAD_SCALE) { - if let Some(back_shares) = checked_mul_div_floor(&env, &assets, &WAD_SCALE, &price) { + if let Some(assets) = checked_mul_div_floor(&env, &shares, &price, &PRICE_SCALE) { + if let Some(back_shares) = checked_mul_div_floor(&env, &assets, &PRICE_SCALE, &price) { // Invariant: round-trip through assets can never yield more shares than started. prop_assert!(back_shares <= shares); } @@ -123,12 +123,12 @@ fn deposit_floor_is_strictly_tight() { assets in 0i128..=1_000_000_000_000_000i128, price in 1i128..=1_000_000_000_000_000i128, )| { - let shares = checked_mul_div_floor(&env, &assets, &WAD_SCALE, &price).unwrap(); + let shares = checked_mul_div_floor(&env, &assets, &PRICE_SCALE, &price).unwrap(); // Never mints more shares than backed by assets. - prop_assert!(shares * price <= assets * WAD_SCALE); + prop_assert!(shares * price <= assets * PRICE_SCALE); // Floor is tight: not a single additional share could be minted. - prop_assert!((shares + 1) * price > assets * WAD_SCALE); + prop_assert!((shares + 1) * price > assets * PRICE_SCALE); }); } @@ -148,30 +148,30 @@ fn conversion_monotonicity_in_amount_and_price() { // Monotonic in amount: if let (Some(s_low), Some(s_high)) = ( - checked_mul_div_floor(&env, &amin, &WAD_SCALE, &pmin), - checked_mul_div_floor(&env, &amax, &WAD_SCALE, &pmin), + checked_mul_div_floor(&env, &amin, &PRICE_SCALE, &pmin), + checked_mul_div_floor(&env, &amax, &PRICE_SCALE, &pmin), ) { prop_assert!(s_low <= s_high); } if let (Some(a_low), Some(a_high)) = ( - checked_mul_div_floor(&env, &amin, &pmin, &WAD_SCALE), - checked_mul_div_floor(&env, &amax, &pmin, &WAD_SCALE), + checked_mul_div_floor(&env, &amin, &pmin, &PRICE_SCALE), + checked_mul_div_floor(&env, &amax, &pmin, &PRICE_SCALE), ) { prop_assert!(a_low <= a_high); } // Monotonic in price: if let (Some(s_cheap), Some(s_dear)) = ( - checked_mul_div_floor(&env, &amax, &WAD_SCALE, &pmin), - checked_mul_div_floor(&env, &amax, &WAD_SCALE, &pmax), + checked_mul_div_floor(&env, &amax, &PRICE_SCALE, &pmin), + checked_mul_div_floor(&env, &amax, &PRICE_SCALE, &pmax), ) { prop_assert!(s_dear <= s_cheap); } if let (Some(a_cheap), Some(a_dear)) = ( - checked_mul_div_floor(&env, &amax, &pmin, &WAD_SCALE), - checked_mul_div_floor(&env, &amax, &pmax, &WAD_SCALE), + checked_mul_div_floor(&env, &amax, &pmin, &PRICE_SCALE), + checked_mul_div_floor(&env, &amax, &pmax, &PRICE_SCALE), ) { prop_assert!(a_cheap <= a_dear); } diff --git a/contracts/async-vault/src/test/delisted.rs b/contracts/async-vault/src/test/delisted.rs index b09ad638..aaa8d1f4 100644 --- a/contracts/async-vault/src/test/delisted.rs +++ b/contracts/async-vault/src/test/delisted.rs @@ -10,7 +10,7 @@ use crate::{ fn a_priced_deposit(f: &Fixture) -> (Address, u64) { let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); (investor, epoch) } @@ -79,7 +79,7 @@ fn the_delisted_holder_is_paid_at_the_next_epochs_price() { let (investor, epoch) = delisted_with_a_priced_deposit(&f); f.vault.claim_deposit(&investor, &epoch); - let exit = f.fulfill_epoch(wad(8) / 5); + let exit = f.fulfill_epoch(price(8) / 5); assert_eq!(f.vault.claim_redeem(&investor, &exit), 320); assert_eq!(f.balance(&investor), 600 + 320); @@ -93,7 +93,7 @@ fn the_delisted_holder_exits_at_the_same_price_as_everyone_in_that_epoch() { f.vault.claim_deposit(&investor, &epoch); f.vault.request_redeem(&other, &200); - let exit = f.fulfill_epoch(wad(8) / 5); + let exit = f.fulfill_epoch(price(8) / 5); assert_eq!(f.vault.claim_redeem(&investor, &exit), 320); assert_eq!(f.vault.claim_redeem(&other, &exit), 320); @@ -105,7 +105,7 @@ fn a_conversion_adds_to_a_redemption_already_open_in_the_epoch() { let investor = f.holder(100); StellarAssetClient::new(&f.e, &f.asset).mint(&investor, &400); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let open = f.vault.current_epoch(); f.vault.request_redeem(&investor, &100); f.identity.allow(&investor, &false); @@ -280,7 +280,7 @@ fn a_conversion_waits_while_the_vault_is_delisted() { let f = setup(); let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &1_000); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.identity.allow(&investor, &false); f.identity.allow(&f.vault.address, &false); @@ -317,7 +317,7 @@ fn a_verifier_fault_for_one_holder_pays_the_priced_deposit_out_in_cash() { 200 ); - let exit = f.fulfill_epoch(wad(2)); + let exit = f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_redeem(&investor, &exit), 400); assert_eq!(balances(&f, &investor), (1_000, 0, 0, 0)); } @@ -363,7 +363,7 @@ proptest! { who }) .collect(); - let epoch = f.fulfill_epoch(wad(1) * price_tenths / 10); + let epoch = f.fulfill_epoch(price(1) * price_tenths / 10); let open = f.vault.current_epoch(); let mut claims: std::vec::Vec<(u16, usize)> = diff --git a/contracts/async-vault/src/test/deposit.rs b/contracts/async-vault/src/test/deposit.rs index 0e97317b..0d82baec 100644 --- a/contracts/async-vault/src/test/deposit.rs +++ b/contracts/async-vault/src/test/deposit.rs @@ -142,7 +142,7 @@ fn a_user_can_claim_deposit_and_receive_shares() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_deposit(&user, &1), 200); @@ -158,7 +158,7 @@ fn a_deposit_cannot_be_claimed_twice() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.claim_deposit(&user, &1); f.vault.claim_deposit(&user, &1); @@ -182,7 +182,7 @@ fn claiming_without_a_request_is_rejected() { let f = setup(); let stranger = Address::generate(&f.e); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); refused( f.vault.try_claim_deposit(&stranger, &1), VaultError::RequestNotFound, @@ -213,7 +213,7 @@ fn a_deposit_below_one_share_is_refunded_at_claim() { let user = f.investor(1_000); f.vault.request_deposit(&user, &1); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); // Nothing to mint, so the asset goes back rather than being kept. assert_eq!(f.vault.claim_deposit(&user, &1), 0); @@ -226,7 +226,7 @@ fn a_refund_after_pricing_leaves_the_priced_total_unchanged() { let f = setup(); let user = f.investor(1_000); f.vault.request_deposit(&user, &1); - let epoch = f.fulfill_epoch(wad(2)); + let epoch = f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_deposit(&user, &epoch), 0); @@ -249,7 +249,7 @@ fn claiming_needs_the_investor_authorisation() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.e.set_auths(&[]); missing_auth(f.vault.try_claim_deposit(&user, &1)); @@ -261,9 +261,9 @@ fn claims_are_scoped_to_their_own_epoch() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.request_deposit(&user, &300); - f.fulfill_epoch(wad(3)); + f.fulfill_epoch(price(3)); assert_eq!(f.vault.claim_deposit(&user, &1), 200); assert_eq!(f.vault.claim_deposit(&user, &2), 100); @@ -276,7 +276,7 @@ fn deposits_after_fulfilling_land_in_the_new_epoch() { let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.request_deposit(&investor, &300), 2); @@ -317,7 +317,7 @@ fn a_deposit_is_refused_while_the_feed_is_stale() { assert_eq!(f.balance(&investor), 1_000); assert_eq!(f.vault.cancellable_escrow(), 0); - f.attest(wad(1)); + f.attest(price(1)); f.vault.request_deposit(&investor, &100); } @@ -343,6 +343,6 @@ fn a_deposit_is_refused_before_the_first_report() { f.vault.try_request_deposit(&investor, &100), VaultError::FeedNotValid, ); - f.attest(wad(1)); + f.attest(price(1)); f.vault.request_deposit(&investor, &100); } diff --git a/contracts/async-vault/src/test/deposit_cap.rs b/contracts/async-vault/src/test/deposit_cap.rs index 5ae9b38d..200318e0 100644 --- a/contracts/async-vault/src/test/deposit_cap.rs +++ b/contracts/async-vault/src/test/deposit_cap.rs @@ -111,7 +111,7 @@ fn deployed_capital_and_multi_epoch_accounting() { // Epoch 1 deposit f.vault.request_deposit(&investor1, &1_000); f.vault.close_epoch(&f.manager); - f.attest(wad(1)); + f.attest(price(1)); f.vault.fulfill_epoch(&1); // Deploy 800 to custodian @@ -143,7 +143,7 @@ fn redemptions_free_capacity() { // Epoch 1: investor1 deposits 1_000 and claims 1_000 shares f.vault.request_deposit(&investor1, &1_000); f.vault.close_epoch(&f.manager); - f.attest(wad(1)); + f.attest(price(1)); f.vault.fulfill_epoch(&1); f.vault.claim_deposit(&investor1, &1); @@ -156,7 +156,7 @@ fn redemptions_free_capacity() { // Investor 1 requests redemption of 500 shares f.vault.request_redeem(&investor1, &500); f.vault.close_epoch(&f.manager); - f.attest(wad(1)); + f.attest(price(1)); f.vault.fulfill_epoch(&2); // Redemption is now priced and committed (500 committed to exit) @@ -185,7 +185,7 @@ fn capital_deployed_under_a_cap(f: &Fixture) -> Address { f.vault.set_deposit_cap(&Some(1_000)); let epoch = f.vault.request_deposit(&investor, &1_000); f.close_epoch(); - f.fulfill_epoch_at(epoch, wad(1)); + f.fulfill_epoch_at(epoch, price(1)); f.vault.deploy_to_custodian(&f.treasury, &1_000); f.vault.set_deposit_cap(&Some(1_500)); investor @@ -224,7 +224,7 @@ fn a_gain_paid_out_to_leavers_leaves_room_above_the_cap() { StellarAssetClient::new(&f.e, &f.asset).mint(&f.custodian, &1_000); f.vault.fund(&f.custodian, &2_000); let exit = f.vault.request_redeem(&investor, &1_000); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.claim_redeem(&investor, &exit); assert_eq!(f.vault.net_deployed(), -1_000); @@ -244,7 +244,7 @@ fn a_loss_at_the_custodian_still_counts_toward_the_cap() { f.vault.claim_deposit(&investor, &1); f.vault.fund(&f.custodian, &500); let exit = f.vault.request_redeem(&investor, &1_000); - f.fulfill_epoch(wad(1) / 2); + f.fulfill_epoch(price(1) / 2); f.vault.claim_redeem(&investor, &exit); assert_eq!(f.vault.net_deployed(), 500); diff --git a/contracts/async-vault/src/test/epochs.rs b/contracts/async-vault/src/test/epochs.rs index 55ba6910..a8660f65 100644 --- a/contracts/async-vault/src/test/epochs.rs +++ b/contracts/async-vault/src/test/epochs.rs @@ -6,11 +6,11 @@ use super::*; fn fulfilling_an_epoch_prices_it_and_opens_the_next() { let f = setup(); - assert_eq!(f.fulfill_epoch(wad(2)), 1); + assert_eq!(f.fulfill_epoch(price(2)), 1); let epoch_1 = f.vault.get_epoch(&1).unwrap(); assert_eq!(epoch_1.status, EpochStatus::Fulfilled); - assert_eq!(epoch_1.share_price, wad(2)); + assert_eq!(epoch_1.share_price, price(2)); let epoch_2 = f.vault.get_epoch(&2).unwrap(); assert_eq!(epoch_2.status, EpochStatus::Open); @@ -26,11 +26,11 @@ fn fulfilling_keeps_the_epoch_total() { let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let epoch_1 = f.vault.get_epoch(&1).unwrap(); assert_eq!(epoch_1.total_deposited, 400); - assert_eq!(epoch_1.share_price, wad(2)); + assert_eq!(epoch_1.share_price, price(2)); assert_eq!( f.vault.get_deposit_request(&1, &investor).unwrap().amount, 400 @@ -91,7 +91,7 @@ fn a_redeem_cannot_join_a_sealed_epoch() { #[test] fn an_open_epoch_cannot_be_fulfilled() { let f = setup(); - f.attest(wad(2)); + f.attest(price(2)); refused(f.vault.try_fulfill_epoch(&1), VaultError::EpochNotPending); assert_eq!(f.vault.get_epoch(&1).unwrap().status, EpochStatus::Open); @@ -118,13 +118,13 @@ fn a_sealed_epoch_cannot_be_closed_again() { #[test] fn a_fulfilled_epoch_cannot_be_fulfilled_again() { let f = setup(); - let epoch = f.fulfill_epoch(wad(2)); + let epoch = f.fulfill_epoch(price(2)); refused( f.vault.try_fulfill_epoch(&epoch), VaultError::EpochNotPending, ); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(2)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(2)); } #[test] @@ -133,7 +133,7 @@ fn epochs_can_be_fulfilled_out_of_order_after_closing() { let first = f.close_epoch(); let second = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&second); f.vault.fulfill_epoch(&first); @@ -175,10 +175,10 @@ fn closing_needs_the_manager_authorisation() { fn anyone_may_fulfill_a_closed_epoch() { let f = setup(); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.e.set_auths(&[]); - assert_eq!(f.vault.fulfill_epoch(&epoch), wad(2)); + assert_eq!(f.vault.fulfill_epoch(&epoch), price(2)); assert_eq!( f.vault.get_epoch(&epoch).unwrap().status, diff --git a/contracts/async-vault/src/test/events.rs b/contracts/async-vault/src/test/events.rs index e34573bc..dfc0f346 100644 --- a/contracts/async-vault/src/test/events.rs +++ b/contracts/async-vault/src/test/events.rs @@ -49,7 +49,7 @@ fn pricing_an_epoch_publishes_the_share_price() { let user = f.investor(1_000); f.vault.request_deposit(&user, &400); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); let share_price = f.vault.fulfill_epoch(&epoch); @@ -76,7 +76,7 @@ fn claiming_the_last_deposit_publishes_the_shares_paid_and_the_settlement() { let f = setup(); let user = f.investor(1_000); f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.claim_deposit(&user, &1); @@ -126,7 +126,7 @@ fn a_deposit_priced_at_zero_shares_publishes_a_refund_not_a_cancellation() { let epoch = f.vault.request_deposit(&inv, &1); f.close_epoch(); - f.attest(wad(4)); + f.attest(price(4)); f.vault.fulfill_epoch(&epoch); assert_eq!(f.vault.claim_deposit(&inv, &epoch), 0); diff --git a/contracts/async-vault/src/test/guards.rs b/contracts/async-vault/src/test/guards.rs index e8a0bc86..5222de33 100644 --- a/contracts/async-vault/src/test/guards.rs +++ b/contracts/async-vault/src/test/guards.rs @@ -484,13 +484,13 @@ fn positive_amount_refuses_zero_and_below() { #[test] fn feed_valid_refuses_a_stale_or_paused_feed() { let f = setup(); - f.attest(wad(1)); + f.attest(price(1)); holds(&f, || guards::feed_valid(&f.e)); f.advance(f.oracle.config().freshness_duration + 1); refuses(&f, VaultError::FeedNotValid, || guards::feed_valid(&f.e)); - f.attest(wad(1)); + f.attest(price(1)); holds(&f, || guards::feed_valid(&f.e)); f.oracle.pause_nav(&f.guardian); refuses(&f, VaultError::FeedNotValid, || guards::feed_valid(&f.e)); @@ -675,7 +675,7 @@ fn epoch_fulfilled_refuses_an_epoch_not_yet_priced() { guards::epoch_fulfilled(&f.e, &sealed) }); - f.fulfill_epoch_at(id, wad(1)); + f.fulfill_epoch_at(id, price(1)); let priced = epoch(&f, id); holds(&f, || guards::epoch_fulfilled(&f.e, &priced)); } @@ -687,7 +687,7 @@ fn not_priced_refuses_a_priced_epoch() { let sealed = epoch(&f, id); holds(&f, || guards::not_priced(&f.e, &sealed)); - f.fulfill_epoch_at(id, wad(1)); + f.fulfill_epoch_at(id, price(1)); let priced = epoch(&f, id); refuses(&f, VaultError::AlreadyPriced, || { guards::not_priced(&f.e, &priced) @@ -704,7 +704,7 @@ fn no_price_available_refuses_a_sealed_epoch_the_vault_could_price() { let sealed = epoch(&f, id); holds(&f, || guards::no_price_available(&f.e, &sealed)); - f.attest(wad(1)); + f.attest(price(1)); refuses(&f, VaultError::PriceAvailable, || { guards::no_price_available(&f.e, &sealed) }); @@ -714,7 +714,7 @@ fn no_price_available_refuses_a_sealed_epoch_the_vault_could_price() { f.vault.unpause(&f.admin); wind_down_now(&f); - f.attest(wad(1)); + f.attest(price(1)); holds(&f, || guards::no_price_available(&f.e, &sealed)); } @@ -731,7 +731,7 @@ fn fulfilable_refuses_an_epoch_the_vault_cannot_price_yet() { refuses(&f, VaultError::FeedNotValid, || { guards::fulfilable(&f.e, &unpriced) }); - f.attest(wad(1)); + f.attest(price(1)); holds(&f, || guards::fulfilable(&f.e, &unpriced)); f.advance(10); diff --git a/contracts/async-vault/src/test/health.rs b/contracts/async-vault/src/test/health.rs index f7dcb71e..9e152c26 100644 --- a/contracts/async-vault/src/test/health.rs +++ b/contracts/async-vault/src/test/health.rs @@ -25,7 +25,7 @@ fn a_finished_vault_with_a_fresh_report_is_healthy() { let f = setup_unfinished(); f.vault.set_min_epoch_duration(&DAY_DURATION); f.vault.finish_setup(); - f.attest(wad(1)); + f.attest(price(1)); assert_eq!(f.vault.health(), all_healthy()); } @@ -34,7 +34,7 @@ fn a_finished_vault_with_a_fresh_report_is_healthy() { fn an_open_setup_is_reported() { let f = setup_unfinished(); f.vault.set_min_epoch_duration(&DAY_DURATION); - f.attest(wad(1)); + f.attest(price(1)); assert_eq!( f.vault.health(), @@ -152,7 +152,7 @@ fn each_missing_wiring_step_shows_in_its_own_flag() { for (miswire, expected) in cases { let f = miswired(miswire); f.vault.set_min_epoch_duration(&DAY_DURATION); - f.attest(wad(1)); + f.attest(price(1)); assert_eq!( f.vault.health(), @@ -170,7 +170,7 @@ fn a_feed_with_no_report_or_the_nav_paused_is_not_valid() { let f = setup_unfinished(); assert!(!f.vault.health().feed_valid); - f.attest(wad(1)); + f.attest(price(1)); f.oracle.pause_nav(&f.guardian); assert!(!f.vault.health().feed_valid); } @@ -178,7 +178,7 @@ fn a_feed_with_no_report_or_the_nav_paused_is_not_valid() { #[test] fn a_notice_longer_than_a_report_lives_is_reported() { let f = setup(); - f.attest(wad(1)); + f.attest(price(1)); let freshness = f.oracle.config().freshness_duration; f.vault.set_notice(&(freshness + 1)); @@ -189,7 +189,7 @@ fn a_notice_longer_than_a_report_lives_is_reported() { #[test] fn a_vault_with_no_minimum_set_is_reported() { let f = setup(); - f.attest(wad(1)); + f.attest(price(1)); assert!(!f.vault.health().min_epoch_duration_set); } @@ -199,7 +199,7 @@ fn setting_the_minimum_during_setup_clears_the_flag() { let f = setup_unfinished(); f.vault.set_min_epoch_duration(&DAY_DURATION); f.vault.finish_setup(); - f.attest(wad(1)); + f.attest(price(1)); assert!(f.vault.health().min_epoch_duration_set); } diff --git a/contracts/async-vault/src/test/mod.rs b/contracts/async-vault/src/test/mod.rs index 32366183..5fe03baa 100644 --- a/contracts/async-vault/src/test/mod.rs +++ b/contracts/async-vault/src/test/mod.rs @@ -48,8 +48,8 @@ pub(crate) use nav_oracle::{ }; pub(crate) use share_token::{ShareToken, ShareTokenClient}; -pub(crate) use stellar_contract_utils::math::wad::WAD_SCALE; use stellar_tokens::rwa::{compliance::ComplianceHook, RWA}; +pub(crate) use strata_bindings::PRICE_SCALE; pub(crate) use strata_timelock::DAY_DURATION; pub(crate) use crate::{ @@ -58,8 +58,8 @@ pub(crate) use crate::{ MAX_WIND_DOWN_DELAY, MIN_UPGRADE_DELAY, MIN_WIND_DOWN_DELAY, }; -fn wad(whole: i128) -> i128 { - whole * WAD_SCALE +fn price(whole: i128) -> i128 { + whole * PRICE_SCALE } fn nav_input(e: &Env, nav_per_share: i128, expires_at: u64) -> NavInput { @@ -184,7 +184,7 @@ impl Fixture<'_> { fn holder(&self, shares: i128) -> Address { let who = self.investor(shares * 2); let epoch = self.vault.request_deposit(&who, &(shares * 2)); - self.fulfill_epoch(wad(2)); + self.fulfill_epoch(price(2)); self.vault.claim_deposit(&who, &epoch); who } @@ -301,7 +301,7 @@ fn open_feed() -> OracleConfig { max_up_bps: 10_000, max_down_bps: 10_000, min_answer: MIN_ANSWER, - max_answer: 1_000 * WAD_SCALE, + max_answer: 1_000 * PRICE_SCALE, } } diff --git a/contracts/async-vault/src/test/multi_epoch.rs b/contracts/async-vault/src/test/multi_epoch.rs index afc46ead..552f9cbc 100644 --- a/contracts/async-vault/src/test/multi_epoch.rs +++ b/contracts/async-vault/src/test/multi_epoch.rs @@ -32,7 +32,7 @@ fn a_younger_epoch_can_be_priced_first() { let first = f.close_epoch(); let second = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&second); f.vault.fulfill_epoch(&first); @@ -62,7 +62,7 @@ fn the_rounding_residue_stays_in_the_reserve_once_the_epoch_settles() { f.vault.request_redeem(&c, &105); let epoch = f.close_epoch(); - f.attest(wad(3) / 2); + f.attest(price(3) / 2); f.vault.fulfill_epoch(&epoch); // floor(309 * 1.5) = 463 credited for the epoch. @@ -93,7 +93,7 @@ fn one_holder_redeems_across_two_epochs() { assert_eq!(f.shares(&a), 100); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&first); f.vault.fulfill_epoch(&second); @@ -114,18 +114,18 @@ fn deposit_only_redeem_only_and_empty_epochs() { let deposits = f.vault.request_deposit(&inv, &400); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&deposits); f.vault.claim_deposit(&inv, &deposits); assert_eq!(f.shares(&inv), 200); f.vault.request_redeem(&inv, &200); let redeems = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&redeems); let empty = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&empty); assert_eq!(f.vault.get_epoch(&empty).unwrap().total_deposited, 0); @@ -147,7 +147,7 @@ fn an_epoch_that_owes_nothing_is_fulfilled_having_paid_nobody() { let epoch = f.close_epoch(); // 0.4 per share: floor(2 * 0.4) = 0 owed for the whole epoch. - f.attest(wad(4) / 10); + f.attest(price(4) / 10); f.vault.fulfill_epoch(&epoch); assert_eq!(f.vault.committed(), 0); @@ -172,7 +172,7 @@ fn a_later_epochs_deposit_does_not_fund_an_earlier_exit() { f.vault.request_redeem(&a, &100); let exits = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&exits); // Nothing on hand, so the claim waits. @@ -210,7 +210,7 @@ fn an_epoch_prices_without_the_cash() { f.vault.request_redeem(&a, &100); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); assert_eq!( @@ -232,7 +232,7 @@ fn a_claim_waits_until_the_reserve_covers_it() { f.vault.request_redeem(&a, &100); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); refused( @@ -258,7 +258,7 @@ fn a_covered_claim_pays_while_a_larger_one_waits() { f.vault.request_redeem(&big, &400); f.vault.request_redeem(&small, &20); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); // 840 owed in total, only 100 on hand. @@ -280,7 +280,7 @@ fn the_treasury_cannot_deploy_while_anything_is_uncovered() { f.vault.request_redeem(&a, &200); let epoch = f.close_epoch(); - f.attest(wad(3)); + f.attest(price(3)); f.vault.fulfill_epoch(&epoch); // 600 owed against 400 held. diff --git a/contracts/async-vault/src/test/notice.rs b/contracts/async-vault/src/test/notice.rs index fbd03da5..ad55c79f 100644 --- a/contracts/async-vault/src/test/notice.rs +++ b/contracts/async-vault/src/test/notice.rs @@ -70,7 +70,7 @@ fn an_epoch_cannot_be_priced_inside_its_notice() { f.vault.set_notice(&3_600); f.vault.request_redeem(&holder, &100); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); refused( f.vault.try_fulfill_epoch(&epoch), @@ -87,10 +87,10 @@ fn it_is_priced_once_the_notice_elapses() { let epoch = f.close_epoch(); f.advance(3_600); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(2)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(2)); } #[test] @@ -99,11 +99,11 @@ fn a_notice_of_zero_prices_as_soon_as_the_valuation_lands() { let holder = f.holder(100); f.vault.request_redeem(&holder, &100); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(2)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(2)); } #[test] @@ -130,7 +130,7 @@ fn the_notice_does_not_reopen_the_cancellation_window() { f.vault.set_notice(&3_600); f.vault.request_deposit(&investor, &1_000); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); // The price is readable even though the epoch cannot be priced yet, so // cancelling now would be declining a price already seen. diff --git a/contracts/async-vault/src/test/oracle_pricing.rs b/contracts/async-vault/src/test/oracle_pricing.rs index d1ec49ec..ff2707c8 100644 --- a/contracts/async-vault/src/test/oracle_pricing.rs +++ b/contracts/async-vault/src/test/oracle_pricing.rs @@ -16,51 +16,51 @@ fn fulfill_is_rejected_before_the_first_attestation() { fn fulfill_is_rejected_while_the_nav_is_paused() { let f = setup(); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.oracle.pause_nav(&f.guardian); refused(f.vault.try_fulfill_epoch(&1), VaultError::FeedNotValid); f.oracle.set_nav_paused(&false); - assert_eq!(f.vault.fulfill_epoch(&1), wad(2)); + assert_eq!(f.vault.fulfill_epoch(&1), price(2)); } #[test] fn fulfill_is_rejected_once_the_feed_goes_stale() { let f = setup(); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.advance(3_601); assert!(f.oracle.is_stale()); refused(f.vault.try_fulfill_epoch(&1), VaultError::FeedNotValid); assert_eq!(f.vault.get_epoch(&1).unwrap().status, EpochStatus::Pending); - f.attest(wad(1)); + f.attest(price(1)); f.vault.fulfill_epoch(&1); - assert_eq!(f.vault.get_epoch(&1).unwrap().share_price, wad(1)); + assert_eq!(f.vault.get_epoch(&1).unwrap().share_price, price(1)); } #[test] fn the_epoch_is_priced_at_the_attestation() { let f = setup(); f.close_epoch(); - f.attest(3 * WAD_SCALE / 2); + f.attest(3 * PRICE_SCALE / 2); f.vault.fulfill_epoch(&1); assert_eq!( f.vault.get_epoch(&1).unwrap().share_price, - 3 * WAD_SCALE / 2 + 3 * PRICE_SCALE / 2 ); - assert_eq!(f.oracle.nav_per_share(), 3 * WAD_SCALE / 2); + assert_eq!(f.oracle.nav_per_share(), 3 * PRICE_SCALE / 2); } #[test] fn an_epoch_is_not_priced_against_a_valuation_older_than_its_close() { let f = setup(); let holder = f.holder(100); - f.attest(wad(3)); + f.attest(price(3)); f.vault.request_redeem(&holder, &100); f.advance(60); @@ -81,11 +81,11 @@ fn a_valuation_that_lands_after_the_close_prices_the_epoch() { f.advance(60); let epoch = f.close_epoch(); f.advance(60); - f.attest(wad(3)); + f.attest(price(3)); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(3)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(3)); } #[test] @@ -96,11 +96,11 @@ fn a_valuation_taken_in_the_closing_ledger_prices_the_epoch() { f.advance(60); let epoch = f.close_epoch(); - f.attest(wad(3)); + f.attest(price(3)); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(3)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(3)); assert_eq!( f.oracle.attested_at(), f.vault.get_epoch(&epoch).unwrap().closed_at @@ -126,7 +126,7 @@ fn a_priced_redemption_still_pays_while_the_nav_is_paused() { let f = setup(); let holder = f.holder(500); let epoch = f.vault.request_redeem(&holder, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.oracle.pause_nav(&f.guardian); assert_eq!(f.oracle.state(), OracleState::Paused); assert_eq!(f.vault.uncovered(), 0); @@ -140,7 +140,7 @@ fn a_priced_redemption_still_pays_once_the_feed_goes_stale() { let f = setup(); let holder = f.holder(500); let epoch = f.vault.request_redeem(&holder, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.advance(f.oracle.config().freshness_duration + 1); assert_eq!(f.oracle.state(), OracleState::Stale); assert_eq!(f.vault.uncovered(), 0); @@ -154,7 +154,7 @@ fn a_priced_deposit_still_claims_while_the_nav_is_paused() { let f = setup(); let investor = f.investor(400); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.oracle.pause_nav(&f.guardian); assert_eq!(f.oracle.state(), OracleState::Paused); diff --git a/contracts/async-vault/src/test/oracle_swap.rs b/contracts/async-vault/src/test/oracle_swap.rs index 4d6a6697..af052530 100644 --- a/contracts/async-vault/src/test/oracle_swap.rs +++ b/contracts/async-vault/src/test/oracle_swap.rs @@ -73,7 +73,7 @@ impl BrokenFeed { e.storage() .instance() .get(&symbol_short!("nav")) - .unwrap_or(WAD_SCALE) + .unwrap_or(PRICE_SCALE) } } @@ -167,17 +167,17 @@ fn the_next_epoch_prices_from_the_new_feed() { .propose_change(&VaultChange::Oracle(next.address.clone())); f.advance(MIN_UPGRADE_DELAY); f.vault.apply_change(&id); - attest_on(&f, &next, wad(2)); + attest_on(&f, &next, price(2)); let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.advance(next.config().cooldown_secs); - attest_on(&f, &next, wad(4)); + attest_on(&f, &next, price(4)); f.vault.fulfill_epoch(&epoch); - assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, wad(4)); + assert_eq!(f.vault.get_epoch(&epoch).unwrap().share_price, price(4)); } #[test] @@ -193,7 +193,7 @@ fn a_sealed_epoch_is_priced_by_the_feed_standing_at_fulfilment() { .propose_change(&VaultChange::Oracle(next.address.clone())); f.advance(MIN_UPGRADE_DELAY); f.vault.apply_change(&id); - attest_on(&f, &next, wad(4)); + attest_on(&f, &next, price(4)); f.vault.fulfill_epoch(&epoch); assert_eq!(f.vault.claim_deposit(&investor, &epoch), 100); @@ -369,7 +369,7 @@ fn both_sides_of_a_sealed_epoch_cancel_when_the_feed_traps_on_its_price() { #[test] fn both_sides_of_a_sealed_epoch_cancel_when_the_feed_prices_at_zero_or_less() { - for nav in [0, -WAD_SCALE] { + for nav in [0, -PRICE_SCALE] { let f = setup(); let (investor, holder, epoch) = seal_both_sides(&f); swap_to_a_feed_that_prices_at(&f, nav); @@ -381,7 +381,7 @@ fn both_sides_of_a_sealed_epoch_cancel_when_the_feed_prices_at_zero_or_less() { #[test] fn a_feed_that_prices_at_zero_or_less_refuses_fulfilment() { - for nav in [0, -WAD_SCALE] { + for nav in [0, -PRICE_SCALE] { let f = setup(); let (_, _, epoch) = seal_both_sides(&f); swap_to_a_feed_that_prices_at(&f, nav); diff --git a/contracts/async-vault/src/test/pricing.rs b/contracts/async-vault/src/test/pricing.rs index 2576ef7d..7568206f 100644 --- a/contracts/async-vault/src/test/pricing.rs +++ b/contracts/async-vault/src/test/pricing.rs @@ -3,12 +3,21 @@ use super::*; #[test] fn direct_unit_pricing_reads_oracle_nav() { let f = setup(); - f.attest(wad(2)); + f.attest(price(2)); - let price = f.e.as_contract(&f.vault.address, || { + let resolved = f.e.as_contract(&f.vault.address, || { DirectUnitPricing::resolve_share_price(&f.e).unwrap() }); - assert_eq!(price, wad(2)); + assert_eq!(resolved, price(2)); +} + +#[test] +fn a_price_of_one_carries_fourteen_decimals() { + let env = Env::default(); + let one = 100_000_000_000_000; + + assert_eq!(DirectUnitPricing::deposit_shares(&env, 7, one), Ok(7)); + assert_eq!(DirectUnitPricing::redeem_assets(&env, 7, one), Ok(7)); } #[test] @@ -37,11 +46,11 @@ fn direct_unit_pricing_rejects_zero_or_negative_price() { fn conversions_round_down_in_vault_favour_and_preserve_value() { let env = Env::default(); let prices = [ - wad(1) / 2, // 0.5 NAV - wad(1), // 1.0 par NAV - 3 * wad(1) / 2, // 1.5 NAV - wad(2), // 2.0 NAV - 1234567890123456789i128, // fractional irregular NAV + price(1) / 2, // 0.5 NAV + price(1), // 1.0 par NAV + 3 * price(1) / 2, // 1.5 NAV + price(2), // 2.0 NAV + 123_456_789_012_345, // fractional irregular NAV ]; let amounts = [1i128, 10, 100, 1_001, 100_000, 10_000_000_000]; @@ -50,10 +59,10 @@ fn conversions_round_down_in_vault_favour_and_preserve_value() { for &assets in &amounts { let shares = DirectUnitPricing::deposit_shares(&env, assets, price).unwrap(); - // Floor check for deposit: shares * price <= assets * WAD_SCALE + // Floor check for deposit: shares * price <= assets * PRICE_SCALE assert!( - shares * price <= assets * WAD_SCALE, - "deposit minted too many shares: {shares} * {price} > {assets} * WAD" + shares * price <= assets * PRICE_SCALE, + "deposit minted too many shares: {shares} * {price} > {assets} * PRICE_SCALE" ); // Round trip: redeeming shares should never yield more assets than deposited @@ -63,10 +72,10 @@ fn conversions_round_down_in_vault_favour_and_preserve_value() { "round-trip value created: {redeemed} > {assets}" ); - // Floor check for redeem: redeemed * WAD_SCALE <= shares * price + // Floor check for redeem: redeemed * PRICE_SCALE <= shares * price assert!( - redeemed * WAD_SCALE <= shares * price, - "redeem paid out too many assets: {redeemed} * WAD > {shares} * {price}" + redeemed * PRICE_SCALE <= shares * price, + "redeem paid out too many assets: {redeemed} * PRICE_SCALE > {shares} * {price}" ); } } diff --git a/contracts/async-vault/src/test/redeem.rs b/contracts/async-vault/src/test/redeem.rs index cbf04bd2..a7e0686b 100644 --- a/contracts/async-vault/src/test/redeem.rs +++ b/contracts/async-vault/src/test/redeem.rs @@ -83,7 +83,7 @@ fn claim_redeem_pays_assets_and_burns_the_shares() { let supply_before = f.share.total_supply(); let vault_assets_before = f.balance(&f.vault.address); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_redeem(&user, &epoch), 400); assert_eq!(f.balance(&user), 400); @@ -98,7 +98,7 @@ fn a_redeem_cannot_be_claimed_twice() { let f = setup(); let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.vault.claim_redeem(&user, &epoch); refused( @@ -148,7 +148,7 @@ fn the_epoch_prices_but_the_claim_waits_for_the_cash() { assert_eq!(f.balance(&f.vault.address), 1_000); f.close_epoch(); - f.attest(wad(4)); + f.attest(price(4)); // 2_000 owed against 1_000 held. Pricing records it; payment waits. f.vault.fulfill_epoch(&epoch); @@ -170,7 +170,7 @@ fn a_covered_epoch_is_fulfilled_and_leaves_the_liability_pending() { let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &500); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!( f.vault.get_epoch(&epoch).unwrap().status, diff --git a/contracts/async-vault/src/test/sealing.rs b/contracts/async-vault/src/test/sealing.rs index 779e6b01..4be70d07 100644 --- a/contracts/async-vault/src/test/sealing.rs +++ b/contracts/async-vault/src/test/sealing.rs @@ -233,7 +233,7 @@ fn an_outsider_seal_waits_the_notice_like_any_other() { VaultError::NoticeNotElapsed, ); f.advance(DAY_DURATION); - f.fulfill_epoch_at(sealed, wad(2)); + f.fulfill_epoch_at(sealed, price(2)); assert_eq!( f.vault.get_epoch(&sealed).unwrap().status, EpochStatus::Fulfilled diff --git a/contracts/async-vault/src/test/settlement.rs b/contracts/async-vault/src/test/settlement.rs index a52a58b6..6cd6a828 100644 --- a/contracts/async-vault/src/test/settlement.rs +++ b/contracts/async-vault/src/test/settlement.rs @@ -58,7 +58,7 @@ fn the_last_deposit_claim_clears_the_share_remainder() { let b = f.investor(5); f.vault.request_deposit(&a, &4); f.vault.request_deposit(&b, &5); - let epoch = f.fulfill_epoch(wad(3)); + let epoch = f.fulfill_epoch(price(3)); assert_eq!(f.vault.pending_mint_shares(), 3); assert_eq!(f.vault.claim_deposit(&a, &epoch), 1); @@ -81,7 +81,7 @@ fn the_last_redemption_claim_clears_the_cash_remainder_and_says_so_once() { let b = f.holder(103); f.vault.request_redeem(&a, &101); f.vault.request_redeem(&b, &103); - let epoch = f.fulfill_epoch(wad(3) / 2); + let epoch = f.fulfill_epoch(price(3) / 2); let mut published = reconciliations(&f, epoch); assert_eq!(published, [shares_reconciled(&f, epoch, 0)]); assert_eq!(f.vault.committed(), 306); @@ -123,7 +123,7 @@ fn the_last_redemption_claim_clears_the_cash_remainder_and_says_so_once() { fn an_epoch_with_no_requests_settles_when_it_is_priced() { let f = setup(); let epoch = f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); @@ -132,7 +132,7 @@ fn an_epoch_with_no_requests_settles_when_it_is_priced() { [ EpochFulfilled { epoch, - share_price: wad(2), + share_price: price(2), total_deposited: 0, } .to_xdr(&f.e, &f.vault.address), @@ -151,7 +151,7 @@ fn a_cancelled_request_does_not_hold_the_epoch_open() { let epoch = f.vault.request_deposit(&a, &400); f.vault.cancel_deposit(&a, &epoch); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let s = f.vault.get_epoch_settlement(&epoch).unwrap(); assert_eq!(s.deposits_open, 0); @@ -167,7 +167,7 @@ fn a_deposit_refunded_at_claim_counts_as_settled() { let b = f.investor(3); let epoch = f.vault.request_deposit(&a, &1); f.vault.request_deposit(&b, &3); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); assert_eq!(f.vault.claim_deposit(&a, &epoch), 0); assert_eq!(f.vault.claim_deposit(&b, &epoch), 1); @@ -183,7 +183,7 @@ fn a_redemption_that_pays_nothing_counts_as_settled() { let f = setup(); let a = f.holder(1); let epoch = f.vault.request_redeem(&a, &1); - f.fulfill_epoch(wad(1) / 2); + f.fulfill_epoch(price(1) / 2); assert_eq!(f.vault.claim_redeem(&a, &epoch), 0); @@ -246,7 +246,7 @@ fn a_zero_share_refund_is_paid_once_its_epochs_redemptions_settle() { let epoch = f.vault.request_deposit(&carol, &1); f.vault.request_redeem(&alice, &5); f.vault.request_redeem(&bob, &5); - f.fulfill_epoch(wad(11) / 10); + f.fulfill_epoch(price(11) / 10); assert_eq!(f.balance(&f.vault.address), 11); assert_eq!(f.vault.committed(), 11); @@ -287,7 +287,7 @@ fn mixed_epoch_with_a_remainder_on_each_side(f: &Fixture) -> MixedEpoch { f.vault.request_deposit(&b, &5); f.vault.request_redeem(&x, &101); f.vault.request_redeem(&y, &103); - f.fulfill_epoch(wad(3) / 2); + f.fulfill_epoch(price(3) / 2); MixedEpoch { epoch, depositors: [(a, 2), (b, 3)], @@ -377,7 +377,7 @@ fn each_remainder_leaves_once_whichever_side_settles_last() { let c = f.investor(9); let later = f.vault.request_deposit(&c, &9); f.vault.request_redeem(&z, &7); - f.fulfill_epoch(wad(3) / 2); + f.fulfill_epoch(price(3) / 2); published.extend(reconciliations(&f, m.epoch)); let (later_mint, later_owed) = (6, 10); assert_eq!(f.vault.pending_mint_shares(), 6 + later_mint); @@ -434,7 +434,7 @@ fn a_zero_asset_redemption_the_holder_cannot_take_back_burns_and_settles() { let epoch = f.vault.request_redeem(&delisted, &1); f.vault.request_redeem(&listed, &1); f.vault.request_redeem(&paid, &3); - f.fulfill_epoch(wad(1) / 2); + f.fulfill_epoch(price(1) / 2); f.identity.allow(&delisted, &false); let supply = f.share.total_supply(); @@ -502,7 +502,7 @@ fn a_refused_mint_keeps_a_priced_deposit_epoch_open() { let f = setup(); let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let module = f.e.register(super::compliance::RefusesEveryMint, ()); f.add_compliance_module(ComplianceHook::CanCreate, &module); @@ -557,7 +557,7 @@ proptest! { for (who, shares) in &holders { f.vault.request_redeem(who, shares); } - let price = wad(1) * price_tenths / 10; + let price = price(1) * price_tenths / 10; let epoch = f.fulfill_epoch(price); let mut published = reconciliations(&f, epoch); diff --git a/contracts/async-vault/src/test/setup.rs b/contracts/async-vault/src/test/setup.rs index 012ff91b..2ddbbe29 100644 --- a/contracts/async-vault/src/test/setup.rs +++ b/contracts/async-vault/src/test/setup.rs @@ -54,12 +54,12 @@ fn a_redemption_planted_during_setup_never_reaches_a_depositor() { f.vault.finish_setup(); let investor = f.investor(1_000); - f.attest(wad(1)); + f.attest(price(1)); f.vault.request_deposit(&investor, &100); - let entry = f.fulfill_epoch(wad(1)); + let entry = f.fulfill_epoch(price(1)); assert_eq!(f.vault.claim_deposit(&investor, &entry), 100); f.vault.request_redeem(&investor, &100); - let exit = f.fulfill_epoch(wad(1)); + let exit = f.fulfill_epoch(price(1)); assert_eq!(f.vault.claim_redeem(&investor, &exit), 100); assert_eq!(f.balance(&investor), 1_000); assert_eq!(f.shares(&planter), 0); @@ -81,7 +81,7 @@ fn setup_finishes_once_the_wiring_is_complete() { f.vault.finish_setup(); assert!(!f.vault.setup_open()); - f.attest(wad(1)); + f.attest(price(1)); let investor = f.investor(1_000); f.vault.request_deposit(&investor, &100); } diff --git a/contracts/async-vault/src/test/share_returns.rs b/contracts/async-vault/src/test/share_returns.rs index 0e33c871..89e40b17 100644 --- a/contracts/async-vault/src/test/share_returns.rs +++ b/contracts/async-vault/src/test/share_returns.rs @@ -38,7 +38,7 @@ impl FailsEveryTransferCheck { fn worthless_exit(f: &Fixture) -> (Address, u64) { let holder = f.holder(10); let epoch = f.vault.request_redeem(&holder, &1); - f.fulfill_epoch(WAD_SCALE / 2); + f.fulfill_epoch(PRICE_SCALE / 2); (holder, epoch) } @@ -147,7 +147,7 @@ fn a_token_pause_does_not_stop_a_worthless_exit_coming_back() { let holder = f.holder(10); let epoch = f.vault.request_redeem(&holder, &1); // Priced at half a unit per share, one share pays nothing. - f.fulfill_epoch(WAD_SCALE / 2); + f.fulfill_epoch(PRICE_SCALE / 2); f.share.pause(&f.admin); assert_eq!(f.vault.claim_redeem(&holder, &epoch), 0); @@ -172,7 +172,7 @@ fn a_worthless_exit_the_compliance_rules_refuse_to_return_burns() { let holder = f.holder(10); let epoch = f.vault.request_redeem(&holder, &1); // Priced at half a unit per share, one share pays nothing. - f.fulfill_epoch(WAD_SCALE / 2); + f.fulfill_epoch(PRICE_SCALE / 2); let module = f.e.register(RefusesEveryTransfer, ()); f.add_compliance_module(ComplianceHook::CanTransfer, &module); diff --git a/contracts/async-vault/src/test/signatures.rs b/contracts/async-vault/src/test/signatures.rs index fa95e65f..33385008 100644 --- a/contracts/async-vault/src/test/signatures.rs +++ b/contracts/async-vault/src/test/signatures.rs @@ -103,7 +103,7 @@ fn each_role_call_asks_its_holder_for_one_signature() { "close_epoch", (f.manager.clone(),).into_val(&f.e), ); - f.fulfill_epoch_at(epoch, wad(2)); + f.fulfill_epoch_at(epoch, price(2)); let free = f.vault.free_reserve(); f.vault.deploy_to_custodian(&f.treasury, &free); f.signed_once_by( @@ -164,7 +164,7 @@ fn claim_redeem_asks_the_holder_for_one_signature() { let f = setup(); let holder = f.holder(500); let epoch = f.vault.request_redeem(&holder, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); f.e.set_auths(&[]); missing_auth(f.vault.try_claim_redeem(&holder, &epoch)); diff --git a/contracts/async-vault/src/test/supply.rs b/contracts/async-vault/src/test/supply.rs index dbe46bbc..83c9a8f3 100644 --- a/contracts/async-vault/src/test/supply.rs +++ b/contracts/async-vault/src/test/supply.rs @@ -15,9 +15,9 @@ fn economic_supply_reflects_fulfilled_unminted_deposits() { assert_eq!(f.vault.total_economic_supply(), 0); assert_eq!(f.vault.pending_mint_shares(), 0); - // Close and fulfill epoch at 2.0 WAD (400 assets / 2 = 200 shares owed). + // Close and fulfill epoch at 2.0 (400 assets / 2 = 200 shares owed). f.close_epoch(); - f.fulfill_epoch_at(epoch, wad(2)); + f.fulfill_epoch_at(epoch, price(2)); // Raw total_supply on token is still 0, but economic supply reflects the 200 shares owed. assert_eq!(f.share.total_supply(), 0); @@ -52,7 +52,7 @@ fn economic_supply_excludes_shares_locked_in_redemption_escrow() { // Close and fulfill epoch and claim. f.close_epoch(); - f.fulfill_epoch_at(epoch, wad(2)); + f.fulfill_epoch_at(epoch, price(2)); assert_eq!(f.vault.committed(), 100); f.vault.claim_redeem(&holder, &epoch); @@ -80,9 +80,9 @@ fn economic_supply_combines_circulating_and_pending_mint_correctly() { // Circulating dropped to 60 (100 - 40 in vault). assert_eq!(f.vault.total_economic_supply(), 60); - // Close and fulfill at 1.0 WAD: 300 assets / 1 = 300 shares owed. + // Close and fulfill at 1.0: 300 assets / 1 = 300 shares owed. f.close_epoch(); - f.fulfill_epoch_at(epoch, wad(1)); + f.fulfill_epoch_at(epoch, price(1)); // Economic supply = 60 circulating + 300 pending mint = 360. assert_eq!(f.vault.pending_mint_shares(), 300); diff --git a/contracts/async-vault/src/test/treasury.rs b/contracts/async-vault/src/test/treasury.rs index 1f0373b7..0dfb4d79 100644 --- a/contracts/async-vault/src/test/treasury.rs +++ b/contracts/async-vault/src/test/treasury.rs @@ -12,7 +12,7 @@ fn capital_makes_the_round_trip_to_the_custodian() { // Escrow stays refundable until the epoch prices, so none of it is free. assert_eq!(f.vault.free_reserve(), 0); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); assert_eq!(f.vault.free_reserve(), 1_000); assert_eq!(f.vault.deploy_to_custodian(&f.treasury, &600), 600); @@ -34,7 +34,7 @@ fn returning_more_than_was_deployed_shows_as_negative_net() { let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &1_000); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); f.vault.fulfill_epoch(&epoch); f.vault.deploy_to_custodian(&f.treasury, &600); @@ -50,7 +50,7 @@ fn assets_owed_to_a_priced_redemption_cannot_be_deployed() { let holder = f.holder(500); let epoch = f.vault.request_redeem(&holder, &500); - assert_eq!(f.fulfill_epoch(wad(2)), epoch); + assert_eq!(f.fulfill_epoch(price(2)), epoch); assert_eq!(f.balance(&f.vault.address), 1_000); assert_eq!(f.vault.free_reserve(), 0); @@ -80,10 +80,10 @@ fn a_claim_waits_while_the_capital_is_deployed() { f.empty_reserve(); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); // Pricing does not need the cash back; the claim does. - assert_eq!(f.vault.fulfill_epoch(&epoch), wad(2)); + assert_eq!(f.vault.fulfill_epoch(&epoch), price(2)); assert_eq!(f.vault.uncovered(), 1_000); refused( f.vault.try_claim_redeem(&holder, &epoch), diff --git a/contracts/async-vault/src/test/ttl.rs b/contracts/async-vault/src/test/ttl.rs index e39064c2..fba7f7d6 100644 --- a/contracts/async-vault/src/test/ttl.rs +++ b/contracts/async-vault/src/test/ttl.rs @@ -156,7 +156,7 @@ fn a_pending_request_still_claims_after_most_of_a_month() { f.advance(29 * DAY_DURATION); f.oracle - .attest(&nav_input(&f.e, wad(2), u64::MAX), &f.attester); + .attest(&nav_input(&f.e, price(2), u64::MAX), &f.attester); f.vault.fulfill_epoch(&epoch); assert_eq!(f.vault.claim_deposit(&user, &epoch), 200); @@ -167,7 +167,7 @@ fn a_deposit_claim_writes_the_new_share_balance_with_the_full_ttl() { let f = setup(); let user = f.investor(1_000); let epoch = f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); testnet_minimum(&f.e); f.vault.claim_deposit(&user, &epoch); diff --git a/contracts/async-vault/src/test/upgrade.rs b/contracts/async-vault/src/test/upgrade.rs index 50b62e3b..90df4d14 100644 --- a/contracts/async-vault/src/test/upgrade.rs +++ b/contracts/async-vault/src/test/upgrade.rs @@ -540,7 +540,7 @@ mod with_wasm { 40 ); - f.fulfill_epoch_at(f.close_epoch(), wad(2)); + f.fulfill_epoch_at(f.close_epoch(), price(2)); assert_eq!(f.vault.claim_redeem(&holder, &epoch), 80); assert_eq!(f.vault.claim_deposit(&depositor, &epoch), 250); assert_eq!(f.shares(&depositor), 250); @@ -574,7 +574,7 @@ mod with_wasm { let staying = f.holder(500); let exiting = f.holder(300); let priced = f.vault.request_redeem(&exiting, &100); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let depositor = f.investor(400); let open = f.vault.request_deposit(&depositor, &400); let successor = Address::generate(&f.e); @@ -613,7 +613,7 @@ mod with_wasm { f.vault.apply_change(&queued); assert_eq!(f.vault.custodian(), Some(successor)); assert_eq!(f.close_epoch(), open); - f.fulfill_epoch_at(open, wad(2)); + f.fulfill_epoch_at(open, price(2)); assert_eq!(f.vault.claim_deposit(&depositor, &open), 200); f.vault.activate_wind_down(); assert_eq!(f.vault.finalize_wind_down_round(), 1_800); diff --git a/contracts/async-vault/src/test/wind_down.rs b/contracts/async-vault/src/test/wind_down.rs index bd463bdc..b3a37b7c 100644 --- a/contracts/async-vault/src/test/wind_down.rs +++ b/contracts/async-vault/src/test/wind_down.rs @@ -232,7 +232,7 @@ fn an_active_wind_down_prices_nothing_and_closes_no_epoch() { let epoch = f.close_epoch(); wind_down_now(&f); - f.attest(wad(2)); + f.attest(price(2)); refused( f.vault.try_fulfill_epoch(&epoch), VaultError::WindDownActive, @@ -248,7 +248,7 @@ fn an_active_wind_down_sends_nothing_to_the_custodian() { let f = setup(); let investor = f.investor(1_000); f.vault.request_deposit(&investor, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); wind_down_now(&f); refused( @@ -272,7 +272,7 @@ fn a_priced_claim_still_pays_during_a_wind_down() { let f = setup(); let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); wind_down_now(&f); assert_eq!(f.vault.claim_redeem(&user, &epoch), 400); @@ -283,7 +283,7 @@ fn a_priced_deposit_still_claims_during_a_wind_down() { let f = setup(); let user = f.investor(1_000); let epoch = f.vault.request_deposit(&user, &400); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); wind_down_now(&f); assert_eq!(f.vault.claim_deposit(&user, &epoch), 200); @@ -296,7 +296,7 @@ fn an_epoch_sealed_before_the_announcement_is_still_cancellable() { let investor = f.investor(1_000); let epoch = f.vault.request_deposit(&investor, &400); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); // The price is readable, so without a wind-down this cancel is refused. refused( @@ -316,7 +316,7 @@ fn an_escrowed_redemption_cancelled_in_a_wind_down_joins_the_payout() { let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &200); f.close_epoch(); - f.attest(wad(2)); + f.attest(price(2)); wind_down_now(&f); assert_eq!(f.vault.cancel_redeem(&user, &epoch), 200); @@ -400,7 +400,7 @@ fn a_round_leaves_priced_liabilities_alone() { let f = setup(); let user = f.holder(500); let epoch = f.vault.request_redeem(&user, &200); - f.fulfill_epoch(wad(2)); + f.fulfill_epoch(price(2)); let committed = f.vault.committed(); assert_eq!(committed, 400); first_round_now(&f); @@ -633,7 +633,7 @@ fn a_redemption_that_pays_nothing_returns_no_shares_in_a_wind_down() { let a = f.holder(200); let b = f.holder(200); let epoch = f.vault.request_redeem(&a, &1); - f.fulfill_epoch(WAD_SCALE / 2); + f.fulfill_epoch(PRICE_SCALE / 2); wind_down_now(&f); assert_eq!(f.vault.finalize_wind_down_round(), 800); @@ -654,7 +654,7 @@ fn a_delisted_holders_worthless_redemption_burns_in_a_wind_down() { let a = f.holder(200); let b = f.holder(200); let epoch = f.vault.request_redeem(&a, &1); - f.fulfill_epoch(WAD_SCALE / 2); + f.fulfill_epoch(PRICE_SCALE / 2); wind_down_now(&f); f.vault.finalize_wind_down_round(); f.identity.allow(&a, &false); @@ -703,7 +703,7 @@ fn a_zero_share_refund_is_refused_once_a_round_has_taken_the_reserve() { let epoch = f.vault.request_deposit(&investor, &1); f.close_epoch(); // A price high enough that one unit of the asset buys no shares at all. - f.fulfill_epoch_at(epoch, wad(2)); + f.fulfill_epoch_at(epoch, price(2)); first_round_now(&f); // Known limit: the refund is not tracked as a liability, so a round can @@ -816,7 +816,7 @@ fn redemption_priced_before_wind_down_is_excluded_from_snapshot() { let u2 = f.holder(500); let epoch = f.vault.request_redeem(&u2, &200); - f.fulfill_epoch(wad(1)); + f.fulfill_epoch(price(1)); assert_eq!(f.vault.pending_burn_shares(), 200); wind_down_now(&f); diff --git a/contracts/nav-oracle/src/lib.rs b/contracts/nav-oracle/src/lib.rs index 1cdcf257..6f306e6a 100644 --- a/contracts/nav-oracle/src/lib.rs +++ b/contracts/nav-oracle/src/lib.rs @@ -51,7 +51,7 @@ use soroban_sdk::{ use stellar_access::access_control::{self, AccessControl}; use stellar_contract_utils::upgradeable; use stellar_macros::{only_admin, only_role}; -use strata_bindings::{OracleFeed, VaultBinding}; +use strata_bindings::{OracleFeed, VaultBinding, PRICE_SCALE}; use state::{get_config, get_latest, nav_paused, ATTESTER_ROLE, GUARDIAN_ROLE}; @@ -61,7 +61,6 @@ pub use governance::{ pub use state::{NavInput, NavReport, OracleConfig, OracleState}; const BPS_DENOM: i128 = 10_000; -const WAD: i128 = 1_000_000_000_000_000_000; /// One report per ledger at most. A deployment sets a longer cooldown. pub const MIN_COOLDOWN_SECS: u64 = 1; @@ -69,11 +68,11 @@ pub const MIN_COOLDOWN_SECS: u64 = 1; pub const MAX_FRESHNESS_SECS: u64 = 35 * strata_timelock::DAY_DURATION; /// A million units of the asset per share. Far above any real price, and far /// below where the deviation arithmetic could overflow. -pub const MAX_ANSWER: i128 = 1_000_000 * WAD; +pub const MAX_ANSWER: i128 = 1_000_000 * PRICE_SCALE; /// A millionth of an asset unit per share, mirroring `MAX_ANSWER`. At it, one /// asset base unit mints at most a million share base units, and a 1 bps /// move cap still allows a move. -pub const MIN_ANSWER: i128 = WAD / 1_000_000; +pub const MIN_ANSWER: i128 = PRICE_SCALE / 1_000_000; /// Longest proof URI an attestation may carry, in bytes. pub const MAX_PROOF_URI_LEN: u32 = 256; @@ -561,7 +560,7 @@ impl NavOracleContract { governance::pending(e) } - /// The stored report: `nav_per_share` in WAD, `accepted_at` and + /// The stored report: `nav_per_share` at 14 decimals, `accepted_at` and /// `expires_at` in seconds, and the proof the attester gave with it, /// `proof_hash` and `proof_uri`. /// @@ -597,8 +596,8 @@ impl NavOracleContract { /// /// # Arguments /// - /// * `input` - `nav_per_share` in WAD: asset base units per share base - /// unit. `expires_at` in seconds: the attester's own expiry. + /// * `input` - `nav_per_share` at 14 decimals: asset base units per + /// share base unit. `expires_at` in seconds: the attester's own expiry. /// `proof_hash` hashes the evidence; `proof_uri` says where to read it, /// or is empty. /// * `caller` - An `attester`. @@ -609,7 +608,7 @@ impl NavOracleContract { /// * `NavPaused` - The NAV is paused. /// * `NavOutOfBand` - `nav_per_share` is outside the band. /// * `ExpiresInPast`, `ExpiresBeforeCooldown` - `expires_at` is not in the - /// future, or its expiry falls inside the cooldown. + /// future, or falls inside the cooldown. /// * `EmptyProofHash` - `proof_hash` is all zeros. /// * `ProofUriTooLong` - `proof_uri` is over 256 bytes. /// * `CooldownActive` - The last report is younger than `cooldown_secs`. @@ -726,7 +725,7 @@ impl NavOracleContract { /// The limits a report must meet: `freshness_duration` and /// `cooldown_secs` in seconds, `max_up_bps` and `max_down_bps` in basis - /// points, `min_answer` and `max_answer` in WAD. + /// points, `min_answer` and `max_answer` at 14 decimals. pub fn config(e: &Env) -> OracleConfig { get_config(e) } @@ -769,8 +768,8 @@ impl OracleFeed for NavOracleContract { compute_state(e) } - /// The stored report's value in WAD: asset base units per share base - /// unit. + /// The stored report's value at 14 decimals: asset base units per share + /// base unit. /// /// # Errors /// diff --git a/contracts/nav-oracle/src/state.rs b/contracts/nav-oracle/src/state.rs index 3137a097..5390a7de 100644 --- a/contracts/nav-oracle/src/state.rs +++ b/contracts/nav-oracle/src/state.rs @@ -58,7 +58,7 @@ pub struct OracleConfig { /// Downward move allowed per attestation, 1 to 10,000. At 10,000 a loss of /// any size lands in one attestation and `min_answer` is the only floor. pub max_down_bps: u32, - /// The lowest valid price, in WAD; at least `MIN_ANSWER`. + /// The lowest valid price, at 14 decimals; at least `MIN_ANSWER`. pub min_answer: i128, pub max_answer: i128, } diff --git a/contracts/nav-oracle/src/test/governance.rs b/contracts/nav-oracle/src/test/governance.rs index 64d8acfd..246dba6c 100644 --- a/contracts/nav-oracle/src/test/governance.rs +++ b/contracts/nav-oracle/src/test/governance.rs @@ -13,6 +13,7 @@ use stellar_access::access_control::{ AccessControlError, AccessControlStorageKey, ROLE_EXTEND_AMOUNT, }; use stellar_access::role_transfer::RoleTransferError; +use strata_bindings::PRICE_SCALE; use strata_storage::INSTANCE_EXTEND_AMOUNT; use strata_timelock::{Clock, DAY_DURATION, MIN_DELAY}; @@ -25,7 +26,6 @@ use crate::{ use super::{missing_auth, refused}; -const SCALE: i128 = 1_000_000_000_000_000_000; const TWO_DAYS_IN_LEDGERS: u32 = 2 * 17_280; /// Testnet's minimum lifetime of a new persistent entry, in ledgers. const TESTNET_MIN_PERSISTENT_TTL: u32 = 120_960; @@ -166,8 +166,8 @@ fn config() -> OracleConfig { cooldown_secs: 60, max_up_bps: 1_000, max_down_bps: 1_000, - min_answer: SCALE / 2, - max_answer: SCALE * 100, + min_answer: PRICE_SCALE / 2, + max_answer: PRICE_SCALE * 100, } } @@ -250,19 +250,19 @@ fn only_a_shorter_freshness_window_is_instant() { ..config() }, OracleConfig { - min_answer: SCALE, + min_answer: PRICE_SCALE, ..config() }, OracleConfig { - min_answer: SCALE / 4, + min_answer: PRICE_SCALE / 4, ..config() }, OracleConfig { - max_answer: SCALE * 50, + max_answer: PRICE_SCALE * 50, ..config() }, OracleConfig { - max_answer: SCALE * 200, + max_answer: PRICE_SCALE * 200, ..config() }, OracleConfig { @@ -378,7 +378,7 @@ fn a_tighter_cap_or_band_waits_after_setup() { ..config() }, OracleConfig { - min_answer: SCALE, + min_answer: PRICE_SCALE, ..config() }, ] { @@ -612,7 +612,7 @@ fn revoking_an_attester_or_a_guardian_stays_instant_after_setup() { assert!(f.oracle.has_role(&f.attester, &ATTESTER_ROLE).is_none()); assert!(f.oracle.has_role(&f.guardian, &GUARDIAN_ROLE).is_none()); assert_eq!( - f.oracle.try_attest(&input(&f.e, SCALE), &f.attester), + f.oracle.try_attest(&input(&f.e, PRICE_SCALE), &f.attester), Err(Ok(AccessControlError::Unauthorized.into())) ); assert_eq!( @@ -737,7 +737,7 @@ fn the_hand_over_offer_lasts_seven_days_of_ledgers() { #[test] fn the_nav_pause_and_clearing_stay_instant_after_setup() { let f = setup(); - f.attest(SCALE); + f.attest(PRICE_SCALE); f.finish(); f.oracle.pause_nav(&f.guardian); @@ -1129,11 +1129,11 @@ fn each_role_call_asks_its_holder_for_one_signature() { let f = setup(); let next = Address::generate(&f.e); - f.oracle.attest(&input(&f.e, SCALE), &f.attester); + f.oracle.attest(&input(&f.e, PRICE_SCALE), &f.attester); f.signed_once_by( &f.attester, "attest", - (input(&f.e, SCALE), f.attester.clone()).into_val(&f.e), + (input(&f.e, PRICE_SCALE), f.attester.clone()).into_val(&f.e), ); f.oracle.pause_nav(&f.guardian); f.signed_once_by( @@ -1217,7 +1217,7 @@ mod with_wasm { #[test] fn the_oracle_upgrades_under_a_live_valuation() { let f = setup_with(|e, args| e.register(oracle_v1::WASM, args)); - f.attest(SCALE); + f.attest(PRICE_SCALE); f.finish(); let probe_hash = f.e.deployer().upload_contract_wasm(oracle_probe::WASM); let id = f.propose(OracleChange::Upgrade(probe_hash)); @@ -1238,7 +1238,7 @@ mod with_wasm { let kept = f.oracle.latest(); assert_eq!( (kept.nav_per_share, kept.accepted_at, kept.expires_at), - (SCALE, 10_000, 10_000 + config().freshness_duration) + (PRICE_SCALE, 10_000, 10_000 + config().freshness_duration) ); assert_eq!(kept.proof_hash, proof(&f.e)); assert_eq!(f.oracle.config(), config()); @@ -1247,8 +1247,8 @@ mod with_wasm { assert!(!f.oracle.setup_open()); assert_eq!(f.oracle.pending_changes().len(), 0); - f.attest(SCALE + SCALE / 20); - assert_eq!(f.oracle.nav_per_share(), SCALE + SCALE / 20); + f.attest(PRICE_SCALE + PRICE_SCALE / 20); + assert_eq!(f.oracle.nav_per_share(), PRICE_SCALE + PRICE_SCALE / 20); f.oracle.pause_nav(&f.guardian); assert_eq!(f.oracle.state(), OracleState::Paused); } diff --git a/contracts/nav-oracle/src/test/guards.rs b/contracts/nav-oracle/src/test/guards.rs index db2bc563..5bb143db 100644 --- a/contracts/nav-oracle/src/test/guards.rs +++ b/contracts/nav-oracle/src/test/guards.rs @@ -6,6 +6,7 @@ use soroban_sdk::{ testutils::{Address as _, Ledger as _}, Address, BytesN, Env, InvokeError, String, }; +use strata_bindings::PRICE_SCALE; use strata_timelock::{Clock, MIN_DELAY}; use crate::guards; @@ -14,8 +15,6 @@ use crate::{ OracleError, MAX_ANSWER, MAX_FRESHNESS_SECS, MAX_PROOF_URI_LEN, MIN_ANSWER, }; -const SCALE: i128 = 1_000_000_000_000_000_000; - /// Plays the vault: the oracle binds only to an address that reports a clock. #[contract] struct VaultStub; @@ -66,8 +65,8 @@ fn config() -> OracleConfig { cooldown_secs: 60, max_up_bps: 1_000, max_down_bps: 1_000, - min_answer: SCALE / 2, - max_answer: SCALE * 100, + min_answer: PRICE_SCALE / 2, + max_answer: PRICE_SCALE * 100, } } @@ -153,7 +152,7 @@ fn valid_config_refuses_a_config_outside_the_bounds() { ..config() }, OracleConfig { - max_answer: SCALE / 4, + max_answer: PRICE_SCALE / 4, ..config() }, OracleConfig { @@ -291,7 +290,7 @@ fn consumable_refuses_a_feed_that_is_not_valid() { let f = setup(); refuses(&f, OracleError::NotConsumable, || guards::consumable(&f.e)); - f.attest(SCALE); + f.attest(PRICE_SCALE); holds(&f, || guards::consumable(&f.e)); f.oracle.pause_nav(&f.guardian); @@ -371,8 +370,8 @@ fn cooldown_elapsed_refuses_a_report_inside_the_cooldown() { let f = setup(); let cfg = config(); let now = f.e.ledger().timestamp(); - let elapsed = report_at(&f.e, SCALE, now - cfg.cooldown_secs); - let running = report_at(&f.e, SCALE, now - cfg.cooldown_secs + 1); + let elapsed = report_at(&f.e, PRICE_SCALE, now - cfg.cooldown_secs); + let running = report_at(&f.e, PRICE_SCALE, now - cfg.cooldown_secs + 1); holds(&f, || guards::cooldown_elapsed(&f.e, &cfg, &elapsed)); refuses(&f, OracleError::CooldownActive, || { @@ -384,19 +383,19 @@ fn cooldown_elapsed_refuses_a_report_inside_the_cooldown() { fn within_deviation_refuses_a_move_past_either_cap() { let f = setup(); let cfg = config(); - let last = report_at(&f.e, SCALE, 0); - let ten_percent = SCALE / 10; + let last = report_at(&f.e, PRICE_SCALE, 0); + let ten_percent = PRICE_SCALE / 10; holds(&f, || { - guards::within_deviation(&f.e, &cfg, &last, SCALE + ten_percent) + guards::within_deviation(&f.e, &cfg, &last, PRICE_SCALE + ten_percent) }); holds(&f, || { - guards::within_deviation(&f.e, &cfg, &last, SCALE - ten_percent) + guards::within_deviation(&f.e, &cfg, &last, PRICE_SCALE - ten_percent) }); refuses(&f, OracleError::DeviationExceeded, || { - guards::within_deviation(&f.e, &cfg, &last, SCALE + ten_percent + 1) + guards::within_deviation(&f.e, &cfg, &last, PRICE_SCALE + ten_percent + 1) }); refuses(&f, OracleError::DeviationExceeded, || { - guards::within_deviation(&f.e, &cfg, &last, SCALE - ten_percent - 1) + guards::within_deviation(&f.e, &cfg, &last, PRICE_SCALE - ten_percent - 1) }); } diff --git a/contracts/nav-oracle/src/test/oracle.rs b/contracts/nav-oracle/src/test/oracle.rs index af789aec..930a1a00 100644 --- a/contracts/nav-oracle/src/test/oracle.rs +++ b/contracts/nav-oracle/src/test/oracle.rs @@ -9,6 +9,7 @@ use soroban_sdk::{ }; use stellar_access::access_control::AccessControlError; +use strata_bindings::PRICE_SCALE; use crate::state::DataKey; use crate::{ @@ -17,7 +18,6 @@ use crate::{ use super::{missing_auth, refused}; -const SCALE: i128 = 1_000_000_000_000_000_000; const DAY_IN_LEDGERS: u32 = 17_280; struct Fixture<'a> { @@ -50,8 +50,8 @@ fn config() -> OracleConfig { cooldown_secs: 60, max_up_bps: 1_000, max_down_bps: 1_000, // 10% - min_answer: SCALE / 2, - max_answer: SCALE * 100, + min_answer: PRICE_SCALE / 2, + max_answer: PRICE_SCALE * 100, } } @@ -98,18 +98,18 @@ fn attest_then_valid_and_consumable() { assert_eq!(f.oracle.state(), OracleState::Stale); assert!(f.oracle.is_stale()); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); - assert_eq!(f.oracle.nav_per_share(), SCALE); + assert_eq!(f.oracle.nav_per_share(), PRICE_SCALE); f.oracle.ensure_consumable(); // must not panic } #[test] fn heartbeat_expiry_makes_it_stale() { let f = setup(); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); @@ -122,7 +122,7 @@ fn heartbeat_expiry_makes_it_stale() { #[test] fn the_nav_pause_holds_regardless_of_freshness() { let f = setup(); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); @@ -138,7 +138,7 @@ fn the_nav_pause_holds_regardless_of_freshness() { fn attest_rejects_out_of_band() { let f = setup(); // Below min_answer. - let r = input(&f.e, SCALE / 4, 1_000_000); + let r = input(&f.e, PRICE_SCALE / 4, 1_000_000); refused( f.oracle.try_attest(&r, &f.attester), OracleError::NavOutOfBand, @@ -154,12 +154,12 @@ fn attest_rejects_out_of_band() { #[test] fn attest_enforces_cooldown_and_deviation() { let f = setup(); - let r1 = input(&f.e, SCALE, 1_000_000); + let r1 = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r1, &f.attester); // Cooldown: only 30s later (< 60), reject. f.e.ledger().set_timestamp(10_030); - let r2 = input(&f.e, SCALE, 1_000_000); + let r2 = input(&f.e, PRICE_SCALE, 1_000_000); refused( f.oracle.try_attest(&r2, &f.attester), OracleError::CooldownActive, @@ -168,16 +168,16 @@ fn attest_enforces_cooldown_and_deviation() { // Past cooldown now. f.e.ledger().set_timestamp(10_100); // Deviation: +20% exceeds the 10% cap. - let big = input(&f.e, SCALE + SCALE / 5, 1_000_000); + let big = input(&f.e, PRICE_SCALE + PRICE_SCALE / 5, 1_000_000); refused( f.oracle.try_attest(&big, &f.attester), OracleError::DeviationExceeded, ); // Valid update: +5% within cap. - let ok = input(&f.e, SCALE + SCALE / 20, 1_000_000); + let ok = input(&f.e, PRICE_SCALE + PRICE_SCALE / 20, 1_000_000); f.oracle.attest(&ok, &f.attester); - assert_eq!(f.oracle.nav_per_share(), SCALE + SCALE / 20); + assert_eq!(f.oracle.nav_per_share(), PRICE_SCALE + PRICE_SCALE / 20); } /// The contract stamps ledger time and derives `expires_at` from its own @@ -185,7 +185,7 @@ fn attest_enforces_cooldown_and_deviation() { #[test] fn attest_stamps_its_own_timestamp() { let f = setup(); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); let stored = f.oracle.latest(); @@ -196,13 +196,14 @@ fn attest_stamps_its_own_timestamp() { #[test] fn attesting_publishes_the_stored_valuation() { let f = setup(); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); assert_eq!( f.e.events().all().filter_by_contract(&f.oracle.address), [crate::NavAttested { attester: f.attester.clone(), - nav_per_share: SCALE, + nav_per_share: PRICE_SCALE, expires_at: 10_000 + 3600, proof_hash: proof(&f.e), proof_uri: String::from_str(&f.e, "ipfs://strata-proof"), @@ -214,7 +215,8 @@ fn attesting_publishes_the_stored_valuation() { #[test] fn the_latest_valuation_keeps_a_full_ttl_while_it_is_read() { let f = setup(); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); f.e.ledger() .with_mut(|l| l.sequence_number += 2 * DAY_IN_LEDGERS); @@ -234,7 +236,7 @@ fn the_latest_valuation_keeps_a_full_ttl_while_it_is_read() { #[test] fn set_config_takes_effect() { let f = setup(); - let r1 = input(&f.e, SCALE, 1_000_000); + let r1 = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r1, &f.attester); // Tighten the per-attestation deviation band to 1%; a subsequent +5% move @@ -247,7 +249,7 @@ fn set_config_takes_effect() { f.oracle.set_config(&tight); f.e.ledger().set_timestamp(10_100); - let five_pct = input(&f.e, SCALE + SCALE / 20, 1_000_000); + let five_pct = input(&f.e, PRICE_SCALE + PRICE_SCALE / 20, 1_000_000); refused( f.oracle.try_attest(&five_pct, &f.attester), OracleError::DeviationExceeded, @@ -258,7 +260,7 @@ fn set_config_takes_effect() { fn attest_is_role_gated() { let f = setup(); let stranger = Address::generate(&f.e); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); assert_eq!( f.oracle.try_attest(&r, &stranger), Err(Ok(AccessControlError::Unauthorized.into())) @@ -268,12 +270,12 @@ fn attest_is_role_gated() { #[test] fn narrowing_the_band_demotes_a_stored_record() { let f = setup(); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); let narrow = OracleConfig { - max_answer: SCALE / 2, + max_answer: PRICE_SCALE / 2, ..config() }; f.oracle.set_config(&narrow); @@ -351,7 +353,7 @@ fn only_admin_can_set_config() { #[test] fn the_guardian_pauses_the_nav_but_unpausing_needs_governance() { let f = setup(); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); @@ -412,13 +414,14 @@ fn a_full_downside_cap_lets_a_large_loss_land_at_once() { cfg.max_down_bps = 10_000; let f = setup_with(cfg); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); f.e.ledger().set_timestamp(10_100); // A 40% fall, far past the 10% upward cap, is admitted at once. - let crash = input(&f.e, SCALE * 60 / 100, 1_000_000); + let crash = input(&f.e, PRICE_SCALE * 60 / 100, 1_000_000); f.oracle.attest(&crash, &f.attester); - assert_eq!(f.oracle.nav_per_share(), SCALE * 60 / 100); + assert_eq!(f.oracle.nav_per_share(), PRICE_SCALE * 60 / 100); } #[test] @@ -427,10 +430,11 @@ fn a_full_downside_cap_still_bounds_a_rise() { cfg.max_down_bps = 10_000; let f = setup_with(cfg); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); f.e.ledger().set_timestamp(10_100); - let spike = input(&f.e, SCALE * 140 / 100, 1_000_000); + let spike = input(&f.e, PRICE_SCALE * 140 / 100, 1_000_000); refused( f.oracle.try_attest(&spike, &f.attester), OracleError::DeviationExceeded, @@ -441,10 +445,11 @@ fn a_full_downside_cap_still_bounds_a_rise() { fn a_configured_downside_still_bounds_a_fall() { let f = setup(); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); f.e.ledger().set_timestamp(10_100); - let crash = input(&f.e, SCALE * 60 / 100, 1_000_000); + let crash = input(&f.e, PRICE_SCALE * 60 / 100, 1_000_000); refused( f.oracle.try_attest(&crash, &f.attester), OracleError::DeviationExceeded, @@ -469,7 +474,8 @@ fn constructor_rejects_a_zero_upside_cap() { #[test] fn the_record_clears_only_while_the_nav_is_paused() { let f = setup(); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); refused(f.oracle.try_clear_latest(), OracleError::NavNotPaused); @@ -479,16 +485,16 @@ fn the_record_clears_only_while_the_nav_is_paused() { // With no stored record, one in-band value lands however far it sits. f.oracle.set_nav_paused(&false); f.e.ledger().set_timestamp(10_100); - let far = input(&f.e, SCALE * 50, 1_000_000); + let far = input(&f.e, PRICE_SCALE * 50, 1_000_000); f.oracle.attest(&far, &f.attester); - assert_eq!(f.oracle.nav_per_share(), SCALE * 50); + assert_eq!(f.oracle.nav_per_share(), PRICE_SCALE * 50); } #[test] fn only_admin_can_clear_latest() { let f = setup(); let stranger = Address::generate(&f.e); - let r = input(&f.e, SCALE, 1_000_000); + let r = input(&f.e, PRICE_SCALE, 1_000_000); f.oracle.attest(&r, &f.attester); f.oracle.pause_nav(&f.guardian); @@ -535,7 +541,8 @@ fn a_full_downside_cap_leaves_min_answer_as_the_only_floor() { cfg.max_down_bps = 10_000; let f = setup_with(cfg); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); f.e.ledger().set_timestamp(10_100); // Straight to the floor in one step, whatever the distance. @@ -555,7 +562,7 @@ fn a_full_downside_cap_leaves_min_answer_as_the_only_floor() { #[test] fn a_floor_below_a_millionth_of_an_asset_unit_per_share_is_refused() { let f = setup(); - assert_eq!(crate::MIN_ANSWER, 1_000_000_000_000); + assert_eq!(crate::MIN_ANSWER, 100_000_000); assert_eq!( f.oracle .try_set_config(&OracleConfig { @@ -596,7 +603,8 @@ fn attested_at_is_when_the_contract_took_the_report() { let f = setup(); f.e.ledger().set_timestamp(50_000); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); assert_eq!(f.oracle.attested_at(), 50_000); } @@ -612,7 +620,7 @@ fn attested_at_without_a_report_is_refused() { fn a_reporter_expiry_inside_the_window_is_kept() { let f = setup(); f.oracle - .attest(&input(&f.e, SCALE, 10_000 + 600), &f.attester); + .attest(&input(&f.e, PRICE_SCALE, 10_000 + 600), &f.attester); assert_eq!(f.oracle.latest().expires_at, 10_000 + 600); f.e.ledger().set_timestamp(10_000 + 601); @@ -623,7 +631,7 @@ fn a_reporter_expiry_inside_the_window_is_kept() { fn a_reporter_expiry_past_the_window_is_cut_to_the_window() { let f = setup(); f.oracle - .attest(&input(&f.e, SCALE, 10_000 + 10_000), &f.attester); + .attest(&input(&f.e, PRICE_SCALE, 10_000 + 10_000), &f.attester); assert_eq!(f.oracle.latest().expires_at, 10_000 + 3600); } @@ -634,7 +642,7 @@ fn an_expiry_inside_its_own_cooldown_is_refused() { // cooldown_secs = 60: an expiry one second short of it is refused. refused( f.oracle - .try_attest(&input(&f.e, SCALE, 10_000 + 59), &f.attester), + .try_attest(&input(&f.e, PRICE_SCALE, 10_000 + 59), &f.attester), OracleError::ExpiresBeforeCooldown, ); } @@ -643,7 +651,7 @@ fn an_expiry_inside_its_own_cooldown_is_refused() { fn an_expiry_exactly_at_the_cooldown_is_accepted() { let f = setup(); f.oracle - .attest(&input(&f.e, SCALE, 10_000 + 60), &f.attester); + .attest(&input(&f.e, PRICE_SCALE, 10_000 + 60), &f.attester); assert_eq!(f.oracle.latest().expires_at, 10_000 + 60); } @@ -651,7 +659,7 @@ fn an_expiry_exactly_at_the_cooldown_is_accepted() { fn a_lapsed_report_is_refreshed_at_once_with_no_cooldown_wait() { let f = setup(); f.oracle - .attest(&input(&f.e, SCALE, 10_000 + 60), &f.attester); + .attest(&input(&f.e, PRICE_SCALE, 10_000 + 60), &f.attester); f.e.ledger().set_timestamp(10_000 + 61); assert_eq!(f.oracle.state(), OracleState::Stale); @@ -659,7 +667,7 @@ fn a_lapsed_report_is_refreshed_at_once_with_no_cooldown_wait() { // The cooldown has also elapsed by the moment the report lapses, so the // next one is accepted at once. f.oracle - .attest(&input(&f.e, SCALE, 10_000 + 61 + 60), &f.attester); + .attest(&input(&f.e, PRICE_SCALE, 10_000 + 61 + 60), &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); } @@ -670,13 +678,14 @@ fn attesting_is_refused_while_the_nav_is_paused() { assert_eq!( f.oracle - .try_attest(&input(&f.e, SCALE, 1_000_000), &f.attester) + .try_attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester) .err(), Some(Ok(crate::OracleError::NavPaused.into())) ); f.oracle.set_nav_paused(&false); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); assert_eq!(f.oracle.state(), OracleState::Valid); } @@ -685,18 +694,20 @@ fn two_reports_in_one_ledger_are_refused_at_the_shortest_cooldown() { let mut cfg = config(); cfg.cooldown_secs = crate::MIN_COOLDOWN_SECS; let f = setup_with(cfg); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); assert_eq!( f.oracle - .try_attest(&input(&f.e, SCALE, 1_000_000), &f.attester) + .try_attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester) .err(), Some(Ok(crate::OracleError::CooldownActive.into())) ); f.e.ledger() .set_timestamp(10_000 + crate::MIN_COOLDOWN_SECS); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); } fn refuses_config(cfg: OracleConfig) { @@ -768,12 +779,13 @@ fn implements_the_feed() {} fn the_oracle_answers_the_feed_interface_the_vault_reads() { implements_the_feed::(); let f = setup(); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); let feed = strata_bindings::OracleFeedClient::new(&f.e, &f.oracle.address); assert_eq!(feed.state(), OracleState::Valid); - assert_eq!(feed.nav_per_share(), SCALE); + assert_eq!(feed.nav_per_share(), PRICE_SCALE); assert_eq!(feed.attested_at(), 10_000); assert_eq!(feed.freshness_duration(), 3600); } @@ -802,7 +814,8 @@ mod proof_reference { fn the_latest_report_carries_its_proof() { let f = setup(); - f.oracle.attest(&input(&f.e, SCALE, 1_000_000), &f.attester); + f.oracle + .attest(&input(&f.e, PRICE_SCALE, 1_000_000), &f.attester); let latest = f.oracle.latest(); assert_eq!(latest.proof_hash, proof(&f.e)); @@ -815,7 +828,7 @@ mod proof_reference { #[test] fn a_report_without_a_proof_hash_is_refused() { let f = setup(); - let mut unproven = input(&f.e, SCALE, 1_000_000); + let mut unproven = input(&f.e, PRICE_SCALE, 1_000_000); unproven.proof_hash = BytesN::from_array(&f.e, &[0; 32]); assert_eq!( @@ -827,7 +840,7 @@ mod proof_reference { #[test] fn a_proof_uri_past_the_limit_is_refused() { let f = setup(); - let mut long = input(&f.e, SCALE, 1_000_000); + let mut long = input(&f.e, PRICE_SCALE, 1_000_000); long.proof_uri = String::from_bytes(&f.e, &[b'x'; (MAX_PROOF_URI_LEN + 1) as usize]); assert_eq!( @@ -839,7 +852,7 @@ mod proof_reference { #[test] fn a_proof_uri_at_the_limit_is_stored_and_published() { let f = setup(); - let mut longest = input(&f.e, SCALE, 1_000_000); + let mut longest = input(&f.e, PRICE_SCALE, 1_000_000); longest.proof_uri = String::from_bytes(&f.e, &[b'x'; MAX_PROOF_URI_LEN as usize]); f.oracle.attest(&longest, &f.attester); @@ -848,7 +861,7 @@ mod proof_reference { f.e.events().all().filter_by_contract(&f.oracle.address), [crate::NavAttested { attester: f.attester.clone(), - nav_per_share: SCALE, + nav_per_share: PRICE_SCALE, expires_at: 10_000 + 3600, proof_hash: proof(&f.e), proof_uri: longest.proof_uri.clone(), @@ -861,7 +874,7 @@ mod proof_reference { #[test] fn a_hash_without_a_uri_is_enough() { let f = setup(); - let mut bare = input(&f.e, SCALE, 1_000_000); + let mut bare = input(&f.e, PRICE_SCALE, 1_000_000); bare.proof_uri = String::from_str(&f.e, ""); f.oracle.attest(&bare, &f.attester); @@ -890,7 +903,7 @@ mod proof_reference { f.e.storage().persistent().set( &DataKey::Latest, &EarlierNavReport { - nav_per_share: SCALE, + nav_per_share: PRICE_SCALE, expires_at: 10_000 + 3600, timestamp: 10_000, }, @@ -898,7 +911,7 @@ mod proof_reference { }); // Past the cooldown and inside the cap: only the old entry can refuse it. f.e.ledger().set_timestamp(10_100); - let next = input(&f.e, SCALE + SCALE / 20, 1_000_000); + let next = input(&f.e, PRICE_SCALE + PRICE_SCALE / 20, 1_000_000); assert_eq!(f.oracle.try_latest().err(), Some(Ok(host_refusal()))); assert_eq!(f.oracle.try_state().err(), Some(Ok(host_refusal()))); @@ -914,7 +927,7 @@ mod proof_reference { f.oracle.attest(&next, &f.attester); let latest = f.oracle.latest(); - assert_eq!(latest.nav_per_share, SCALE + SCALE / 20); + assert_eq!(latest.nav_per_share, PRICE_SCALE + PRICE_SCALE / 20); assert_eq!(latest.accepted_at, 10_100); assert_eq!(latest.proof_hash, proof(&f.e)); assert_eq!( diff --git a/contracts/sep40-feed/src/lib.rs b/contracts/sep40-feed/src/lib.rs index e24bbab3..38383b59 100644 --- a/contracts/sep40-feed/src/lib.rs +++ b/contracts/sep40-feed/src/lib.rs @@ -13,10 +13,10 @@ //! - **A failing read is no price.** A read that fails, the vault's or the //! oracle's, answers as if no price exists. The cost: a broken oracle looks //! like a missing price. -//! - **Fourteen decimals at the edge, WAD inside.** Every price lands in -//! `DECIMALS` (14); the vault's NAV stays in WAD (18) until then. The cost: -//! precision below 10^-14 is lost, and a price that floors to zero is no -//! price. +//! - **The NAV as is.** The NAV already carries the 14 decimals Stellar +//! feeds use, so when the asset and the share have the same decimals the +//! feed answers it unchanged. The cost: other decimals shift it by a power +//! of ten, and a price that floors to zero is no price. //! - **Resolution is the freshness window.** `resolution` answers the //! oracle's `freshness_duration`, and a price's own timestamp is not //! rounded to it. The cost: the resolution moves with the oracle, against @@ -40,11 +40,10 @@ use sep40::{Asset, PriceData, PriceFeed}; use soroban_sdk::{ contract, contracterror, contractevent, contractimpl, panic_with_error, vec, Address, Env, Vec, }; -use strata_bindings::{VaultBinding, VaultViewClient}; +use strata_bindings::{VaultBinding, VaultViewClient, PRICE_DECIMALS}; use strata_timelock::{setup, Clock, Refusal, TimelockHost}; pub use governance::{FeedChange, FeedPendingChange}; -pub use price::{DECIMALS, ONE}; strata_bindings::error_enum! { strata_bindings::FEED_ERRORS, @@ -260,9 +259,9 @@ impl PriceFeed for Sep40Feed { ] } - /// Decimal places every price carries: always `DECIMALS` (14). + /// Decimal places every price carries: always 14. fn decimals(_e: &Env) -> u32 { - DECIMALS + PRICE_DECIMALS } /// Seconds a report stays current: the vault's current oracle's @@ -274,8 +273,8 @@ impl PriceFeed for Sep40Feed { quote::resolution(e) } - /// The price of `asset` at `timestamp`, in `DECIMALS`, if the standing - /// report covered that second. + /// The price of `asset` at `timestamp`, with 14 decimals, if the + /// standing report covered that second. /// /// # Arguments /// @@ -290,9 +289,9 @@ impl PriceFeed for Sep40Feed { quote::at(e, &asset, timestamp) } - /// Up to `records` most recent prices of `asset`, in `DECIMALS`, newest - /// first. The feed keeps no history, so this is `lastprice` alone, or - /// `None` when `records` is `0`. + /// Up to `records` most recent prices of `asset`, with 14 decimals, + /// newest first. The feed keeps no history, so this is `lastprice` alone, + /// or `None` when `records` is `0`. /// /// # Arguments /// @@ -305,8 +304,8 @@ impl PriceFeed for Sep40Feed { quote::latest(e, &asset).map(|data| vec![e, data]) } - /// The most recent price of `asset`, in `DECIMALS`, timestamped at the - /// report's attestation time. + /// The most recent price of `asset`, with 14 decimals, timestamped at + /// the report's attestation time. /// /// # Arguments /// diff --git a/contracts/sep40-feed/src/price.rs b/contracts/sep40-feed/src/price.rs index d5e8ba54..49d22d93 100644 --- a/contracts/sep40-feed/src/price.rs +++ b/contracts/sep40-feed/src/price.rs @@ -1,14 +1,6 @@ -/// The kit's NAV scale. -const WAD_DECIMALS: u32 = 18; -/// SEP-40 price decimals the feed answers. -pub const DECIMALS: u32 = 14; -/// One unit of the feed's price, at `DECIMALS`. -pub const ONE: i128 = 10i128.pow(DECIMALS); - -/// The gap between the kit's WAD and the feed's `DECIMALS`. -const WAD_TO_FEED: i128 = 10i128.pow(WAD_DECIMALS - DECIMALS); - -/// Converts a WAD-scaled NAV per share into a SEP-40 price, floored. +/// Converts the oracle's NAV per share into a SEP-40 price: the NAV itself +/// when the asset and the share have the same decimals, otherwise shifted by +/// the difference and floored. pub(crate) fn share_price( nav_per_share: i128, asset_decimals: u32, @@ -20,10 +12,10 @@ pub(crate) fn share_price( let price = if share_decimals >= asset_decimals { let scale = 10i128.checked_pow(share_decimals - asset_decimals)?; - nav_per_share.checked_mul(scale)? / WAD_TO_FEED + nav_per_share.checked_mul(scale)? } else { let scale = 10i128.checked_pow(asset_decimals - share_decimals)?; - nav_per_share / WAD_TO_FEED / scale + nav_per_share / scale }; (price > 0).then_some(price) diff --git a/contracts/sep40-feed/src/quote.rs b/contracts/sep40-feed/src/quote.rs index 15465088..0ae6a4a2 100644 --- a/contracts/sep40-feed/src/quote.rs +++ b/contracts/sep40-feed/src/quote.rs @@ -1,11 +1,11 @@ use sep40::{Asset, PriceData}; use soroban_sdk::{token::TokenClient, Env}; use strata_bindings::{ - OracleFeedClient, OracleState, VaultViewClient, WindDownInfo, WindDownStatus, + OracleFeedClient, OracleState, VaultViewClient, WindDownInfo, WindDownStatus, PRICE_SCALE, }; use crate::bound_vault; -use crate::price::{share_price, ONE}; +use crate::price::share_price; /// `Ok(Ok(value))` only; any other shape of a `try_` call reads as absent. fn ok( @@ -55,7 +55,7 @@ fn quote<'a>(e: &'a Env, asset: &Asset) -> Option<(PriceData, OracleFeedClient<' let share_decimals = ok(TokenClient::new(e, &share_token).try_decimals())?; share_price(nav_per_share, asset_decimals, share_decimals)? } else { - ONE + PRICE_SCALE }; Some((PriceData { price, timestamp }, oracle)) diff --git a/contracts/sep40-feed/src/test/kit.rs b/contracts/sep40-feed/src/test/kit.rs index c366d40c..f2580f50 100644 --- a/contracts/sep40-feed/src/test/kit.rs +++ b/contracts/sep40-feed/src/test/kit.rs @@ -11,12 +11,11 @@ use async_vault::{AsyncVault, VaultRoles}; use nav_oracle::{NavInput, NavOracleContract, NavOracleContractClient, OracleConfig, MIN_ANSWER}; use sep40::{Asset, PriceData}; +use strata_bindings::PRICE_SCALE; use super::PRICE; use crate::{FeedChange, Sep40Feed, Sep40FeedClient}; -const WAD: i128 = 10i128.pow(18); - fn reads_the_vault_view() {} fn reads_the_oracle_feed() {} @@ -56,7 +55,7 @@ fn kit_vault(e: &Env) -> KitVault<'_> { max_up_bps: 10_000, max_down_bps: 10_000, min_answer: MIN_ANSWER, - max_answer: 1_000 * WAD, + max_answer: 1_000 * PRICE_SCALE, }, ), ), @@ -111,7 +110,7 @@ fn the_feed_quotes_a_kit_vault_through_its_oracle() { oracle.attest( &NavInput { - nav_per_share: 105 * WAD / 100, + nav_per_share: 105 * PRICE_SCALE / 100, expires_at: u64::MAX, proof_hash: BytesN::from_array(&e, &[7; 32]), proof_uri: String::from_str(&e, ""), diff --git a/contracts/sep40-feed/src/test/mod.rs b/contracts/sep40-feed/src/test/mod.rs index 9c06c5d1..2cb090f7 100644 --- a/contracts/sep40-feed/src/test/mod.rs +++ b/contracts/sep40-feed/src/test/mod.rs @@ -28,8 +28,7 @@ use crate::{FeedError, Sep40Feed, Sep40FeedClient}; /// A margin past the instance's extend threshold, in ledgers. const TWO_DAYS_IN_LEDGERS: u32 = 2 * 17_280; -/// The vault's standing report, as `nav_per_share = 1.05` WAD, prices at the -/// feed's 14 decimals. +/// The vault's standing report: a NAV of 1.05, which the feed answers as is. pub(crate) const PRICE: i128 = 105_000_000_000_000; pub(crate) struct Fixture<'a> { @@ -167,7 +166,7 @@ fn build<'a>( let oracle = OracleStubClient::new(&e, &e.register(OracleStub, ())); oracle.set_report(&StubReport { state: OracleState::Valid, - nav_per_share: 1_050_000_000_000_000_000, + nav_per_share: PRICE, attested_at: 10_000, freshness_duration: 3_600, }); diff --git a/contracts/sep40-feed/src/test/price.rs b/contracts/sep40-feed/src/test/price.rs index d753415b..97e32992 100644 --- a/contracts/sep40-feed/src/test/price.rs +++ b/contracts/sep40-feed/src/test/price.rs @@ -1,21 +1,25 @@ -use crate::price::share_price; +use strata_bindings::PRICE_SCALE; -const WAD: i128 = 10i128.pow(18); +use crate::price::share_price; #[test] -fn equal_decimals_drop_four_digits() { - assert_eq!(share_price(WAD, 7, 7), Some(100_000_000_000_000)); +fn equal_decimals_answer_the_nav_as_is() { + assert_eq!(share_price(PRICE_SCALE, 7, 7), Some(100_000_000_000_000)); assert_eq!( - share_price(1_050_000_000_000_000_000, 7, 7), + share_price(105_000_000_000_000, 7, 7), Some(105_000_000_000_000) ); + assert_eq!( + share_price(12_345_678_901_234, 7, 7), + Some(12_345_678_901_234) + ); } #[test] fn more_share_decimals_raise_the_price() { // 1 share = 2 assets; asset 7, share 9: 0.02 asset base units per share base unit. assert_eq!( - share_price(20_000_000_000_000_000, 7, 9), + share_price(2_000_000_000_000, 7, 9), Some(200_000_000_000_000) ); } @@ -24,7 +28,7 @@ fn more_share_decimals_raise_the_price() { fn fewer_share_decimals_lower_the_price() { // 1 share = 2 assets; asset 7, share 6: 20 asset base units per share base unit. assert_eq!( - share_price(20_000_000_000_000_000_000, 7, 6), + share_price(2_000_000_000_000_000, 7, 6), Some(200_000_000_000_000) ); } @@ -32,21 +36,21 @@ fn fewer_share_decimals_lower_the_price() { #[test] fn the_price_rounds_down() { assert_eq!( - share_price(123_456_789_012_345_678, 7, 7), - Some(12_345_678_901_234) + share_price(12_345_678_901_234, 8, 7), + Some(1_234_567_890_123) ); } #[test] fn an_overflow_gives_no_price() { - assert_eq!(share_price(WAD, 0, 38), None); // nav × 10^38 overflows - assert_eq!(share_price(WAD, 0, 39), None); // 10^39 overflows - assert_eq!(share_price(WAD, 40, 0), None); // 10^40 overflows + assert_eq!(share_price(PRICE_SCALE, 0, 38), None); // nav × 10^38 overflows + assert_eq!(share_price(PRICE_SCALE, 0, 39), None); // 10^39 overflows + assert_eq!(share_price(PRICE_SCALE, 40, 0), None); // 10^40 overflows } #[test] fn a_price_of_zero_or_less_is_no_price() { assert_eq!(share_price(0, 7, 7), None); - assert_eq!(share_price(-WAD, 7, 7), None); - assert_eq!(share_price(WAD, 22, 7), None); // floors to 0 + assert_eq!(share_price(-PRICE_SCALE, 7, 7), None); + assert_eq!(share_price(PRICE_SCALE, 22, 7), None); // floors to 0 } diff --git a/contracts/sep40-feed/src/test/quotes.rs b/contracts/sep40-feed/src/test/quotes.rs index cf7a6a2c..264b1918 100644 --- a/contracts/sep40-feed/src/test/quotes.rs +++ b/contracts/sep40-feed/src/test/quotes.rs @@ -43,14 +43,14 @@ fn the_base_asset_is_quoted_at_one() { #[test] fn unequal_decimals_scale_the_price() { let f = setup_with_decimals(7, 9); - f.report(|r| r.nav_per_share = 20_000_000_000_000_000); + f.report(|r| r.nav_per_share = 2_000_000_000_000); assert_eq!( f.feed.lastprice(&f.share_asset()), Some(at(200_000_000_000_000, 10_000)) ); let f = setup_with_decimals(7, 6); - f.report(|r| r.nav_per_share = 20_000_000_000_000_000_000); + f.report(|r| r.nav_per_share = 2_000_000_000_000_000); assert_eq!( f.feed.lastprice(&f.share_asset()), Some(at(200_000_000_000_000, 10_000)) @@ -217,7 +217,7 @@ fn the_feed_follows_an_oracle_swap() { let second = super::OracleStubClient::new(&f.e, &f.e.register(super::OracleStub, ())); second.set_report(&super::StubReport { state: OracleState::Valid, - nav_per_share: 2_000_000_000_000_000_000, + nav_per_share: 200_000_000_000_000, attested_at: 10_000, freshness_duration: 600, }); @@ -251,7 +251,7 @@ fn the_feed_stores_no_price() { assert_eq!(instance_before, instance_after); assert_eq!(persistent_before, persistent_after); - f.report(|r| r.nav_per_share = 2_000_000_000_000_000_000); + f.report(|r| r.nav_per_share = 200_000_000_000_000); assert_eq!( f.feed.lastprice(&f.share_asset()).unwrap().price, 200_000_000_000_000 diff --git a/crates/strata-bindings/src/lib.rs b/crates/strata-bindings/src/lib.rs index 6e38fe16..5a71924a 100644 --- a/crates/strata-bindings/src/lib.rs +++ b/crates/strata-bindings/src/lib.rs @@ -1,6 +1,7 @@ //! # Design //! -//! The interfaces the kit's contracts share, and their error code blocks. +//! The interfaces the kit's contracts share, their price scale and their +//! error code blocks. //! //! - **The compiler checks the feed.** The vault prices from `OracleFeed`, //! which the kit's oracle and any adopter's feed implement. The cost: a feed @@ -15,6 +16,10 @@ //! - **The compiler checks the vault's views.** The SEP-40 feed reads //! `VaultView`, which the vault implements. The cost: the wind-down types //! live here, not in the vault. +//! - **One price scale, the feeds' own.** The oracle, the vault and the +//! SEP-40 feed keep `nav_per_share` at 14 decimals, as Stellar price feeds +//! do, so the feed needs no scale conversion. The cost: a price finer than +//! 10^-14 of an asset base unit per share base unit cannot be stored. #![no_std] @@ -26,6 +31,12 @@ pub use errors::{ ErrorRange, COMPLIANCE_ERRORS, FEED_ERRORS, ORACLE_ERRORS, TOKEN_ERRORS, VAULT_ERRORS, }; +/// Decimal places of a share price: asset base units per share base unit, +/// as Stellar price feeds carry them. +pub const PRICE_DECIMALS: u32 = 14; +/// A share price of one asset base unit per share base unit. +pub const PRICE_SCALE: i128 = 10i128.pow(PRICE_DECIMALS); + #[contracttype] #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum OracleState { @@ -39,6 +50,7 @@ pub enum OracleState { #[contracttrait] pub trait OracleFeed { fn state(e: &Env) -> OracleState; + /// Asset base units per share base unit, at `PRICE_DECIMALS`. fn nav_per_share(e: &Env) -> i128; /// Ledger time the standing report was accepted. fn attested_at(e: &Env) -> u64; diff --git a/docs/MONITORING_PLAN.md b/docs/MONITORING_PLAN.md index aac8ab92..626f9b18 100644 --- a/docs/MONITORING_PLAN.md +++ b/docs/MONITORING_PLAN.md @@ -124,7 +124,7 @@ The oracle holds one report. It stays valid until its `expires_at`, which is at most `freshness_duration` after the oracle accepted it, while it sits in the band `[min_answer, max_answer]` and the NAV is not paused. The vault prices an epoch only from a valid report accepted at or after the epoch was sealed. -Prices are in WAD: `10^18` is one asset base unit per share base unit. +Prices carry 14 decimals: `10^14` is one asset base unit per share base unit. ### V1. Report close to expiry @@ -264,7 +264,7 @@ The vault's figures, all in asset base units: - **Source:** on the vault, the headroom `liquid_reserve() - committed()`, against what the sealed epochs would commit: for each epoch whose `get_epoch(id)` status is `Pending`, - `total_shares_redeeming * nav_per_share / 10^18`, with `nav_per_share` from + `total_shares_redeeming * nav_per_share / 10^14`, with `nav_per_share` from `latest()` on the oracle. - **Threshold:** the headroom is smaller than that total. - **Severity:** Warning. **Told:** treasury. diff --git a/docs/kit-spec.md b/docs/kit-spec.md index b8bc718f..f9908644 100644 --- a/docs/kit-spec.md +++ b/docs/kit-spec.md @@ -152,8 +152,8 @@ Deploying the Strata Vault Kit involves six contracts configured via `environmen | **`nav_oracle`** | `config.cooldown_secs` | `u64` (seconds) | Minimum time between consecutive attestations. At least 1 s (`MIN_COOLDOWN_SECS`), so at most one report per ledger. At most `freshness_duration`, so a new report can always replace the last one before the freshness window ends | `nav_oracle.constructor_args` | | **`nav_oracle`** | `config.max_up_bps` | `u32` (basis points) | Largest upward move per attestation, 1 to 10,000 | `nav_oracle.constructor_args` | | **`nav_oracle`** | `config.max_down_bps` | `u32` (basis points) | Largest downward move per attestation, 1 to 10,000; 10,000 lets a loss of any size land at once | `nav_oracle.constructor_args` | -| **`nav_oracle`** | `config.min_answer` | `i128` (18 decimals) | Absolute floor price per share, at least `MIN_ANSWER` ($`10^{12}`$, a millionth of an asset unit per share). An oracle upgraded in place with a stored `min_answer` below the floor keeps it; even its instant `set_config` (a shorter freshness window) is refused until a timelocked `Config` change raises it to the floor | `nav_oracle.constructor_args` | -| **`nav_oracle`** | `config.max_answer` | `i128` (18 decimals) | Absolute ceiling price per share ($`\ge \text{min\_answer}`$, $`\le 10^{6} \times 10^{18}`$, `MAX_ANSWER`) | `nav_oracle.constructor_args` | +| **`nav_oracle`** | `config.min_answer` | `i128` (14 decimals) | Absolute floor price per share, at least `MIN_ANSWER` ($`10^{8}`$, a millionth of an asset unit per share). An oracle upgraded in place with a stored `min_answer` below the floor keeps it; even its instant `set_config` (a shorter freshness window) is refused until a timelocked `Config` change raises it to the floor | `nav_oracle.constructor_args` | +| **`nav_oracle`** | `config.max_answer` | `i128` (14 decimals) | Absolute ceiling price per share ($`\ge \text{min\_answer}`$, $`\le 10^{6} \times 10^{14}`$, `MAX_ANSWER`) | `nav_oracle.constructor_args` | | **`async_vault`** | `asset` | `Address` | Settlement asset SAC contract address (e.g. USDC). Must have the share token's 7 decimals: `finish_setup` refuses with `SetupIncomplete` otherwise (`health().decimals_match`). Every classic Stellar asset has 7; a Soroban token with other decimals needs a fork of the share token | `async_vault.constructor_args` | | **`async_vault`** | `share_token` | `Address` | Deployed share token contract address | `async_vault.constructor_args` | | **`async_vault`** | `oracle` | `Address` | Deployed NAV oracle contract address | `async_vault.constructor_args` | @@ -653,7 +653,8 @@ section that would be empty is left out, so a view has no `# Events` and no override keep OpenZeppelin's docs. - Amounts are in the asset's base units and shares in the share token's base - units. Prices are in WAD: asset base units per share base unit, times 10^18. + units. Prices are asset base units per share base unit, times 10^14 (14 + decimals). Times and durations are in seconds; `live_until_ledger` is a ledger number. - An error named without its enum is the contract's own. Any other error carries its enum, as in `AccessControlError::Unauthorized`. diff --git a/docs/strata-product-and-architecture.md b/docs/strata-product-and-architecture.md index 173a9f02..41a8c1b5 100644 --- a/docs/strata-product-and-architecture.md +++ b/docs/strata-product-and-architecture.md @@ -501,13 +501,13 @@ the ledger time on every read rather than cache the resolution. `resolution()` answers `0` when the vault or its oracle cannot be read — a real oracle never reports a zero window, so `0` only ever means the feed has no price either, and a consumer must check for it before dividing. `decimals()` -is 14, as Stellar price feeds use; the kit keeps the NAV in WAD (18 -decimals), so the feed converts at the edge: -`nav_per_share × 10^(share decimals − asset decimals) / 10^4`, rounded down, -with an overflow or a non-positive result giving no price — precision below -10^-14 of an asset unit per share is lost, and a share whose value rounds to -zero has no price. Moving the NAV itself to 14 decimals is a separate -decision. +is 14, as Stellar price feeds use, and the oracle and the vault keep +`nav_per_share` at that same scale: asset base units per share base unit, +times 10^14. The vault's setup requires the asset and the share token to have +the same decimals, so the feed answers `nav_per_share` unchanged. With other +decimals it would answer +`nav_per_share × 10^(share decimals − asset decimals)`, rounded down, with an +overflow or a non-positive result giving no price. ### 8.6 Compliance diff --git a/environments.toml b/environments.toml index 959788b1..064e7ced 100644 --- a/environments.toml +++ b/environments.toml @@ -37,11 +37,11 @@ constructor_args = '--name "Strata Vault USDC" --symbol bvUSDC --admin me --comp # `--config` takes the OracleConfig struct as JSON. The values match the # harness's testnet oracle: a one-hour freshness window, a one-minute cooldown, # a 10% cap on a rise, no cap on a fall (10,000 bps lets a loss of any size -# land at once) and a 0.5–100 band at the 18-decimal scale. The two i128 fields +# land at once) and a 0.5–100 band at the 14-decimal scale. The two i128 fields # are strings because they do not survive a JSON number round trip. [development.contracts.nav_oracle] client = true -constructor_args = "--admin me --attester me --guardian me --config '{\"freshness_duration\":3600,\"cooldown_secs\":60,\"max_up_bps\":1000,\"max_down_bps\":10000,\"min_answer\":\"500000000000000000\",\"max_answer\":\"100000000000000000000\"}'" +constructor_args = "--admin me --attester me --guardian me --config '{\"freshness_duration\":3600,\"cooldown_secs\":60,\"max_up_bps\":1000,\"max_down_bps\":10000,\"min_answer\":\"50000000000000\",\"max_answer\":\"10000000000000000\"}'" [development.contracts.async_vault] client = true diff --git a/scripts/harness/lib/amounts.ts b/scripts/harness/lib/amounts.ts index 9c0c2312..29e62eb3 100644 --- a/scripts/harness/lib/amounts.ts +++ b/scripts/harness/lib/amounts.ts @@ -1,7 +1,7 @@ import { Asset } from "@stellar/stellar-sdk" -export const WAD = 10n ** 18n -export const PRICE_SCALE = WAD +export const PRICE_DECIMALS = 14 +export const PRICE_SCALE = 10n ** BigInt(PRICE_DECIMALS) export const XLM = Asset.native() export const XLM_DECIMALS = 7 diff --git a/scripts/harness/lib/network.ts b/scripts/harness/lib/network.ts index e6bc6b42..66b8065b 100644 --- a/scripts/harness/lib/network.ts +++ b/scripts/harness/lib/network.ts @@ -1,6 +1,6 @@ import { Networks } from "@stellar/stellar-sdk" -import { WAD } from "./amounts.js" +import { PRICE_SCALE } from "./amounts.js" export type NetworkName = "local" | "testnet" @@ -35,8 +35,8 @@ export interface Network { const band = { max_up_bps: 1000, max_down_bps: 10_000, - min_answer: (WAD / 2n).toString(), - max_answer: (WAD * 100n).toString(), + min_answer: (PRICE_SCALE / 2n).toString(), + max_answer: (PRICE_SCALE * 100n).toString(), } // The quickstart image's standalone root key. Public, and worthless off a laptop. diff --git a/scripts/harness/seed.ts b/scripts/harness/seed.ts index 71438d9d..fa3996c3 100644 --- a/scripts/harness/seed.ts +++ b/scripts/harness/seed.ts @@ -2,7 +2,7 @@ import { type Keypair } from "@stellar/stellar-sdk" import { accountRow } from "./lib/account-table.js" import { pay, trustline } from "./lib/accounts.js" -import { price, units } from "./lib/amounts.js" +import { PRICE_DECIMALS, price, units } from "./lib/amounts.js" import { trustlineBalance } from "./lib/balances.js" import { connect, @@ -24,11 +24,8 @@ function formatAmount(amount: bigint, decimals: number): string { return `${whole}.${fraction.toString().padStart(decimals, "0").slice(0, 4)}` } -function formatWad(wad: bigint): string { - const factor = 10n ** 18n - const whole = wad / factor - const fraction = wad % factor - return `$${whole}.${fraction.toString().padStart(18, "0").slice(0, 4)}` +function formatPrice(value: bigint): string { + return `$${formatAmount(value, PRICE_DECIMALS)}` } async function hasTrustline(c: Connected, address: string): Promise { @@ -194,7 +191,7 @@ async function main(): Promise { console.log(" ✓ Epoch 1 closed") const nav = price(1) // $1.00 NAV - console.log(` + attesting NAV (${formatWad(nav)})...`) + console.log(` + attesting NAV (${formatPrice(nav)})...`) await attest(c, nav) console.log(" ✓ NAV attested on oracle") @@ -329,7 +326,9 @@ async function main(): Promise { console.log( `Total Value Locked: ${formatAmount(finalFree + custodianBal, decimals)} USDC (NAV basis)`, ) - console.log(`Latest Attested NAV: ${formatWad(oracleLatest.nav_per_share)}`) + console.log( + `Latest Attested NAV: ${formatPrice(oracleLatest.nav_per_share)}`, + ) console.log("\n--- CONTRACT ADDRESSES ---") console.table(c.deployment.contracts) diff --git a/scripts/harness/wind-down.test.ts b/scripts/harness/wind-down.test.ts index 95a46495..fca79f6c 100644 --- a/scripts/harness/wind-down.test.ts +++ b/scripts/harness/wind-down.test.ts @@ -104,7 +104,7 @@ describe("a wind-down on a throwaway vault", () => { const holder = () => c.keys["holder-1"].publicKey() it("a holder subscribes, is priced and claims shares", async () => { - await freshFeed(c, 2n * 10n ** 18n) + await freshFeed(c, price(2)) expect( await submit("request_deposit", "holder-1", { holder: holder(), @@ -116,7 +116,7 @@ describe("a wind-down on a throwaway vault", () => { caller: c.keys.manager.publicKey(), }), ).toBe("accepted") - await attest(c, 2n * 10n ** 18n) + await attest(c, price(2)) await waitForNotice(c, vault(c, c.keys.outsider), 1n) expect(await submit("fulfill_epoch", "outsider", { epoch_id: 1n })).toBe( "accepted",