Liking cljdoc? Tell your friends :D

skuld.ledger.stake

Bonded proof-of-stake: delegation, rewards, unbonding, slashing.

Pure functions over a plain map. urd's consensus layer already takes a WEIGHTED validator set and already decomposes changes into TRIGGER/TRANSITION/ACTIVATION; this namespace is the economic layer that computes those weights, and nothing here touches the network or a database.

Shares, and why they are not tokens

A delegation stores SHARES, never a token amount. It exists for exactly one reason: a slash becomes validator.tokens -= x -- one write -- instead of a loop over every delegator. The exchange rate tokens/shares falls, and every delegation is diluted without being touched.

This is the same trick as the reward ratio below, and both are the answer to the same question: how do you charge or credit N delegators in O(1)?

The reward ratio is FIXED-POINT, and that is not a compromise

F1 accumulates cum(n) = SUM over periods of rewards_p / tokens_p, and the obvious Clojure move is an exact Ratio -- no truncation, no rounding, and the Cosmos SDK carries a documented 3-ulp fudge factor precisely because it could not have that.

Measured, it is catastrophic. Adding rationals multiplies denominators, and the reduced denominator grows LINEARLY in the number of periods at about 26 bits each:

10 periods       294 bits      1 ms

100 periods 2,748 bits 57 ms 400 periods 10,363 bits 365 ms

A million blocks is a multi-megabyte integer that has to be stored, hashed into the app-hash and compared every block, with superlinear arithmetic on top. Fixed-point is load-bearing, not a limitation of Go.

So: cum-ratio is an integer numerator over a constant ratio-scale. Exact rationals are still used where the quantity is BOUNDED and not accumulated -- commission and slash fractions -- where they cost nothing and remove a rounding decision.

Truncation always favours the pool, and the remainder is not lost

Every division here truncates DOWN when paying out. Paying a fraction too much is a solvency hole; paying a fraction too little leaves dust in the pool. The dust is then routed explicitly to the community pool rather than discarded, which is what lets solvent? be an equality rather than an inequality -- see check-solvency.

What makes unbonding safe

Two rules, and they are the whole security property:

an entry created AT OR AFTER the infraction height is slashable -- stake that was bonded when the offence happened cannot outrun the consequence, however fast its owner exits.

a MATURE entry is exempt -- the tokens are already paid out and gone.

Which is why max-evidence-age must not exceed unbonding-time. Cosmos matches them by convention and validates nothing; validate-params refuses the mismatch here, because a chain that accepts evidence older than its unbonding period cannot punish what the evidence proves.

Bonded proof-of-stake: delegation, rewards, unbonding, slashing.

Pure functions over a plain map. urd's consensus layer already takes a
WEIGHTED validator set and already decomposes changes into
TRIGGER/TRANSITION/ACTIVATION; this namespace is the economic layer that
computes those weights, and nothing here touches the network or a database.

## Shares, and why they are not tokens

A delegation stores SHARES, never a token amount. It exists for exactly one
reason: a slash becomes `validator.tokens -= x` -- one write -- instead of
a loop over every delegator. The exchange rate `tokens/shares` falls, and
every delegation is diluted without being touched.

This is the same trick as the reward ratio below, and both are the answer to
the same question: how do you charge or credit N delegators in O(1)?

## The reward ratio is FIXED-POINT, and that is not a compromise

F1 accumulates `cum(n) = SUM over periods of rewards_p / tokens_p`, and the
obvious Clojure move is an exact `Ratio` -- no truncation, no rounding, and
the Cosmos SDK carries a documented 3-ulp fudge factor precisely because it
could not have that.

Measured, it is catastrophic. Adding rationals multiplies denominators, and
the reduced denominator grows LINEARLY in the number of periods at about 26
bits each:

    10 periods       294 bits      1 ms
   100 periods     2,748 bits     57 ms
   400 periods    10,363 bits    365 ms

A million blocks is a multi-megabyte integer that has to be stored, hashed
into the app-hash and compared every block, with superlinear arithmetic on
top. Fixed-point is load-bearing, not a limitation of Go.

So: `cum-ratio` is an integer numerator over a constant `ratio-scale`.
Exact rationals are still used where the quantity is BOUNDED and not
accumulated -- commission and slash fractions -- where they cost nothing and
remove a rounding decision.

## Truncation always favours the pool, and the remainder is not lost

Every division here truncates DOWN when paying out. Paying a fraction too
much is a solvency hole; paying a fraction too little leaves dust in the
pool. The dust is then routed explicitly to the community pool rather than
discarded, which is what lets `solvent?` be an equality rather than an
inequality -- see `check-solvency`.

## What makes unbonding safe

Two rules, and they are the whole security property:

  an entry created AT OR AFTER the infraction height is slashable -- stake
  that was bonded when the offence happened cannot outrun the consequence,
  however fast its owner exits.

  a MATURE entry is exempt -- the tokens are already paid out and gone.

Which is why `max-evidence-age` must not exceed `unbonding-time`. Cosmos
matches them by convention and validates nothing; `validate-params` refuses
the mismatch here, because a chain that accepts evidence older than its
unbonding period cannot punish what the evidence proves.
raw docstring

active-setclj

(active-set state)

The validators that should be in the consensus set, as {id power}.

Every element of the ordering is load-bearing for determinism, and this is Cosmos's ApplyAndReturnValidatorSetUpdates reproduced deliberately:

sorted by power DESCENDING, id ASCENDING as the tiebreak -- two nodes must not disagree about which of two equal-power validators is in the set.

jailed validators excluded, because jailing IS removal from the set; it is the mechanism, not a flag consulted later.

zero power stops the scan -- a validator below one unit of power reduction cannot be represented in the set at all.

capped at max-validators.

The validators that should be in the consensus set, as `{id power}`.

Every element of the ordering is load-bearing for determinism, and this is
Cosmos's `ApplyAndReturnValidatorSetUpdates` reproduced deliberately:

  sorted by power DESCENDING, id ASCENDING as the tiebreak -- two nodes must
  not disagree about which of two equal-power validators is in the set.

  jailed validators excluded, because jailing IS removal from the set; it is
  the mechanism, not a flag consulted later.

  zero power stops the scan -- a validator below one unit of power
  reduction cannot be represented in the set at all.

  capped at `max-validators`.
raw docstring

allocateclj

(allocate state v amount)

Credit amount to v, split into commission and the delegator pool.

Three writes, and none of them touches a delegation. That is the whole point of F1: the cost of paying a validator's delegators is independent of how many there are.

Credit `amount` to `v`, split into commission and the delegator pool.

Three writes, and none of them touches a delegation. That is the whole
point of F1: the cost of paying a validator's delegators is independent of
how many there are.
raw docstring

allocate-blockclj

(allocate-block state fees commit)

Split a block's fees across the validators that PARTICIPATED in its commit.

commit is {validator {:power p :vote :commit|:nil|:absent}} -- the record of who did what, taken from the commit certificate. urd signs vote payloads, so this is cryptographic and consensus-agreed rather than a local opinion.

Why the denominator keeps absentees but the payout does not

Each validator's share is its power over the TOTAL power of the commit set, absentees included -- but an absent validator is not paid, and its share falls through to the community pool.

The alternative, dividing only among signers, pays them MORE when a peer is down. That is the shape of Sui's tallying rule, where rewards taken from a reported validator are redistributed to the reporters, and a two-thirds cartel can zero an honest validator and collect its income. Absence should cost the absent; it should not be an opportunity for everyone else.

Cosmos does neither: it ignores the vote flag entirely, so an absent validator sits in both numerator and denominator and is paid in full. Its own F1 specification names the consequence -- "one could withhold their signature for risk-free gain" -- and its AllocateTokens carries a TODO about it from 2018.

The effect here is that absence is priced CONTINUOUSLY: miss one block, lose one block's fees. Cosmos prices it as a step -- fifty free misses, then a slash -- so an operator who reboots often enough but never crosses the threshold pays nothing at all, forever.

Split a block's fees across the validators that PARTICIPATED in its commit.

`commit` is `{validator {:power p :vote :commit|:nil|:absent}}` -- the record
of who did what, taken from the commit certificate. urd signs vote payloads,
so this is cryptographic and consensus-agreed rather than a local opinion.

## Why the denominator keeps absentees but the payout does not

Each validator's share is its power over the TOTAL power of the commit set,
absentees included -- but an absent validator is not paid, and its share
falls through to the community pool.

The alternative, dividing only among signers, pays them MORE when a peer is
down. That is the shape of Sui's tallying rule, where rewards taken from a
reported validator are redistributed to the reporters, and a two-thirds
cartel can zero an honest validator and collect its income. Absence should
cost the absent; it should not be an opportunity for everyone else.

Cosmos does neither: it ignores the vote flag entirely, so an absent
validator sits in both numerator and denominator and is paid in full. Its
own F1 specification names the consequence -- "one could withhold their
signature for risk-free gain" -- and its `AllocateTokens` carries a TODO
about it from 2018.

The effect here is that absence is priced CONTINUOUSLY: miss one block, lose
one block's fees. Cosmos prices it as a step -- fifty free misses, then a
slash -- so an operator who reboots often enough but never crosses the
threshold pays nothing at all, forever.
raw docstring

apply-set-changesclj

(apply-set-changes state)

Move validators between bonded and unbonding to match the active set.

This is the half of Cosmos's ApplyAndReturnValidatorSetUpdates that changes STATE, as distinct from set-updates which computes the deltas the consensus layer is told about. Both read the same active-set, so they cannot disagree.

Without it there was no bonding path at all: create-validator produced an :unbonded validator, delegate never changed status, and consensus power is zero unless bonded -- so a freshly staked validator was invisible forever and every test set :bonded by hand.

Bonded -> Unbonded directly is deliberately impossible. A validator leaving the set passes through :unbonding, and that window is the whole reason retroactive slashing has anything left to slash.

Move validators between bonded and unbonding to match the active set.

This is the half of Cosmos's `ApplyAndReturnValidatorSetUpdates` that
changes STATE, as distinct from `set-updates` which computes the deltas the
consensus layer is told about. Both read the same `active-set`, so they
cannot disagree.

Without it there was no bonding path at all: `create-validator` produced an
`:unbonded` validator, `delegate` never changed status, and consensus power
is zero unless bonded -- so a freshly staked validator was invisible
forever and every test set `:bonded` by hand.

`Bonded -> Unbonded` directly is deliberately impossible. A validator
leaving the set passes through `:unbonding`, and that window is the whole
reason retroactive slashing has anything left to slash.
raw docstring

assert-representable!clj

(assert-representable! set* max-total)

Refuse a set whose total power the consensus layer cannot carry.

urd.consensus.reconfig/max-total-power is not a BFT bound -- it is arithmetic headroom for the proposer-priority accumulator, kept well below the platform maximum because ClojureScript numbers are doubles and exact integers hold only to 2^53. Discovering that at scale would mean a divergence between platforms; discovering it here means a parameter is wrong.

Refuse a set whose total power the consensus layer cannot carry.

`urd.consensus.reconfig/max-total-power` is not a BFT bound -- it is
arithmetic headroom for the proposer-priority accumulator, kept well below
the platform maximum because ClojureScript numbers are doubles and exact
integers hold only to 2^53. Discovering that at scale would mean a
divergence between platforms; discovering it here means a parameter is
wrong.
raw docstring

check-solvencyclj

(check-solvency state total-issued)

What the system owes versus what it has recorded.

Cosmos asserts this only at genesis; it is the invariant the whole crisis module existed to protect, and with an app-hash it costs nothing to check every commit. Returns a map so a failure can be attributed rather than merely detected.

What the system owes versus what it has recorded.

Cosmos asserts this only at genesis; it is the invariant the whole crisis
module existed to protect, and with an app-hash it costs nothing to check
every commit. Returns a map so a failure can be attributed rather than
merely detected.
raw docstring

commit-setclj

(commit-set state)

Adopt the current active set as the baseline for the next diff.

Adopt the current active set as the baseline for the next diff.
raw docstring

complete-unbondingclj

(complete-unbonding state d v)

Pay out every matured entry for [d v]. Returns [state amount].

Pay out every matured entry for `[d v]`. Returns `[state amount]`.
raw docstring

complete-validator-unbondingclj

(complete-validator-unbonding state)

Move validators whose unbonding window has elapsed to :unbonded.

Only here does a validator stop being slashable, which is why the check is on BOTH height and time, and why slash refuses an :unbonded validator: its stake has been released.

Move validators whose unbonding window has elapsed to `:unbonded`.

Only here does a validator stop being slashable, which is why the check is
on BOTH height and time, and why `slash` refuses an `:unbonded` validator:
its stake has been released.
raw docstring

consensus-updatesclj

(consensus-updates state)

set-updates in the shape urd.consensus.reconfig expects.

A sequence of {:id ... :power n}, power zero meaning removal. reconfig dedupes and sorts by (str :id) itself -- deliberately, because CometBFT #3181 was two honest nodes disagreeing about the proposer after the application emitted updates in different orders. We therefore do NOT sort here: doing it in one place is what makes the property hold regardless of what any caller does.

These ride on the proposed value as :validator-updates, which is the TRIGGER; consensus applies them when the value is decided, which is the ACTIVATION. The split is what stops a validator set changing on an un-decided proposal.

`set-updates` in the shape `urd.consensus.reconfig` expects.

A sequence of `{:id ... :power n}`, power zero meaning removal. `reconfig`
dedupes and sorts by `(str :id)` itself -- deliberately, because CometBFT
#3181 was two honest nodes disagreeing about the proposer after the
application emitted updates in different orders. We therefore do NOT sort
here: doing it in one place is what makes the property hold regardless of
what any caller does.

These ride on the proposed value as `:validator-updates`, which is the
TRIGGER; consensus applies them when the value is decided, which is the
ACTIVATION. The split is what stops a validator set changing on an
un-decided proposal.
raw docstring

create-validatorclj

(create-validator state v commission)

Register v with a commission rate (an exact rational in [0,1]).

Register `v` with a commission rate (an exact rational in [0,1]).
raw docstring

default-issuanceclj

Fee-only by default.

Deliberately zero, so a deployment that has not decided its monetary policy gets the behaviour it did before this existed rather than a rate nobody chose. Fee-only is also the right answer for a permissioned or consortium launch, where the validator set is known and there is no security budget to bootstrap.

Data, not a function: a strategy stored as a closure could not be serialised into the app-hash, compared between nodes, or replayed from genesis.

Fee-only by default.

Deliberately zero, so a deployment that has not decided its monetary policy
gets the behaviour it did before this existed rather than a rate nobody
chose. Fee-only is also the right answer for a permissioned or consortium
launch, where the validator set is known and there is no security budget to
bootstrap.

Data, not a function: a strategy stored as a closure could not be serialised
into the app-hash, compared between nodes, or replayed from genesis.
raw docstring

default-paramsclj


delegateclj

(delegate state d v amount)

Bond amount from d to v. Returns state.

Settles any existing rewards first, so the delegation's stake snapshot is never stale across a share change.

Bond `amount` from `d` to `v`. Returns state.

Settles any existing rewards first, so the delegation's stake snapshot is
never stale across a share change.
raw docstring

delegation-rewardsclj

(delegation-rewards state d v end-period)

What [d v] has earned since its start period.

(cum_end - cum_start) x stake, split at every slash so the stake is rescaled for each sub-interval. A slash between entry and withdrawal means the delegation held fewer real tokens for the later part, and paying on the original stake would pay rewards the validator never accrued.

The rescaling has to CARRY

The obvious implementation reduces over the slashes to rescale the stake, then computes the final segment from the ORIGINAL snapshot. That is wrong with more than one slash: it pays on stake x (1 - f_last) rather than stake x PRODUCT(1 - f_i). Two halvings then become one halving, and the delegation claims twice what it earned.

It is not caught by the min raw available cap at the withdrawal site either -- that turns over-payment into a RACE, where the first delegator to withdraw drains the pool and the rest get nothing. The running stake is threaded through to the final segment here, as x/distribution/keeper/delegation.go:141 does.

What `[d v]` has earned since its start period.

`(cum_end - cum_start) x stake`, split at every slash so the stake is
rescaled for each sub-interval. A slash between entry and withdrawal means
the delegation held fewer real tokens for the later part, and paying on the
original stake would pay rewards the validator never accrued.

## The rescaling has to CARRY

The obvious implementation reduces over the slashes to rescale the stake,
then computes the final segment from the ORIGINAL snapshot. That is wrong
with more than one slash: it pays on `stake x (1 - f_last)` rather than
`stake x PRODUCT(1 - f_i)`. Two halvings then become one halving, and the
delegation claims twice what it earned.

It is not caught by the `min raw available` cap at the withdrawal site
either -- that turns over-payment into a RACE, where the first delegator to
withdraw drains the pool and the rest get nothing. The running stake is
threaded through to the final segment here, as
`x/distribution/keeper/delegation.go:141` does.
raw docstring

handle-equivocationclj

(handle-equivocation state v infraction-height power-at evidence-age)

Slash, jail and TOMBSTONE v for double-signing at infraction-height.

Stake slashing is reserved for this, and the reason is the asymmetry Cosmos documents well: a fault detected IMMEDIATELY needs no cap, because the jail-then-unjail cycle serialises it and the validator cannot commit another while jailed. A fault detected with a DELAY can be discovered many times over for one key compromise -- misconfigure an HSM, double-sign a hundred old blocks -- so it needs a cap, and the tombstone is that cap. You are punished for the first one and then permanently removed.

Refused outright if the evidence is older than the unbonding period: the stake it names has been paid out, so there is nothing left to slash. validate-params guarantees the two windows are compatible; this is the per-item check.

Slash, jail and TOMBSTONE `v` for double-signing at `infraction-height`.

Stake slashing is reserved for this, and the reason is the asymmetry Cosmos
documents well: a fault detected IMMEDIATELY needs no cap, because the
jail-then-unjail cycle serialises it and the validator cannot commit another
while jailed. A fault detected with a DELAY can be discovered many times
over for one key compromise -- misconfigure an HSM, double-sign a hundred
old blocks -- so it needs a cap, and the tombstone is that cap. You are
punished for the first one and then permanently removed.

Refused outright if the evidence is older than the unbonding period: the
stake it names has been paid out, so there is nothing left to slash.
`validate-params` guarantees the two windows are compatible; this is the
per-item check.
raw docstring

initclj

(init)
(init params)

A chain with no validators and no stake.

A chain with no validators and no stake.
raw docstring

issuancecljmultimethod

New tokens to mint for this block, as a function of state.

The one structural decision, taken from Cosmos: issuance and fees are the SAME STREAM. Newly minted tokens are added to the block's pool and flow through exactly the same distribution path -- there is no separate block-reward mechanism. That is why switching between fee-only and hybrid is a parameter here rather than a second settlement path.

New tokens to mint for this block, as a function of state.

The one structural decision, taken from Cosmos: issuance and fees are the
SAME STREAM. Newly minted tokens are added to the block's pool and flow
through exactly the same distribution path -- there is no separate
block-reward mechanism. That is why switching between fee-only and hybrid is
a parameter here rather than a second settlement path.
raw docstring

jailclj

(jail state v until)

Remove v from the active set until until.

Jailing is a boolean and a removal from the power index -- everything else follows from having no power. Delegations are untouched and accrued rewards stay withdrawable; the validator and its delegators simply stop earning.

Remove `v` from the active set until `until`.

Jailing is a boolean and a removal from the power index -- everything else
follows from having no power. Delegations are untouched and accrued rewards
stay withdrawable; the validator and its delegators simply stop earning.
raw docstring

liveness-defaultsclj

How much absence is tolerated before a validator is removed from the set.

A window and a threshold, exactly as Cosmos does it, because the ring-buffer structure is genuinely good: O(1) per block, O(window) storage, and the counter is a cached popcount so the common case reads nothing.

What is NOT copied is the downtime SLASH. With participation-weighted rewards, absence is already priced continuously -- every missed block costs its fees. Slashing on top charges twice for one fault, and the charge lands mostly on delegators who did nothing. Jailing remains, because its job is different: it removes a validator that is hurting liveness from the set.

How much absence is tolerated before a validator is removed from the set.

A window and a threshold, exactly as Cosmos does it, because the ring-buffer
structure is genuinely good: O(1) per block, O(window) storage, and the
counter is a cached popcount so the common case reads nothing.

What is NOT copied is the downtime SLASH. With participation-weighted
rewards, absence is already priced continuously -- every missed block costs
its fees. Slashing on top charges twice for one fault, and the charge lands
mostly on delegators who did nothing. Jailing remains, because its job is
different: it removes a validator that is hurting liveness from the set.
raw docstring

mintclj

(mint state)

Issue this block's tokens into the pool, recording the increase in supply.

:issued is what check-solvency measures against, so minting must go through here -- crediting the pool without growing the recorded supply would read as insolvency one block later.

Issue this block's tokens into the pool, recording the increase in supply.

`:issued` is what `check-solvency` measures against, so minting must go
through here -- crediting the pool without growing the recorded supply would
read as insolvency one block later.
raw docstring

participating?clj

Which votes count as showing up.

:commit endorsed the block. :nil voted, and voted against -- it showed up and did its job, it simply did not like the proposal. Counting that as absence would punish honest disagreement during a fork, which is the one moment a chain most needs validators to speak freely. Liveness measures PARTICIPATION, not agreement.

Cosmos reaches the same conclusion (only BlockIDFlagAbsent is a miss) but documents no reason anywhere -- no comment, no ADR, and no test exercising nil in either slashing or distribution. Ethereum's structure agrees implicitly, rewarding source and target votes even when the head vote differs. Written down here because it is a real decision, not a default.

Which votes count as showing up.

`:commit` endorsed the block. `:nil` voted, and voted against -- it showed
up and did its job, it simply did not like the proposal. Counting that as
absence would punish honest disagreement during a fork, which is the one
moment a chain most needs validators to speak freely. Liveness measures
PARTICIPATION, not agreement.

Cosmos reaches the same conclusion (only `BlockIDFlagAbsent` is a miss) but
documents no reason anywhere -- no comment, no ADR, and no test exercising
nil in either slashing or distribution. Ethereum's structure agrees
implicitly, rewarding source and target votes even when the head vote
differs. Written down here because it is a real decision, not a default.
raw docstring

potential-powerclj

(potential-power state v)

What a validator's stake WOULD be worth if it were in the set.

The distinction from power breaks a circularity that made the set uncomputable: consensus power is zero unless bonded, bonding depends on being in the top N by power, and if the ranking used consensus power then nothing unbonded could ever rank. Cosmos keeps a power index over potential power for exactly this reason and assigns status afterwards.

A jailed validator has none: jailing IS removal from the set.

What a validator's stake WOULD be worth if it were in the set.

The distinction from `power` breaks a circularity that made the set
uncomputable: consensus power is zero unless bonded, bonding depends on
being in the top N by power, and if the ranking used consensus power then
nothing unbonded could ever rank. Cosmos keeps a power index over potential
power for exactly this reason and assigns status afterwards.

A jailed validator has none: jailing IS removal from the set.
raw docstring

powerclj

(power state v)

Consensus voting power: bonded tokens divided by the power reduction.

Integer division, so a validator below one full unit of reduction has ZERO power and is simply not in the set. That is deliberate -- it keeps the weight small enough for the consensus layer's total-power bound.

Consensus voting power: bonded tokens divided by the power reduction.

Integer division, so a validator below one full unit of reduction has ZERO
power and is simply not in the set. That is deliberate -- it keeps the
weight small enough for the consensus layer's total-power bound.
raw docstring

ratio-scaleclj

Fixed-point denominator for the cumulative reward ratio.

10^18, matching the SDK's LegacyDec. Large enough that a single block's reward-per-token is representable for any realistic stake, small enough that the numerator stays a machine-friendly integer for centuries.

Fixed-point denominator for the cumulative reward ratio.

10^18, matching the SDK's `LegacyDec`. Large enough that a single block's
reward-per-token is representable for any realistic stake, small enough that
the numerator stays a machine-friendly integer for centuries.
raw docstring

record-voteclj

(record-vote state v vote)

Record whether v participated in the commit at the current height.

Jails on crossing the threshold. Returns state.

The grace period is a start-height bump rather than a counter reset: a newly bonded validator is not jailable until a full window has passed, which is what stops it being punished for blocks it was not present for.

Record whether `v` participated in the commit at the current height.

Jails on crossing the threshold. Returns state.

The grace period is a `start-height` bump rather than a counter reset: a
newly bonded validator is not jailable until a full window has passed, which
is what stops it being punished for blocks it was not present for.
raw docstring

set-updatesclj

(set-updates state)

Deltas to hand urd.consensus.reconfig/apply-updates, as {id power}.

Only CHANGES are emitted, and a removal is a power of zero -- which is why the previous set has to be persisted: without it, a validator that dropped out is indistinguishable from one that was never there, and no removal would ever be emitted.

Deltas to hand `urd.consensus.reconfig/apply-updates`, as `{id power}`.

Only CHANGES are emitted, and a removal is a power of zero -- which is why
the previous set has to be persisted: without it, a validator that dropped
out is indistinguishable from one that was never there, and no removal would
ever be emitted.
raw docstring

share-scaleclj

Shares are integers in units of 1e-18 of a share.

Not exact rationals, and for the same measured reason the reward ratio is fixed-point: a validator's total shares accumulate over every delegation, so rational denominators would compound. Scaled integers keep every share computation in integer arithmetic with one truncation rule.

Arithmetic on shares uses auto-promoting *' and BigInt, because at this scale a single ordinary delegation overflows a long: 10^6 tokens x 10^18 is 10^24. Tokens themselves stay longs -- only the share space is scaled.

Shares are integers in units of 1e-18 of a share.

Not exact rationals, and for the same measured reason the reward ratio is
fixed-point: a validator's total shares accumulate over every delegation, so
rational denominators would compound. Scaled integers keep every share
computation in integer arithmetic with one truncation rule.

Arithmetic on shares uses auto-promoting `*'` and BigInt, because at this
scale a single ordinary delegation overflows a long: 10^6 tokens x 10^18 is
10^24. Tokens themselves stay longs -- only the share space is scaled.
raw docstring

slashclj

(slash state v infraction-height power-at fraction)

Slash v for an infraction at infraction-height, given the POWER it held at that height.

power-at is an argument and not something recomputed from current stake, which is the whole point. Deriving it from tokens now is wrong in both directions: stake that arrived AFTER the offence would be punished for it (measured: a 10x over-slash landing entirely on a delegator who joined later), and stake that left between offence and evidence would shrink the penalty -- which is precisely the escape route the unbonding rules exist to close. Cosmos takes power as a parameter for the same reason (x/staking/keeper/slash.go:36).

Order matters: unbonding entries are slashed first and their NOTIONAL subtracted, then whatever remains is burned from the validator itself.

Slash `v` for an infraction at `infraction-height`, given the POWER it held
at that height.

`power-at` is an argument and not something recomputed from current stake,
which is the whole point. Deriving it from `tokens` now is wrong in both
directions: stake that arrived AFTER the offence would be punished for it
(measured: a 10x over-slash landing entirely on a delegator who joined
later), and stake that left between offence and evidence would shrink the
penalty -- which is precisely the escape route the unbonding rules exist to
close. Cosmos takes power as a parameter for the same reason
(`x/staking/keeper/slash.go:36`).

Order matters: unbonding entries are slashed first and their NOTIONAL
subtracted, then whatever remains is burned from the validator itself.
raw docstring

tokens-forclj

(tokens-for {:keys [tokens shares]} s)

Tokens s shares are currently worth, truncated DOWN.

Truncating up would let the last delegator out withdraw more than the validator holds.

Tokens `s` shares are currently worth, truncated DOWN.

Truncating up would let the last delegator out withdraw more than the
validator holds.
raw docstring

undelegateclj

(undelegate state d v shares)

Begin unbonding shares of [d v]. Returns [state tokens].

Creates an entry stamped with the CURRENT height, which is what makes it retroactively slashable for anything that happened at or after it.

Begin unbonding `shares` of `[d v]`. Returns `[state tokens]`.

Creates an entry stamped with the CURRENT height, which is what makes it
retroactively slashable for anything that happened at or after it.
raw docstring

unjailclj

(unjail state v)

Return v to the set. The operator's call, and only after the jail expires.

Refused for a tombstoned validator: equivocation is permanent, and that is the whole difference between the two punishments.

Return `v` to the set. The operator's call, and only after the jail expires.

Refused for a tombstoned validator: equivocation is permanent, and that is
the whole difference between the two punishments.
raw docstring

validate-paramsclj

(validate-params {:keys [unbonding-time max-evidence-age max-entries]
                  :as params})

Refuse a configuration that cannot punish what it can prove.

Evidence older than the unbonding period names stake that has already been paid out, so accepting it produces a slash that cannot be collected. Cosmos ships 3 weeks of evidence against 21 days of unbonding and enforces the relation nowhere -- a latent misconfiguration that is free to close here.

Refuse a configuration that cannot punish what it can prove.

Evidence older than the unbonding period names stake that has already been
paid out, so accepting it produces a slash that cannot be collected. Cosmos
ships 3 weeks of evidence against 21 days of unbonding and enforces the
relation nowhere -- a latent misconfiguration that is free to close here.
raw docstring

withdraw-rewardsclj

(withdraw-rewards state d v)

Settle [d v]. Returns [state amount].

The delegation is re-initialised at the current period afterwards, so its stake snapshot is refreshed. Every path that changes shares calls this first -- that pairing is what makes the snapshot trustworthy.

Settle `[d v]`. Returns `[state amount]`.

The delegation is re-initialised at the current period afterwards, so its
`stake` snapshot is refreshed. Every path that changes shares calls this
first -- that pairing is what makes the snapshot trustworthy.
raw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close