Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/p/nym-moultest123/x/games/prorata/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186406
  max_deposit = "6000000ugnot"

prorata.gno

// Package prorata splits an integer amount across weighted claimants without
// leaking or inventing a unit.
//
// Every payout in a game is this operation: a pot, a roster, and a weight each.
// Written the obvious way, `amount*weight/total` per claimant, it is wrong in
// two ways that only show up with real money in the contract. The shares are
// each rounded down, so their sum is short of the amount by up to one unit per
// claimant, and that dust either accumulates in the contract forever or gets
// handed to whoever the code happens to pay last. And `amount*weight` overflows
// an int64 long before either factor does, which turns a large payout negative.
//
// Split fixes both. It distributes by largest remainder: floor every share,
// then hand the leftover units out one at a time to the claimants whose
// truncated fraction was largest, ties going to the lower index. The result
// sums to EXACTLY the amount, every time, and the rule is deterministic, so
// every node computes the same split and a Render of it does not change between
// calls.
//
// Nothing here reads the chain and nothing holds coins: the caller owns the
// roster and the custody. A game built on this package is at
// [r/moul/x/games/lastwords](/r/nym-moultest123/x/games/lastwords/v0).
package prorata

import (
	"errors"
	"sort"
)

const maxInt64 = int64(9223372036854775807)

var (
	// ErrNegativeAmount is returned when the amount to split is negative.
	ErrNegativeAmount = errors.New("prorata: amount must not be negative")
	// ErrNegativeWeight is returned when any weight is negative.
	ErrNegativeWeight = errors.New("prorata: weights must not be negative")
	// ErrNoWeight is returned when there is nobody to pay, or every weight is
	// zero. The caller must decide where the amount goes instead: silently
	// returning an empty split would strand it.
	ErrNoWeight = errors.New("prorata: total weight is zero, nothing to split across")
	// ErrOverflow is returned when the arithmetic does not fit in an int64.
	ErrOverflow = errors.New("prorata: weights overflow int64")
)

// Split divides amount across weights and returns one share per weight, in the
// same order. The shares sum to exactly amount.
//
// A zero weight is allowed and receives nothing, including no remainder unit:
// somebody with no claim is not paid dust.
func Split(amount int64, weights []int64) ([]int64, error) {
	if amount < 0 {
		return nil, ErrNegativeAmount
	}
	total, err := Total(weights)
	if err != nil {
		return nil, err
	}
	if total == 0 {
		return nil, ErrNoWeight
	}

	shares := make([]int64, len(weights))
	if amount == 0 {
		return shares, nil
	}

	// Floor each share, and keep the truncated numerator to rank by.
	rems := make([]entry, 0, len(weights))
	assigned := int64(0)
	for i, w := range weights {
		if w == 0 {
			continue
		}
		share, rem, err := divide(amount, w, total)
		if err != nil {
			return nil, err
		}
		shares[i] = share
		assigned += share
		rems = append(rems, entry{index: i, rem: rem})
	}

	// Hand the leftover out by largest remainder. There are strictly fewer
	// leftover units than claimants, so one pass over the ranking is enough.
	left := amount - assigned
	if left <= 0 {
		return shares, nil
	}
	sort.Sort(byRemainder(rems))
	for i := 0; i < len(rems) && left > 0; i++ {
		shares[rems[i].index]++
		left--
	}
	return shares, nil
}

// Share returns what one weight is owed out of amount, rounded down. It is the
// "what would I get" query, and deliberately does NOT account for the
// remainder: use Split when the shares have to add up.
func Share(amount, weight, total int64) (int64, error) {
	if amount < 0 {
		return 0, ErrNegativeAmount
	}
	if weight < 0 || total < 0 {
		return 0, ErrNegativeWeight
	}
	if total == 0 {
		return 0, ErrNoWeight
	}
	if weight > total {
		weight = total
	}
	share, _, err := divide(amount, weight, total)
	return share, err
}

// Total sums weights, refusing an int64 overflow rather than wrapping into a
// negative total that would make every share nonsense.
func Total(weights []int64) (int64, error) {
	sum := int64(0)
	for _, w := range weights {
		if w < 0 {
			return 0, ErrNegativeWeight
		}
		if w > maxInt64-sum {
			return 0, ErrOverflow
		}
		sum += w
	}
	return sum, nil
}

// divide returns amount*weight/total rounded down, plus the remainder of that
// division, without ever computing amount*weight.
//
// It splits the amount into whole multiples of total and what is left over:
// amount = q*total + r, so amount*weight/total is exactly q*weight +
// r*weight/total. The first term is exact and the second multiplies a value
// already smaller than total, which is what keeps the product in range.
func divide(amount, weight, total int64) (share, rem int64, err error) {
	q := amount / total
	r := amount % total
	if weight != 0 && q > maxInt64/weight {
		return 0, 0, ErrOverflow
	}
	whole := q * weight
	if weight != 0 && r > maxInt64/weight {
		return 0, 0, ErrOverflow
	}
	part := r * weight
	if whole > maxInt64-part/total {
		return 0, 0, ErrOverflow
	}
	return whole + part/total, part % total, nil
}

// entry is one claimant's truncated fraction, for ranking the leftover.
type entry struct {
	index int
	rem   int64
}

// byRemainder ranks by largest truncated remainder, ties by lowest index, so
// the split is identical on every node.
type byRemainder []entry

func (b byRemainder) Len() int      { return len(b) }
func (b byRemainder) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byRemainder) Less(i, j int) bool {
	if b[i].rem != b[j].rem {
		return b[i].rem > b[j].rem
	}
	return b[i].index < b[j].index
}

prorata_test.gno

package prorata

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func sum(xs []int64) int64 {
	t := int64(0)
	for _, x := range xs {
		t += x
	}
	return t
}

func TestSplitTable(t *testing.T) {
	cases := []struct {
		name    string
		amount  int64
		weights []int64
		want    []int64
	}{
		{"exact thirds", 99, []int64{1, 1, 1}, []int64{33, 33, 33}},
		{"one unit of dust, to the lowest index", 10, []int64{1, 1, 1}, []int64{4, 3, 3}},
		{"two units of dust", 11, []int64{1, 1, 1}, []int64{4, 4, 3}},
		{"uneven weights", 100, []int64{1, 2, 3}, []int64{17, 33, 50}},
		{"a single claimant takes it all", 7, []int64{5}, []int64{7}},
		{"zero weight is paid nothing", 10, []int64{0, 1, 1}, []int64{0, 5, 5}},
		{"zero weight is not paid dust either", 10, []int64{0, 1, 1, 1}, []int64{0, 4, 3, 3}},
		{"nothing to split", 0, []int64{3, 1}, []int64{0, 0}},
		{"amount smaller than the roster", 2, []int64{1, 1, 1, 1}, []int64{1, 1, 0, 0}},
		{"weight dominates", 1000, []int64{999, 1}, []int64{999, 1}},
	}
	for _, tc := range cases {
		got, err := Split(tc.amount, tc.weights)
		uassert.NoError(t, err, tc.name)
		uassert.Equal(t, len(tc.want), len(got), tc.name)
		for i := range tc.want {
			uassert.Equal(t, tc.want[i], got[i], tc.name)
		}
	}
}

// TestSplitAlwaysSumsToTheAmount is the whole point: a split that is short by
// dust strands coins in the realm forever, and one that is over cannot be paid.
func TestSplitAlwaysSumsToTheAmount(t *testing.T) {
	weightsets := [][]int64{
		{1, 1, 1},
		{1, 2, 3, 4, 5, 6, 7},
		{7, 0, 1},
		{100, 1},
		{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
		{1},
		{999983, 17, 5},
	}
	for _, ws := range weightsets {
		for amount := int64(0); amount < 60; amount++ {
			got, err := Split(amount, ws)
			uassert.NoError(t, err)
			uassert.Equal(t, amount, sum(got), "shares must sum to the amount")
		}
		for _, amount := range []int64{1000, 123457, 999999999} {
			got, err := Split(amount, ws)
			uassert.NoError(t, err)
			uassert.Equal(t, amount, sum(got))
		}
	}
}

// TestLargestRemainderWins pins the allocation rule, so a payout cannot quietly
// change to "whoever the loop paid last".
func TestLargestRemainderWins(t *testing.T) {
	// total 10, amount 4: floors are 0,0,1,1 with remainders 4,8,2,6.
	got, err := Split(4, []int64{1, 2, 3, 4})
	uassert.NoError(t, err)
	uassert.Equal(t, int64(0), got[0], "smallest remainder, no extra unit")
	uassert.Equal(t, int64(1), got[1], "largest remainder, gets one")
	uassert.Equal(t, int64(1), got[2], "floor 1, remainder 2, gets none")
	uassert.Equal(t, int64(2), got[3], "second largest, gets the other")
	uassert.Equal(t, int64(4), sum(got))
}

func TestSplitValidation(t *testing.T) {
	_, err := Split(-1, []int64{1})
	uassert.ErrorIs(t, err, ErrNegativeAmount)

	_, err = Split(10, []int64{1, -1})
	uassert.ErrorIs(t, err, ErrNegativeWeight)

	_, err = Split(10, nil)
	uassert.ErrorIs(t, err, ErrNoWeight, "an empty roster is the caller's problem, not dust")

	_, err = Split(10, []int64{0, 0})
	uassert.ErrorIs(t, err, ErrNoWeight, "every weight zero is the same problem")
}

// TestNoOverflowOnLargePots is the second failure mode: amount*weight wraps
// negative long before either factor is anywhere near the limit.
func TestNoOverflowOnLargePots(t *testing.T) {
	// A pot of 10^18 ugnot split across weights that would overflow if
	// multiplied together first.
	pot := int64(1000000000000000000)
	got, err := Split(pot, []int64{3000000000, 1000000000})
	uassert.NoError(t, err)
	uassert.Equal(t, pot, sum(got))
	uassert.Equal(t, int64(750000000000000000), got[0])
	uassert.Equal(t, int64(250000000000000000), got[1])

	got, err = Split(maxInt64, []int64{1, 1})
	uassert.NoError(t, err)
	uassert.Equal(t, maxInt64, sum(got), "even the largest possible pot")

	_, err = Total([]int64{maxInt64, 1})
	uassert.ErrorIs(t, err, ErrOverflow, "a wrapped total makes every share nonsense")
}

func TestShare(t *testing.T) {
	got, err := Share(100, 1, 3)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(33), got, "rounded down, the remainder is Split's job")

	got, err = Share(1000000000000000000, 3000000000, 4000000000)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(750000000000000000), got)

	got, err = Share(100, 7, 3)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(100), got, "a weight above the total is clamped, never over-paid")

	_, err = Share(10, 1, 0)
	uassert.ErrorIs(t, err, ErrNoWeight)
	_, err = Share(-1, 1, 2)
	uassert.ErrorIs(t, err, ErrNegativeAmount)
	_, err = Share(10, -1, 2)
	uassert.ErrorIs(t, err, ErrNegativeWeight)
}

func TestTotal(t *testing.T) {
	got, err := Total([]int64{1, 2, 3})
	uassert.NoError(t, err)
	uassert.Equal(t, int64(6), got)

	got, err = Total(nil)
	uassert.NoError(t, err)
	uassert.Equal(t, int64(0), got, "empty sums to zero; Split is what refuses it")
}