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/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/mimir"
gno = "0.9"

[addpkg]
  creator = "g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz"
  height = 1353478
  max_deposit = "500000000ugnot"

json.gno

package mimir

import "strings"

const hexDigits = "0123456789abcdef"

// Quote returns s as a JSON string literal.
func Quote(s string) string {
	var b strings.Builder
	b.WriteByte('"')
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c == '"' || c == '\\':
			b.WriteByte('\\')
			b.WriteByte(c)
		case c == '\n':
			b.WriteString(`\n`)
		case c == '\r':
			b.WriteString(`\r`)
		case c == '\t':
			b.WriteString(`\t`)
		case c < 0x20:
			b.WriteString(`\u00`)
			b.WriteByte(hexDigits[c>>4])
			b.WriteByte(hexDigits[c&0xf])
		default:
			b.WriteByte(c)
		}
	}
	b.WriteByte('"')
	return b.String()
}

// Escape makes user text safe to place in gnoweb markdown: it cannot open
// links, images, HTML or headings.
func Escape(s string) string {
	r := strings.NewReplacer(
		"\\", "\\\\", "[", "\\[", "]", "\\]", "(", "\\(", ")", "\\)",
		"<", "&lt;", ">", "&gt;", "*", "\\*", "_", "\\_", "`", "\\`",
		"#", "\\#", "|", "\\|", "\n", " ", "\r", " ",
	)
	return r.Replace(s)
}

// FormatUSD renders 6-decimal units as a dollar amount with two decimals, rounded down.
func FormatUSD(units int64) string {
	sign := ""
	if units < 0 {
		sign = "-"
		units = -units
	}
	cents := units / 10_000
	frac := cents % 100
	s := sign + itoa(cents/100) + "."
	if frac < 10 {
		s += "0"
	}
	return s + itoa(frac)
}

func itoa(n int64) string {
	if n == 0 {
		return "0"
	}
	var buf [20]byte
	i := len(buf)
	for n > 0 {
		i--
		buf[i] = byte('0' + n%10)
		n /= 10
	}
	return string(buf[i:])
}

math.gno

package mimir

import "math/bits"

// MulDiv returns floor(a*b/d) without overflowing the 128-bit product.
// It panics on negative inputs, a zero divisor or a result above int64.
func MulDiv(a, b, d int64) int64 {
	if a < 0 || b < 0 || d <= 0 {
		panic("mimir: MulDiv needs a, b >= 0 and d > 0")
	}
	hi, lo := bits.Mul64(uint64(a), uint64(b))
	if hi >= uint64(d) {
		panic("mimir: MulDiv overflow")
	}
	q, _ := bits.Div64(hi, lo, uint64(d))
	if q > uint64(1<<63-1) {
		panic("mimir: MulDiv overflow")
	}
	return int64(q)
}

// Add returns a+b, panicking on overflow, so a sum of stakes can never wrap.
func Add(a, b int64) int64 {
	c := a + b
	if (b > 0 && c < a) || (b < 0 && c > a) {
		panic("mimir: add overflow")
	}
	return c
}

mimir_test.gno

package mimir

import (
	"testing"

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

func TestHistoryBefore(t *testing.T) {
	var h History
	uassert.Equal(t, int64(0), h.Before(0).A)

	h.Record(100, Amounts{A: 1})
	h.Record(100, Amounts{A: 2}) // same second coalesces
	h.Record(200, Amounts{A: 2, B: 5})
	h.Record(300, Amounts{A: 7, B: 5})
	uassert.Equal(t, 3, h.Len())

	uassert.Equal(t, int64(7), h.Before(0).A)   // no cutoff: latest
	uassert.Equal(t, int64(0), h.Before(100).A) // strictly before 100: nothing
	uassert.Equal(t, int64(2), h.Before(101).A) // the coalesced checkpoint
	uassert.Equal(t, int64(0), h.Before(200).B) // 200 itself is excluded
	uassert.Equal(t, int64(5), h.Before(250).B)
	uassert.Equal(t, int64(7), h.Before(1000).A)
}

func TestMulDiv(t *testing.T) {
	uassert.Equal(t, int64(6), MulDiv(4, 3, 2))
	uassert.Equal(t, int64(3), MulDiv(10, 1, 3)) // rounds down
	big := int64(1) << 62
	uassert.Equal(t, big, MulDiv(big, big, big)) // 124-bit product
	uassert.PanicsContains(t, nil, "overflow", func() { MulDiv(big, big, 1) })
	uassert.PanicsContains(t, nil, "d > 0", func() { MulDiv(1, 1, 0) })
}

func TestAdd(t *testing.T) {
	uassert.Equal(t, int64(3), Add(1, 2))
	uassert.PanicsContains(t, nil, "overflow", func() { Add(1<<62, 1<<62) })
}

roles.gno

package mimir

import (
	"chain"
	"strconv"
)

// TimelockSeconds delays ownership, oracle and fee-recipient changes.
const TimelockSeconds = int64(2 * 24 * 60 * 60)

// Roles holds a market realm's roles, pause flag and guarded-launch caps, and
// enforces the same rules the EVM contracts do:
//   - two-step ownership with a timelock;
//   - a timelocked oracle change the owner can revoke at once;
//   - the oracle is never also the owner, the arbiter or the fee recipient;
//   - the audit agent may only dispute, and never holds another role;
//   - a timelocked fee-recipient change;
//   - queued changes are executed by anyone once due.
//
// Every method takes the caller and the block time from the realm, which
// owns the Roles value.
type Roles struct {
	Owner               address
	Arbiter             address
	AuditAgent          address
	Oracle              address
	FeeRecipient        address
	PendingOwner        address
	PendingOwnerEta     int64
	PendingOracle       address
	PendingOracleEta    int64
	PendingFeeRecipient address
	PendingFeeEta       int64
	Paused              bool
	MaxAccountStake     int64
	MaxMarketStake      int64
}

// NewRoles validates the initial roles as the EVM constructors did.
func NewRoles(owner, arbiter, oracle, feeRecipient address) *Roles {
	if !owner.IsValid() || !arbiter.IsValid() || !oracle.IsValid() || !feeRecipient.IsValid() {
		panic("ZeroAddress")
	}
	if oracle == owner || oracle == arbiter || oracle == feeRecipient {
		panic("RoleCollision")
	}
	chain.Emit("OwnershipTransferred", "previous", "", "next", owner.String())
	chain.Emit("ArbiterChanged", "previous", "", "next", arbiter.String())
	chain.Emit("OracleChanged", "previous", "", "next", oracle.String())
	chain.Emit("FeeRecipientChanged", "previous", "", "next", feeRecipient.String())
	return &Roles{Owner: owner, Arbiter: arbiter, Oracle: oracle, FeeRecipient: feeRecipient}
}

func i64(n int64) string { return strconv.FormatInt(n, 10) }

func (r *Roles) AssertOwner(caller address) {
	if caller != r.Owner {
		panic("NotOwner")
	}
}

func (r *Roles) AssertOracle(caller address) {
	if r.Oracle == "" || caller != r.Oracle {
		panic("NotOracle")
	}
}

func (r *Roles) AssertArbiter(caller address) {
	if caller != r.Arbiter {
		panic("NotArbiter")
	}
}

func (r *Roles) AssertNotPaused() {
	if r.Paused {
		panic("IsPaused")
	}
}

func (r *Roles) checkAuditCollision(next address) {
	if next != "" && next == r.AuditAgent {
		panic("RoleCollision")
	}
}

func (r *Roles) TransferOwnership(caller, next address, now int64) {
	r.AssertOwner(caller)
	if !next.IsValid() {
		panic("ZeroAddress")
	}
	r.PendingOwner = next
	r.PendingOwnerEta = now + TimelockSeconds
	chain.Emit("OwnershipTransferStarted", "previous", r.Owner.String(), "next", next.String(), "eta", i64(r.PendingOwnerEta))
}

func (r *Roles) CancelOwnershipTransfer(caller address) {
	r.AssertOwner(caller)
	if r.PendingOwnerEta == 0 {
		panic("NothingQueued")
	}
	chain.Emit("OwnershipTransferCancelled", "pending", r.PendingOwner.String())
	r.PendingOwner = ""
	r.PendingOwnerEta = 0
}

func (r *Roles) AcceptOwnership(caller address, now int64) {
	if r.PendingOwner == "" || caller != r.PendingOwner {
		panic("NotPendingOwner")
	}
	if now < r.PendingOwnerEta {
		panic("Timelocked")
	}
	r.checkAuditCollision(caller)
	chain.Emit("OwnershipTransferred", "previous", r.Owner.String(), "next", caller.String())
	r.Owner = caller
	r.PendingOwner = ""
	r.PendingOwnerEta = 0
}

func (r *Roles) QueueOracle(caller, next address, now int64) {
	r.AssertOwner(caller)
	if !next.IsValid() {
		panic("ZeroAddress")
	}
	if next == r.Owner || next == r.Arbiter || next == r.FeeRecipient {
		panic("RoleCollision")
	}
	r.PendingOracle = next
	r.PendingOracleEta = now + TimelockSeconds
	chain.Emit("OracleChangeQueued", "next", next.String(), "eta", i64(r.PendingOracleEta))
}

// RevokeOracle is the emergency stop: the oracle loses its power at once.
func (r *Roles) RevokeOracle(caller address) {
	r.AssertOwner(caller)
	chain.Emit("OracleChanged", "previous", r.Oracle.String(), "next", "")
	r.Oracle = ""
}

func (r *Roles) CancelOracle(caller address) {
	r.AssertOwner(caller)
	if r.PendingOracleEta == 0 {
		panic("NothingQueued")
	}
	chain.Emit("OracleChangeCancelled", "next", r.PendingOracle.String())
	r.PendingOracle = ""
	r.PendingOracleEta = 0
}

func (r *Roles) ExecuteOracle(now int64) {
	if r.PendingOracleEta == 0 {
		panic("NothingQueued")
	}
	if now < r.PendingOracleEta {
		panic("Timelocked")
	}
	r.checkAuditCollision(r.PendingOracle)
	chain.Emit("OracleChanged", "previous", r.Oracle.String(), "next", r.PendingOracle.String())
	r.Oracle = r.PendingOracle
	r.PendingOracle = ""
	r.PendingOracleEta = 0
}

// SetAuditAgent appoints the reviewer that may dispute with a bond; "" disables it.
func (r *Roles) SetAuditAgent(caller, next address) {
	r.AssertOwner(caller)
	if next != "" && (next == r.Owner || next == r.Arbiter || next == r.Oracle || next == r.FeeRecipient) {
		panic("RoleCollision")
	}
	chain.Emit("AuditAgentChanged", "previous", r.AuditAgent.String(), "next", next.String())
	r.AuditAgent = next
}

func (r *Roles) SetArbiter(caller, next address) {
	r.AssertOwner(caller)
	if !next.IsValid() {
		panic("ZeroAddress")
	}
	if next == r.Oracle {
		panic("RoleCollision")
	}
	r.checkAuditCollision(next)
	chain.Emit("ArbiterChanged", "previous", r.Arbiter.String(), "next", next.String())
	r.Arbiter = next
}

// SetCaps sets guarded launch caps in mUSD units (0 = none). They only gate new positions.
func (r *Roles) SetCaps(caller address, market, account int64) {
	r.AssertOwner(caller)
	if market < 0 || account < 0 {
		panic("BadCap")
	}
	r.MaxMarketStake = market
	r.MaxAccountStake = account
	chain.Emit("CapsChanged", "maxMarketStake", i64(market), "maxAccountStake", i64(account))
}

// CheckCaps panics when an account's stake or a market's total is over its cap.
func (r *Roles) CheckCaps(mine, total int64) {
	if (r.MaxAccountStake != 0 && mine > r.MaxAccountStake) || (r.MaxMarketStake != 0 && total > r.MaxMarketStake) {
		panic("CapExceeded")
	}
}

func (r *Roles) QueueFeeRecipient(caller, next address, now int64) {
	r.AssertOwner(caller)
	if !next.IsValid() {
		panic("ZeroAddress")
	}
	r.PendingFeeRecipient = next
	r.PendingFeeEta = now + TimelockSeconds
	chain.Emit("FeeRecipientQueued", "next", next.String(), "eta", i64(r.PendingFeeEta))
}

func (r *Roles) CancelFeeRecipient(caller address) {
	r.AssertOwner(caller)
	if r.PendingFeeEta == 0 {
		panic("NothingQueued")
	}
	chain.Emit("FeeRecipientCancelled", "next", r.PendingFeeRecipient.String())
	r.PendingFeeRecipient = ""
	r.PendingFeeEta = 0
}

func (r *Roles) ExecuteFeeRecipient(now int64) {
	if r.PendingFeeEta == 0 {
		panic("NothingQueued")
	}
	if now < r.PendingFeeEta {
		panic("Timelocked")
	}
	r.checkAuditCollision(r.PendingFeeRecipient)
	chain.Emit("FeeRecipientChanged", "previous", r.FeeRecipient.String(), "next", r.PendingFeeRecipient.String())
	r.FeeRecipient = r.PendingFeeRecipient
	r.PendingFeeRecipient = ""
	r.PendingFeeEta = 0
}

func (r *Roles) SetPaused(caller address, p bool) {
	r.AssertOwner(caller)
	r.Paused = p
	if p {
		chain.Emit("Paused", "paused", "true")
	} else {
		chain.Emit("Paused", "paused", "false")
	}
}

// ParseOptional reads an optional address argument: "" means none.
func ParseOptional(s string) address {
	if s == "" {
		return ""
	}
	a := address(s)
	if !a.IsValid() {
		panic("BadAddress")
	}
	return a
}

stakehistory.gno

// Package mimir holds the pure helpers Mimir's market realms share: stake
// history checkpoints (settlement cutoffs) and overflow-safe arithmetic.
package mimir

// Amounts are cumulative net deposits on each side, and the copied part of each.
type Amounts struct {
	A, B, CopiedA, CopiedB int64
}

type Checkpoint struct {
	At      int64 // unix seconds
	Amounts Amounts
}

// History is an append-only list of checkpoints in time order. Deposits in the
// same second coalesce into one checkpoint. Settlement never scans all deposits.
type History struct {
	points []Checkpoint
}

// Record stores the running totals as of `now`.
func (h *History) Record(now int64, a Amounts) {
	n := len(h.points)
	if n != 0 && h.points[n-1].At == now {
		h.points[n-1].Amounts = a
		return
	}
	h.points = append(h.points, Checkpoint{At: now, Amounts: a})
}

// Before returns the totals recorded strictly before cutoff. A cutoff of 0
// means no cutoff: the latest totals.
func (h *History) Before(cutoff int64) Amounts {
	hi := len(h.points)
	if hi == 0 {
		return Amounts{}
	}
	if cutoff == 0 {
		return h.points[hi-1].Amounts
	}
	lo := 0
	for lo < hi {
		mid := lo + (hi-lo)/2
		if h.points[mid].At < cutoff {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	if lo == 0 {
		return Amounts{}
	}
	return h.points[lo-1].Amounts
}

func (h *History) Len() int { return len(h.points) }