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/daily/pullpayment/v0"
gno = "0.9"

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

pullpayment.gno

// Package pullpayment is the escrow ledger behind the pull-payment pattern, as
// a pure, reusable package.
//
// The pattern is the classic Solidity answer to reentrancy: never push value to
// an address, credit it and let the recipient withdraw. A push sends control to
// the recipient in the middle of your state transition, and a malicious
// recipient re-enters before you have finished updating. Pull inverts that —
// the recipient calls in, and their own withdrawal is the only state being
// touched.
//
// This package is the BOOKKEEPING half only: who is owed what, and the
// checks-effects-interactions ordering that makes a withdrawal safe. It moves
// no coins. The realm that holds the funds performs the transfer AFTER calling
// Withdraw, which is exactly the ordering the pattern demands — the balance is
// already zeroed when the transfer happens, so a reentrant call finds nothing
// left to take.
//
// Iteration is over sorted addresses, never a built-in map range: gno map
// iteration order is unspecified and a Render built from one can differ between
// nodes, which is a consensus bug rather than a cosmetic one.
//
// A live demo of this package is at
// [r/moul/x/daily/pullpaymentdemo](/r/nym-moultest123/x/daily/pullpaymentdemo/v0).
package pullpayment

import (
	"errors"
	"sort"
)

// MaxPayees bounds the ledger so gas stays predictable.
const MaxPayees = 4096

var (
	ErrBadAmount = errors.New("pullpayment: amount must be positive")
	ErrFull      = errors.New("pullpayment: too many payees")
	ErrNothing   = errors.New("pullpayment: nothing to withdraw")
	ErrOverflow  = errors.New("pullpayment: credit would overflow")
)

const maxInt64 = int64(9223372036854775807)

// Ledger records what each address is owed.
type Ledger struct {
	owed      map[string]int64
	total     int64
	withdrawn int64
}

// New returns an empty Ledger.
func New() *Ledger { return &Ledger{owed: map[string]int64{}} }

// Credit records that payee is owed amount more. Amounts accumulate: crediting
// twice owes the sum.
func (l *Ledger) Credit(payee string, amount int64) error {
	if amount <= 0 {
		return ErrBadAmount
	}
	cur, seen := l.owed[payee]
	if !seen && len(l.owed) >= MaxPayees {
		return ErrFull
	}
	if cur > maxInt64-amount || l.total > maxInt64-amount {
		return ErrOverflow
	}
	l.owed[payee] = cur + amount
	l.total += amount
	return nil
}

// Balance returns what payee is currently owed; zero when nothing.
func (l *Ledger) Balance(payee string) int64 { return l.owed[payee] }

// Withdraw zeroes payee's balance and returns what was owed.
//
// The caller transfers the returned amount AFTER this call. That ordering is
// the point of the pattern: the credit is already gone from the ledger when
// control passes to the recipient, so a reentrant Withdraw returns ErrNothing.
func (l *Ledger) Withdraw(payee string) (int64, error) {
	amount, ok := l.owed[payee]
	if !ok || amount == 0 {
		return 0, ErrNothing
	}
	delete(l.owed, payee) // effects before interactions
	l.total -= amount
	l.withdrawn += amount
	return amount, nil
}

// Forfeit drops a payee's credit without paying it, returning what was dropped.
func (l *Ledger) Forfeit(payee string) (int64, error) {
	amount, ok := l.owed[payee]
	if !ok || amount == 0 {
		return 0, ErrNothing
	}
	delete(l.owed, payee)
	l.total -= amount
	return amount, nil
}

// TotalOwed returns the sum of every outstanding balance — what the holding
// realm must keep in reserve.
func (l *Ledger) TotalOwed() int64 { return l.total }

// TotalWithdrawn returns the lifetime sum of successful withdrawals.
func (l *Ledger) TotalWithdrawn() int64 { return l.withdrawn }

// Payees returns every address with an outstanding balance, sorted.
func (l *Ledger) Payees() []string {
	out := make([]string, 0, len(l.owed))
	for p := range l.owed {
		out = append(out, p)
	}
	sort.Strings(out)
	return out
}

// Count returns how many payees are owed something.
func (l *Ledger) Count() int { return len(l.owed) }

// IsEmpty reports whether nothing is owed to anyone.
func (l *Ledger) IsEmpty() bool { return len(l.owed) == 0 }

// Iterate calls fn for each payee in sorted order. Returning true stops.
func (l *Ledger) Iterate(fn func(payee string, amount int64) bool) {
	for _, p := range l.Payees() {
		if fn(p, l.owed[p]) {
			return
		}
	}
}

// CreditMany credits several payees, applying nothing unless every entry is
// valid — a partial split would leave the ledger disagreeing with the funds.
func (l *Ledger) CreditMany(payees []string, amounts []int64) error {
	if len(payees) != len(amounts) {
		return ErrBadAmount
	}
	// Validate first.
	for _, a := range amounts {
		if a <= 0 {
			return ErrBadAmount
		}
	}
	probe := len(l.owed)
	for _, p := range payees {
		if _, seen := l.owed[p]; !seen {
			probe++
		}
	}
	if probe > MaxPayees {
		return ErrFull
	}
	var sum int64
	for _, a := range amounts {
		if sum > maxInt64-a {
			return ErrOverflow
		}
		sum += a
	}
	if l.total > maxInt64-sum {
		return ErrOverflow
	}
	// Then apply.
	for i, p := range payees {
		l.owed[p] += amounts[i]
	}
	l.total += sum
	return nil
}

// Consistent reports whether TotalOwed equals the sum of the balances. Always
// true through the public API; exported so callers can assert the invariant.
func (l *Ledger) Consistent() bool {
	var sum int64
	for _, a := range l.owed {
		sum += a
	}
	return sum == l.total
}

pullpayment_test.gno

package pullpayment

import (
	"strconv"
	"strings"
	"testing"

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

func TestEmpty(t *testing.T) {
	l := New()
	uassert.True(t, l.IsEmpty())
	uassert.Equal(t, 0, l.Count())
	uassert.Equal(t, int64(0), l.TotalOwed())
	uassert.Equal(t, int64(0), l.Balance("nobody"))
	uassert.True(t, l.Consistent())
}

func TestCreditAccumulates(t *testing.T) {
	l := New()
	uassert.NoError(t, l.Credit("alice", 100))
	uassert.NoError(t, l.Credit("alice", 50))

	uassert.Equal(t, int64(150), l.Balance("alice"), "credits accumulate")
	uassert.Equal(t, 1, l.Count(), "the same payee is not counted twice")
	uassert.Equal(t, int64(150), l.TotalOwed())
	uassert.True(t, l.Consistent())
}

func TestCreditRejectsNonPositive(t *testing.T) {
	l := New()
	uassert.ErrorIs(t, l.Credit("alice", 0), ErrBadAmount)
	uassert.ErrorIs(t, l.Credit("alice", -1), ErrBadAmount)
	uassert.True(t, l.IsEmpty(), "a rejected credit changes nothing")
}

func TestWithdrawZeroesBalance(t *testing.T) {
	l := New()
	l.Credit("alice", 100)

	got, err := l.Withdraw("alice")
	uassert.NoError(t, err)
	uassert.Equal(t, int64(100), got)
	uassert.Equal(t, int64(0), l.Balance("alice"), "the balance is gone before the caller transfers")
	uassert.Equal(t, int64(0), l.TotalOwed())
	uassert.Equal(t, int64(100), l.TotalWithdrawn())
	uassert.True(t, l.Consistent())
}

// TestReentrantWithdrawGetsNothing is the security property the pattern exists
// for: the second entry finds the balance already zeroed.
func TestReentrantWithdrawGetsNothing(t *testing.T) {
	l := New()
	l.Credit("attacker", 1000)

	first, err := l.Withdraw("attacker")
	uassert.NoError(t, err)
	uassert.Equal(t, int64(1000), first)

	// Simulating the reentrant call the recipient would make from its handler,
	// BEFORE the outer caller has transferred anything.
	second, err := l.Withdraw("attacker")
	uassert.ErrorIs(t, err, ErrNothing, "a reentrant withdrawal must find nothing")
	uassert.Equal(t, int64(0), second)
	uassert.Equal(t, int64(1000), l.TotalWithdrawn(), "and must not be counted twice")
}

func TestWithdrawUnknownPayee(t *testing.T) {
	l := New()
	_, err := l.Withdraw("nobody")
	uassert.ErrorIs(t, err, ErrNothing)
}

func TestForfeit(t *testing.T) {
	l := New()
	l.Credit("alice", 100)
	l.Credit("bob", 40)

	dropped, err := l.Forfeit("alice")
	uassert.NoError(t, err)
	uassert.Equal(t, int64(100), dropped)
	uassert.Equal(t, int64(40), l.TotalOwed())
	uassert.Equal(t, int64(0), l.TotalWithdrawn(), "a forfeit is not a withdrawal")
	uassert.True(t, l.Consistent())

	_, err = l.Forfeit("alice")
	uassert.ErrorIs(t, err, ErrNothing)
}

func TestPayeesSorted(t *testing.T) {
	l := New()
	l.Credit("carol", 3)
	l.Credit("alice", 1)
	l.Credit("bob", 2)

	uassert.Equal(t, "alice,bob,carol", strings.Join(l.Payees(), ","))
}

func TestIterateSortedAndStops(t *testing.T) {
	l := New()
	l.Credit("b", 2)
	l.Credit("a", 1)

	var seen []string
	l.Iterate(func(p string, amt int64) bool {
		seen = append(seen, p+":"+strconv.FormatInt(amt, 10))
		return false
	})
	uassert.Equal(t, "a:1,b:2", strings.Join(seen, ","))

	n := 0
	l.Iterate(func(p string, amt int64) bool { n++; return true })
	uassert.Equal(t, 1, n)
}

func TestCreditMany(t *testing.T) {
	l := New()
	err := l.CreditMany([]string{"a", "b", "c"}, []int64{10, 20, 30})
	uassert.NoError(t, err)

	uassert.Equal(t, int64(10), l.Balance("a"))
	uassert.Equal(t, int64(30), l.Balance("c"))
	uassert.Equal(t, int64(60), l.TotalOwed())
	uassert.True(t, l.Consistent())
}

// TestCreditManyIsAllOrNothing pins that a bad entry applies none of the split.
func TestCreditManyIsAllOrNothing(t *testing.T) {
	l := New()
	l.Credit("existing", 5)

	err := l.CreditMany([]string{"a", "b"}, []int64{10, -1})
	uassert.ErrorIs(t, err, ErrBadAmount)

	uassert.Equal(t, int64(0), l.Balance("a"), "the valid entry must not be applied either")
	uassert.Equal(t, int64(5), l.TotalOwed(), "the ledger is untouched")
	uassert.Equal(t, 1, l.Count())
	uassert.True(t, l.Consistent())
}

func TestCreditManyMismatchedLengths(t *testing.T) {
	l := New()
	uassert.ErrorIs(t, l.CreditMany([]string{"a"}, []int64{1, 2}), ErrBadAmount)
	uassert.True(t, l.IsEmpty())
}

func TestCreditManyAccumulates(t *testing.T) {
	l := New()
	l.Credit("a", 5)
	uassert.NoError(t, l.CreditMany([]string{"a", "b"}, []int64{10, 1}))
	uassert.Equal(t, int64(15), l.Balance("a"), "adds to the existing balance")
	uassert.Equal(t, int64(16), l.TotalOwed())
}

func TestOverflowGuard(t *testing.T) {
	l := New()
	uassert.NoError(t, l.Credit("whale", maxInt64))
	uassert.ErrorIs(t, l.Credit("whale", 1), ErrOverflow)
	uassert.ErrorIs(t, l.Credit("other", 1), ErrOverflow, "the total would overflow too")
	uassert.Equal(t, maxInt64, l.TotalOwed(), "a refused credit changes nothing")
	uassert.True(t, l.Consistent())
}

func TestCreditManyOverflowGuard(t *testing.T) {
	l := New()
	l.Credit("a", maxInt64-5)
	uassert.ErrorIs(t, l.CreditMany([]string{"b", "c"}, []int64{10, 10}), ErrOverflow)
	uassert.Equal(t, int64(0), l.Balance("b"), "nothing applied")
}

func TestMaxPayees(t *testing.T) {
	l := New()
	for i := 0; i < MaxPayees; i++ {
		uassert.NoError(t, l.Credit("p"+strconv.Itoa(i), 1))
	}
	uassert.Equal(t, MaxPayees, l.Count())

	uassert.ErrorIs(t, l.Credit("overflow", 1), ErrFull, "a full ledger refuses a new payee")
	uassert.NoError(t, l.Credit("p0", 1), "existing payees can still be credited")
	uassert.Equal(t, int64(2), l.Balance("p0"))
}

func TestCreditManyRespectsCapacity(t *testing.T) {
	l := New()
	for i := 0; i < MaxPayees-1; i++ {
		l.Credit("p"+strconv.Itoa(i), 1)
	}
	uassert.ErrorIs(t, l.CreditMany([]string{"x", "y"}, []int64{1, 1}), ErrFull,
		"the batch would exceed capacity, so none of it applies")
	uassert.Equal(t, int64(0), l.Balance("x"))
}

// TestFullLifecycle walks a realistic split-then-claim sequence.
func TestFullLifecycle(t *testing.T) {
	l := New()
	uassert.NoError(t, l.CreditMany([]string{"alice", "bob", "carol"}, []int64{500, 300, 200}))
	uassert.Equal(t, int64(1000), l.TotalOwed(), "the realm must hold 1000 in reserve")

	got, _ := l.Withdraw("bob")
	uassert.Equal(t, int64(300), got)
	uassert.Equal(t, int64(700), l.TotalOwed(), "reserve drops by exactly what was paid")

	l.Credit("alice", 100)
	got, _ = l.Withdraw("alice")
	uassert.Equal(t, int64(600), got, "a later credit is included in one withdrawal")

	uassert.Equal(t, int64(200), l.TotalOwed())
	uassert.Equal(t, int64(900), l.TotalWithdrawn())
	uassert.Equal(t, "carol", strings.Join(l.Payees(), ","))
	uassert.True(t, l.Consistent())
}