netting source realm
Realm netting is a multilateral obligation clearing register in GNOT. A convenor opens a netting set and admits membe...
Realm netting is a multilateral obligation clearing register in GNOT. A convenor opens a netting set and admits members; each member declares, against other members, what it owes them; closing the set computes every member's NET position — what it is owed minus what it owes — and only those net amounts move. Net debtors pay in, net creditors withdraw, and a graph of G gross obligations collapses to at most N-1 transfers.
WHY THIS EXISTS (see DISCOVERY.md): across 641 live packages on gnoland-1 and 637 on onyx-1, thirteen chains mirrored in gnolang/tx-exports, and GitHub-wide `extension:gno`, no package records BILATERAL obligations between pairs of parties, computes net positions, or compresses gross obligations into net transfers. The two closest artifacts were read in full — mainnet p/moul/x/daily/pullpayment/v0 and r/moul/x/daily/splitter/v1 — and both fail on the same structural point: their ledgers are keyed by PAYEE ALONE, so there is no payer axis, no directed graph, and nothing to net. Both are ports of Solidity's canonical primitives, and both ports kept the one-dimensional ledger.
THE DELTA IS STATED AT ITS REAL SIZE AND NO LARGER. Multilateral netting is not a new idea — it is CLS, ACH, Sardex, the Romanian Ministry of Economy's national setoff, and a literature of graph algorithms (DISCOVERY.md § out-of-language prior art). What is new here is a Gno implementation, with this portfolio's live-validated custody discipline. Nothing more is claimed.
WHAT NETTING IS WORTH, HONESTLY: compression requires MUTUALITY. A star graph — every member owing one hub and the hub owing nobody — nets to itself, and the gross and net figures are identical. This realm therefore REPORTS the gross and net terms (Compression) and never asserts a saving. Read the two pairs of numbers; the ratio is whatever the members' obligations make it.
COMPOSITION: coin movement is delegated to coinio, fee arithmetic and the fee pot to feeledger, the declaration window and exactly-once settlement authorization to duebook, ordered storage to p/nt/avl/v0, and free-text render output to the ecosystem sanitizer p/nt/markdown/sanitize/v0. This realm owns only the netting arithmetic, the set state machine, and the conservation bookkeeping.
A NETTING SET HOLDS NO COINS WHILE IT IS OPEN. An obligation is a DECLARATION, not a transfer: Declare moves no value and locks none. Coins enter only at Settle, after the set has closed and net positions are frozen. This is why Cancel and Lapse need no refund path at all — there is nothing held to refund — and it is the sharpest difference between this realm and the escrow family the discovery gate found.
NET POSITIONS ARE MAINTAINED INCREMENTALLY, NOT COMPUTED AT CLOSE. Each Declare applies -amount to the debtor and +amount to the creditor in the same transaction, so the vector of net positions sums to zero by construction at every height. Close asserts that sum is zero anyway (netsSumToZero) before a single coin can be asked for. The assertion is unreachable through the public API and is kept because it is the one invariant whose violation would mint or destroy value.
THE SETTLEMENT IS ONE DEFERRAL. Open schedules exactly one duebook deferral per set — owner: the convenor, due: the declaration deadline, expiry: the end of the closing window — and the three transitions out of [open] are the three ways that deferral can be consumed:
Example
1Close -> book.Claim (due, not expired; ANYONE)
2Cancel -> book.Cancel (convenor renounces, while open)
3Lapse -> book.Expire (anyone, once the closing window is over)
Because duebook consumes a deferral before returning and never reuses an ID, a set can leave [open] AT MOST ONCE, structurally. The book's open-deferral cap is likewise this realm's cap on open sets.
LIFECYCLE (stored states in brackets):
Example
1Open (anyone) : opens [open]; caller is the convenor;
2 schedules the deferral.
3Admit (convenor) : adds a member, while [open]. Admission
4 obligates nobody: it only makes an
5 address a legal endpoint of a declaration.
6Declare (member) : "I owe this member X". Caller is ALWAYS
7 the debtor, so a declaration can only ever
8 increase the CALLER's own net debit. No
9 coins move.
10Close (ANYONE) : height in [deadline, closeEnd). Freezes
11 every net position. netValue == 0 (a fully
12 circular graph) settles on the spot with
13 no coins ever held -> [settled]. Otherwise
14 -> [settling] with a pay-in window.
15Settle (net debtor,+send): exactly the debtor's own net debit, once,
16 while [settling] and before settleEnd. The
17 last payment that completes the set
18 credits every net creditor -> [settled].
19Abandon (ANYONE) : [settling], settleEnd reached, still
20 short. Every debtor who paid gets exactly
21 what it paid back, FEE-FREE -> [abandoned].
22Cancel (convenor) : while [open] -> [cancelled]. No coins are
23 held, so nothing is refunded.
24Lapse (ANYONE) : [open] and closeEnd reached -> [lapsed].
25 The permissionless valve: a set nobody
26 closes cannot hold its duebook slot
27 forever.
28Withdraw (any creditor) : the caller's whole credit balance, in
29 coins. Pull-only; this realm never pushes.
30Prune (ANYONE) : removes a terminal set holding no coins.
31 The freed storage deposit is refunded by
32 the chain to the CALLER, which is the
33 incentive to call it.
34WithdrawFees (ANYONE) : pays the accrued fee pot to the
35 compile-time FeeCollector.
36SweepSurplus (ANYONE) : out-of-band coins to the FeeCollector,
37 never touching tracked liabilities.
ALL-OR-NOTHING, AND WHAT IT COSTS: a net creditor is credited only once EVERY net debtor has paid in full. One defaulting debtor therefore denies every creditor in that set — and the compensation is that no creditor is ever credited a ugnot the realm does not already hold, and every debtor who paid gets its money back fee-free. A partial-settlement design would pay some creditors from other debtors' money and need a rule for who; there is no such rule here because there is no such case.
THE FEE, precisely: feeBps is snapshotted at Open from the compile-time SettleFeeBps, so a set's terms are fixed when it is created and visible in SetInfo from that moment. It is charged ONCE, at the moment a set becomes [settled], on each net creditor's credit, with feeledger's floor rounding (rounding favors the creditor). The ledger is constructed with the compile-time MaxFeeBps cap, so a fee above the cap is refused by the primitive, not by a check in this file. There is no fee on declaring, no fee on settling, and NO FEE ON ANY ABANDON REFUND.
THERE IS NO ADMIN. The fee rate, the fee collector, every bound and every window are compile-time constants; no address can change terms, pause the realm, or touch a set it does not convene. The convenor's only powers are admitting members and cancelling its own set while it is open — neither of which can move a coin. The deployer has no privilege of any kind after deployment.
MONETARY INVARIANT (conservation): let H be the ugnot held at this realm's address, P the sum of coins paid in for sets still [settling] (tracked O(1) as totalPending), L the ledger's liabilities (unclaimed creditor credits, unclaimed abandon refunds, and the fee pot), and S >= 0 the out-of-band surplus:
Example
1H == P + L + S
Every transition moves value between exactly two terms inside one transaction: Settle raises H and P together (coinio.Receive is the receipt-guaranteed shape); completing a set moves netValue out of P and into L, split into creditor credits and the fee; Abandon moves paidIn out of P and into L fee-free; Withdraw and WithdrawFees debit L before the identical amount leaves H (checks-effects-interactions); any panic aborts the whole transaction; this realm never issues or removes coins.
ONLY GNOT IS ACCEPTED: Settle rejects any envelope that is not exactly one positive ugnot coin (coinio.Receive). Every other entrypoint rejects attached coins outright rather than converting them into sweepable surplus.
AUTHORIZATION: every identity is derived from the crossing entrypoint's cur.Previous().Address(). No function takes a caller identity as a parameter, so declaring a debt as another member, settling another member's net debit, or withdrawing another creditor's balance is impossible by construction.
STORAGE: a set record is paid for by the convenor's transaction deposit, a member record by the convenor's Admit, and a pair record by the declaring debtor's own transaction. Completing or abandoning a set drops nothing; Prune removes the whole terminal record, and the chain refunds the freed deposit to the transaction that frees it.
15
const MaxLabelLen, MaxMemoLen
const CloseWindowBlocks
CloseWindowBlocks is how long after the deadline a set may still be closed. Past it, Close is impossible (the deferral has expired) and Lapse is the only way out — which strands no money, because an open set holds none.
const Denom
Denom is the only asset this realm holds.
const FeeCollector
FeeCollector receives withdrawn fees and swept surplus. Compile-time constant: there is no setter and no transfer path. It is the deploying namespace's address — stated plainly: the operator of this realm.
const MaxFeeBps
MaxFeeBps is the hard ceiling on any fee this realm could ever charge, enforced by the feeledger the realm is constructed with — a feeBps above it is refused by the primitive's own validation, not by a check in this file. 500 bps = 5%.
const MaxMembers
MaxMembers caps one set's membership. Close iterates the member tree twice (once to assert the nets sum to zero, once to freeze positions), and completing a set iterates it once more to credit creditors, so this is the bound that keeps every O(M) pass inside a transaction's gas. 32 is deliberately modest: a clearing set is a counterparty group, not a population.
const MaxOpenPerConvenor
MaxOpenPerConvenor bounds how much of the global cap one convenor may occupy (permission_registry R1 precedent: an uncapped per-principal share of a global cap is a griefing vector, not a feature).
const MaxOpenSets
MaxOpenSets caps simultaneously open sets, via the duebook's own open-deferral cap. The AVAILABILITY BOUND this implies is stated rather than hidden: when the book is full, Open fails until a set is closed, cancelled or lapsed. Settling and terminal sets do not occupy a slot — their deferral is already consumed.
const MaxPairs
MaxPairs caps the DISTINCT ordered (debtor, creditor) pairs one set may hold. Declarations themselves are unbounded in count — a repeat declaration between an existing pair accumulates into that pair's record and allocates nothing — so this bounds storage, not activity. MaxMembers*(MaxMembers-1) == 992 is the complete digraph; 256 is a deliberate fraction of it.
const MaxRenderRows
MaxRenderRows bounds the list length on the render pages.
const MinObligation
MinObligation keeps dust declarations out of the graph: 0.001 GNOT. Declaring costs no coins, so the only thing a dust declaration wastes is the declarer's own storage deposit — but a graph full of 1-ugnot edges makes the compression figures meaningless, which is the output this realm exists to produce.
const RealmPath
RealmPath is this realm's own path, used to build Render links.
const SettleFeeBps
SettleFeeBps is the fee actually snapshotted into every set at Open: 100 bps = 1%, charged once, when the set becomes settled, on each net creditor's credit, floor-rounded in the creditor's favor. 1% is the most conservative live fee in this portfolio (fee_split precedent) and is what crowdfund charges.
const SettleWindowBlocks
SettleWindowBlocks is how long net debtors have to pay in after a set closes. Past it, Abandon refunds every payer fee-free.
34
func Abandon
crossing ActionAbandon ends a set that reached its settlement deadline still short, and credits every debtor who paid exactly what it paid, FEE-FREE. Anyone may call it: the outcome is fully determined by the set's own state, so there is nothing for a caller to steer.
Net creditors receive nothing on this path, and that is the all-or-nothing guarantee working rather than failing: they were never credited, so there is no clawback, and no creditor was ever paid from another debtor's money.
func Admit
crossing ActionAdmit adds an address to a set's membership while the set is open. Convenor only.
ADMISSION OBLIGATES NOBODY. Being a member only makes an address a legal endpoint of a declaration — it cannot be made a debtor by anyone but itself (see Declare). What admission does control is the griefing surface: without it, any address could fill a set to MaxPairs with declarations naming strangers, and the convenor could not form the group it meant to form.
func BalanceOf
ActionBalanceOf returns an address's withdrawable credit.
func Cancel
crossing ActionCancel ends an open set. Convenor only, any time while the set is open. No refund path is needed and none exists: an open set holds no coins, because a declaration is not a transfer. What members lose is the storage deposit and gas they spent declaring, which is stated plainly rather than hidden — a convenor can waste a member's gas but can never touch a member's money.
func Close
crossing ActionClose freezes every net position in a set and opens the pay-in window. Anyone may call it, from the declaration deadline until the closing window ends; the duebook Claim consumes the set's deferral, so this can succeed at most once per set, ever.
A set whose net value is ZERO — every member's obligations exactly cancelled, which is what a fully circular graph produces — settles on the spot. No coins are ever asked for, held, or paid, and the gross value is extinguished in one transaction. That case is the whole point of the realm, so it is the fast path rather than a special one.
func Compression
ActionCompression returns the four numbers the product exists to produce: how many obligations were declared and for how much, against how many transfers the netting leaves and for how much. The RATIO IS NOT RETURNED and is not asserted anywhere — divide them if you want it, and note that netValue can legitimately be zero (a fully circular graph, the best possible case), which is exactly why no ratio is computed here.
While a set is still open the net figures are zero because they are frozen at Close, not derived on read.
func Declare
crossing ActionDeclare records that the CALLER owes a fellow member `amount` ugnot, while the set is open. No coins move and none are locked: an obligation is a declaration, and the only value this realm ever holds arrives at Settle.
The caller is ALWAYS the debtor. That is the whole authorization model here and it is worth saying plainly: a declaration can only increase the caller's own net debit and some other member's net credit, so no address can be made to owe anything by anyone else. Declaring repeatedly toward the same creditor accumulates into one pair record and allocates no new storage.
func FeesAccrued
ActionFeesAccrued is the fee pot, withdrawable only to the FeeCollector.
func GrossOf
ActionGrossOf returns a member's gross declared flows: what it has declared it owes, and what others have declared they owe it. These are the uncompressed figures, kept so a reader can see what netting removed.
func Height
ActionHeight returns the chain height this realm sees, so a caller can compare it against a deadline without a second query.
func Held
ActionHeld is the realm's actual ugnot balance.
func IsMember
ActionIsMember reports whether an address is party to a set.
func Lapse
crossing ActionLapse ends an open set whose closing window has passed. Anyone may call it. This is the permissionless valve: a set nobody closes cannot hold its duebook slot forever, and because an open set holds no coins there is nothing stranded by the outcome.
func Liabilities
ActionLiabilities is everything this realm owes anyone: pending pay-ins plus unclaimed credits plus the fee pot.
func Lifetime
ActionLifetime returns the realm's cumulative counters: sets settled, gross and net value across every closed set, coins paid in, credited to creditors, refunded by Abandon, and withdrawn.
func MemberCount
ActionMemberCount returns how many addresses are party to a set.
func NetOf
ActionNetOf returns a member's live net position: positive when it is owed that much on balance, negative when it owes that much. It is live while the set is open and frozen thereafter. A non-member reads 0, which is also a member's value when its obligations cancel exactly — use IsMember to tell the two apart.
func NumSets
ActionNumSets returns how many sets have ever been opened. It is the id high-water mark, so it does not decrease when a set is pruned.
func Obligation
ActionObligation returns the cumulative amount debtor has declared it owes creditor in a set. Direction matters: Obligation(id, a, b) and Obligation(id, b, a) are different edges and both may be non-zero — the graph is directed, and netting them is Close's job, not storage's.
func Open
crossing ActionOpen convenes a netting set and returns its id. Anyone may open one; the caller becomes the convenor. The fee terms (SettleFeeBps at this moment — a compile-time constant, so always SettleFeeBps) are snapshotted into the set and are fixed from here on. declareBlocks is the length of the declaration window and must be within [MinDeclareBlocks, MaxDeclareBlocks] — enforced by the duebook.
The convenor is NOT automatically a member. A convenor that wants to net its own obligations must Admit itself, which keeps "who runs the set" and "who is party to it" separate concepts.
func OpenOf
ActionOpenOf returns how many open sets an address convenes.
func OpenSets
ActionOpenSets returns how many sets are currently open, via the duebook's own open-deferral count.
func PositionOf
ActionPositionOf returns a member's frozen settlement figures: what it must pay in, what it is owed, and what it has actually paid. All three are zero until the set is closed.
func Prune
crossing ActionPrune removes a terminal set that holds no coins, reclaiming its storage. Anyone may call it: the chain refunds the freed storage deposit to the pruning transaction, which is the incentive. Credits already in the ledger are unaffected — they are a per-address balance, not part of the set record.
func Render
Render serves the index at "" and a set page at "<id>".
func SetLabel
ActionSetLabel returns a set's label, verbatim and unsanitized. Render sanitizes; a caller reading the raw value gets the raw value.
func SetMemo
ActionSetMemo returns a set's memo, verbatim and unsanitized.
func Settle
crossing ActionSettle pays in the caller's own net debit, in full, once. The attached envelope must be exactly the caller's frozen net debit — not more, not less, and not in instalments. Partial payment is refused rather than accommodated: it would leave the set holding money that belongs to neither the payer nor any creditor, and a rule for who gets it first.
The payment that completes the set credits every net creditor in the same transaction and the set becomes settled.
func Status
ActionStatus returns a set's stored state.
func Surplus
ActionSurplus is Held minus Liabilities: out-of-band coins, sweepable to the FeeCollector. It is never negative in correct operation.
func SweepSurplus
crossing ActionSweepSurplus sends out-of-band coins to the FeeCollector: for the pot denom, everything above tracked liabilities; for any foreign denom, the full balance. Pending pay-ins, creditor credits and the fee pot are untouchable by construction (coinio.Sweep refuses to dip below the reserve). Anyone may call it.
func TotalPending
ActionTotalPending is the P term of the conservation invariant: coins paid in for sets that have not yet settled or been abandoned.
func Withdraw
crossing ActionWithdraw pays the caller its entire credit balance in coins and returns the amount. Pull-only: this realm never pushes a payout, so a creditor that cannot receive coins can never block a settlement. Credits arrive from a settled set (net of that set's fee) and from an abandoned set's refund (fee-free); both land in the same balance.
func WithdrawFees
crossing ActionWithdrawFees pays the entire accrued fee pot to the compile-time FeeCollector. Anyone may call it: the destination is fixed, so there is nothing for a caller to steer.