Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle bottom boundary rounding error #1078

Draft
wants to merge 1 commit into
base: fix_precision_of_balance_calculations_in_distributor
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions apps/distributor/src/weights.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { parseUnits } from 'viem'

type WeightedShare = { address: `0x${string}`; amount: bigint }

export enum Mode {
Expand All @@ -23,7 +25,7 @@ export function calculateWeights(
address: `0x${string}`
balance: string
}[],
timeAdjustedAmount: bigint,
poolAmount: bigint,
mode: Mode = Mode.Linear
): Record<string, WeightedShare> {
const poolWeights: Record<`0x${string}`, bigint> = {}
Expand All @@ -48,7 +50,7 @@ export function calculateWeights(
for (const { address } of balances) {
const poolWeight = poolWeights[address] ?? 0n

const amount = (poolWeight * timeAdjustedAmount) / totalWeight
const amount = (poolWeight * poolAmount) / totalWeight

if (amount > 0n) {
weightedShares[address] = {
Expand All @@ -58,23 +60,24 @@ export function calculateWeights(
}
}

handleRoundingErrors(weightedShares, timeAdjustedAmount)
handleRoundingErrors(weightedShares, poolAmount)

return weightedShares
}

// Helper function to handle rounding errors
function handleRoundingErrors(shares: Record<string, WeightedShare>, targetAmount: bigint) {
let totalDistributed = 0n
for (const share of Object.values(shares)) {
totalDistributed += share.amount
}
const totalDistributed = Object.values(shares).reduce((a, b) => a + b.amount, 0n)
const largestShare = Object.values(shares).reduce((a, b) => (a.amount > b.amount ? a : b))
const difference = targetAmount - totalDistributed
const oneSend = parseUnits('1', 18)

if (totalDistributed > targetAmount) {
const difference = targetAmount - totalDistributed
const largestShare = Object.values(shares).reduce((a, b) => (a.amount > b.amount ? a : b))
largestShare.amount += difference
}
if (totalDistributed < targetAmount && difference < oneSend) {
largestShare.amount -= difference
}
}

function calculateWeightByMode(
Expand Down
Loading