Playground
allowlist.gno
package mint
import (
"strings"
"gno.land/r/sys/users"
validators "gno.land/r/sys/validators/v2"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia2/core"
)
// Allowlist sets (design §4.6). A phase's set is a comma-separated
// union of terms; an address is eligible if any term admits it:
//
// users registered in r/sys/users (live check)
// validators in the active validator set (live check)
// holders:<cid> holds a token of collection <cid>
// merkle:<root> in a sha256 merkle tree; the minter passes the proof
//
// A term may carry "|"-separated provenance notes for humans, e.g.
// "merkle:<root>|src:<git-sha>|data:<sha256>"; notes never affect logic.
const (
MaxSetLen = 512
MaxSetTerms = 4
)
type setTerm struct {
name, arg string
}
// parseSet validates a set and returns its terms; it panics on any error so
// AddPhase rejects a malformed set before it is ever frozen.
func parseSet(set string) []setTerm {
safe.AssertText("set", set, MaxSetLen)
parts := strings.Split(set, ",")
if len(parts) > MaxSetTerms {
panic("set: at most 4 terms")
}
terms := make([]setTerm, 0, len(parts))
for _, part := range parts {
body, _, _ := strings.Cut(part, "|")
name, arg, _ := strings.Cut(body, ":")
switch name {
case "users", "validators":
if arg != "" {
panic("set: " + name + " takes no argument")
}
case "holders":
core.Info(arg) // panics for an unknown collection
case "merkle":
arg = safe.AssertHex("set merkle root", arg, 32)
default:
panic("set: unknown term " + name)
}
terms = append(terms, setTerm{name: name, arg: arg})
}
return terms
}
// eligible reports whether addr may mint in a phase with this set, and why
// not. Live sets are evaluated at mint time, so a deleted user or a removed
// validator loses eligibility immediately.
func eligible(cid, set string, addr address, proof string) (bool, string) {
if set == "" {
return true, ""
}
for _, t := range parseSet(set) {
switch t.name {
case "users":
if users.ResolveAddress(addr) != nil {
return true, ""
}
case "validators":
if validators.IsValidator(addr) {
return true, ""
}
case "holders":
if n, err := core.BalanceOf(t.arg, addr); err == nil && n > 0 {
return true, ""
}
case "merkle":
// an empty proof is valid for a one-address tree (root == leaf, SA-L4)
if safe.MerkleVerify(t.arg, safe.AllowlistLeaf(cid, addr), proof) {
return true, ""
}
}
}
return false, "address is not in this phase's allowlist (" + set + ")"
}
gnomod.toml
module = "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia2/mint/v1" gno = "0.9" [addpkg] creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06" height = 829921 max_deposit = "100000000ugnot"
mint.gno
// Package mint is the platform's first minter (design §2.5.3): sale
// phases, fixed price or Dutch auction, live and merkle allowlists, lifetime
// wallet caps, and payment settlement. It is replaceable: core binds each
// collection to the minter that created it, so a future mint/v2 serves new
// collections without touching sales in progress.
//
// Creator flow (one multi-message transaction from the frontend; safety does
// not depend on atomicity because nobody can mint a Draft):
//
// Create -> AddPhase x1..3 -> Launch
//
// Collector flow: Mint, with Price / Phases / Eligible as the read side.
package mint
import (
"chain"
"chain/runtime"
"strconv"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia2/core"
)
const MaxPhases = 3
// sale is this minter's per-collection state. Phases can change only while
// core says Draft; after Launch they are frozen with the rest (I-6).
type sale struct {
phases []types.Phase
}
var sales avl.Tree // cid -> *sale
// Create opens a Draft collection for the calling wallet and pays the
// protocol's create fee from the attached ugnot (excess refunded).
// Empty payee strings default to "creator:10000". expectedCID, when set,
// makes the transaction fail instead of creating a different id than the
// frontend showed (OA B2).
func Create(cur realm, name, symbol, description, engineID, params string,
maxSupply, royaltyBps int64, primaryPayees, royaltyPayees, expectedCID string,
) string {
paid := received(cur)
creator := cur.Previous().Address()
fee := core.FeeConfig()
if paid < fee.CreateFee {
panic("create fee is " + itoa(fee.CreateFee) + "ugnot, sent " + itoa(paid))
}
self := creator.String() + ":10000"
if primaryPayees == "" {
primaryPayees = self
}
if royaltyPayees == "" {
royaltyPayees = self
}
cid := core.CreateCollection(cross(cur), creator, types.CollectionSpec{
Name: name, Symbol: symbol, Description: description,
EngineID: engineID, Params: params,
MaxSupply: maxSupply, RoyaltyBps: royaltyBps,
PrimaryPayees: primaryPayees, RoyaltyPayees: royaltyPayees,
})
if expectedCID != "" && cid != expectedCID {
panic("collection id would be " + cid + ", expected " + expectedCID + "; retry")
}
sales.Set(cid, &sale{})
pay(cur, fee.Treasury, fee.CreateFee)
pay(cur, creator, paid-fee.CreateFee)
return cid
}
// AddPhase appends a sale phase. Phases are ordered and do not overlap.
// kind is "allow" (set required) or "public" (set empty); a fixed price has
// startPrice == floorPrice and zero steps; walletCap 0 means no cap.
func AddPhase(cur realm, cid, kind, set string,
startHeight, endHeight, startPrice, floorPrice, stepBlocks, stepAmount, walletCap int64,
) {
assertNoDeposit(cur)
s := mustDraftSale(cur, cid)
if len(s.phases) >= MaxPhases {
panic("at most " + itoa(MaxPhases) + " phases")
}
p := types.Phase{
Kind: kind, Set: set,
StartHeight: startHeight, EndHeight: endHeight,
StartPrice: startPrice, FloorPrice: floorPrice,
StepBlocks: stepBlocks, StepAmount: stepAmount,
WalletCap: walletCap,
}
if err := p.Validate(); err != nil {
panic(err)
}
if set != "" {
parseSet(set)
}
if n := len(s.phases); n > 0 && p.StartHeight <= s.phases[n-1].EndHeight {
panic("phases must not overlap: start after height " + itoa(s.phases[n-1].EndHeight))
}
s.phases = append(s.phases, p)
chain.Emit("PhaseAdded", "cid", cid, "index", itoa(int64(len(s.phases)-1)), "kind", kind, "set", set)
}
// ClearPhases removes every phase of a Draft.
func ClearPhases(cur realm, cid string) {
assertNoDeposit(cur)
s := mustDraftSale(cur, cid)
s.phases = nil
chain.Emit("PhasesCleared", "cid", cid)
}
// Launch freezes the sale. creatorCommit is safe.Commit(chainID, cid,
// "creator", secret), computed off-chain — never send the secret to a node
// before reveal. beaconSource (with useBeacon) is "" / "committed" for the
// platform beacon or an approved randomness provider's package path
// (core.RandomnessProviders). The engine-author fee is snapshotted here.
func Launch(cur realm, cid, creatorCommit string, revealWindow int64, useBeacon bool, beaconSource string) {
assertNoDeposit(cur)
s := mustDraftSale(cur, cid)
if len(s.phases) == 0 {
panic("add at least one phase before launching")
}
core.Launch(cross(cur), cid, types.LaunchSpec{
StartHeight: s.phases[0].StartHeight,
EndHeight: s.phases[len(s.phases)-1].EndHeight,
RevealWindow: revealWindow,
CreatorCommit: creatorCommit,
UseBeacon: useBeacon,
BeaconSource: beaconSource,
})
}
// Abort returns a launched collection with no mints to Draft (core rules).
func Abort(cur realm, cid string) {
assertNoDeposit(cur)
assertCreator(cur, cid)
core.AbortLaunch(cross(cur), cid)
}
// Reserve mints the creator's reserve to the creator before the sale.
func Reserve(cur realm, cid string, count int64) string {
assertNoDeposit(cur)
creator := assertCreator(cur, cid)
first, last := core.ReserveTo(cross(cur), cid, creator, count)
return itoa(first) + "-" + itoa(last)
}
// Mint buys count tokens in the phase open at this block, at that block's
// unit price, never above maxUnitPrice (a Dutch step cannot surprise the
// buyer). proof is the merkle proof for merkle sets, otherwise "". Returns
// "first-last". Every attached unit is paid out or refunded (I-3, I-4).
func Mint(cur realm, cid string, count, maxUnitPrice int64, proof string) string {
paid := received(cur)
buyer := cur.Previous().Address()
h := runtime.ChainHeight()
p, ok := mustSale(cid).phaseAt(h)
if !ok {
panic("no sale phase is open at height " + itoa(h))
}
if count <= 0 || count > core.MaxMintPerTx {
panic("count must be 1.." + itoa(core.MaxMintPerTx))
}
if ok, reason := eligible(cid, p.Set, buyer, proof); !ok {
panic(reason)
}
if p.WalletCap > 0 && core.MintedBy(cid, buyer)+count > p.WalletCap {
panic("wallet cap: " + itoa(p.WalletCap) + " per wallet, already minted " + itoa(core.MintedBy(cid, buyer)))
}
price := p.PriceAt(h)
if price > maxUnitPrice {
panic("unit price at this block is " + itoa(price) + "ugnot, above maxUnitPrice " + itoa(maxUnitPrice))
}
cost := price * count
if paid < cost {
panic("send " + itoa(cost) + "ugnot, sent " + itoa(paid))
}
first, last := core.MintTo(cross(cur), cid, buyer, count)
fee := core.FeeConfig()
sp := split(cid, cost)
pay(cur, fee.Treasury, sp.protocol)
pay(cur, sp.engineAuthor, sp.engine)
for i, payee := range sp.payees {
pay(cur, payee.Addr, sp.shares[i])
}
pay(cur, buyer, paid-cost)
chain.Emit("Sale", "cid", cid, "buyer", buyer.String(), "first", itoa(first), "last", itoa(last),
"unitPrice", itoa(price), "protocolFee", itoa(sp.protocol), "engineFee", itoa(sp.engine),
"engineAuthor", sp.engineAuthor.String())
return itoa(first) + "-" + itoa(last)
}
// primarySplit is how a primary sale of `amount` is paid (I-4: protocol +
// engine + sum(shares) == amount): the protocol fee frozen at Launch
// (SA-I5), the engine author's fee (snapshot at Launch, 0 when the creator
// is the author), the rest split over the frozen primary payees.
type primarySplit struct {
protocol, engine int64
engineAuthor address
payees []types.Payee
shares []int64
}
func split(cid string, amount int64) primarySplit {
sp := primarySplit{protocol: safe.BpsOf(amount, core.PrimaryFeeBps(cid))}
author, bps := core.EngineFee(cid)
sp.engineAuthor, sp.engine = author, safe.BpsOf(amount, bps)
sp.payees = core.PrimaryPayees(cid)
sp.shares = safe.SplitByBps(amount-sp.protocol-sp.engine, sp.payees)
return sp
}
func (s *sale) phaseAt(h int64) (types.Phase, bool) {
for _, p := range s.phases {
if p.Covers(h) {
return p, true
}
}
return types.Phase{}, false
}
func mustSale(cid string) *sale {
v := sales.Get(cid)
if v == nil {
panic("collection " + cid + " was not created by this minter")
}
return v.(*sale)
}
func mustDraftSale(cur realm, cid string) *sale {
assertCreator(cur, cid)
if core.Info(cid).State != types.StateDraft {
panic("phases are frozen after launch")
}
return mustSale(cid)
}
func assertCreator(cur realm, cid string) address {
who := cur.Previous().Address()
if core.Info(cid).Creator != who {
panic("only the collection's creator can do this")
}
return who
}
// --- reads -------------------------------------------------------------------
// Price is the unit price at height h, or -1 when no phase covers h.
func Price(cid string, h int64) int64 {
p, ok := mustSale(cid).phaseAt(h)
if !ok {
return -1
}
return p.PriceAt(h)
}
// Phases is the phase list as JSON.
func Phases(cid string) string {
w := &safe.JSONWriter{}
w.BeginArray()
for _, p := range mustSale(cid).phases {
w.BeginObject()
w.StrField("kind", p.Kind)
w.StrField("set", p.Set)
w.IntField("startHeight", p.StartHeight)
w.IntField("endHeight", p.EndHeight)
w.IntField("startPrice", p.StartPrice)
w.IntField("floorPrice", p.FloorPrice)
w.IntField("stepBlocks", p.StepBlocks)
w.IntField("stepAmount", p.StepAmount)
w.IntField("walletCap", p.WalletCap)
w.EndObject()
}
w.EndArray()
return w.String()
}
// Eligible answers "can addr mint now, and how many?" with the same checks
// Mint runs, so the UI never disagrees with the chain (OA B3). JSON:
// {phase, kind, eligible, reason, remainingCap (-1 = no cap), price}.
func Eligible(cid string, addr address, proof string) string {
h := runtime.ChainHeight()
w := &safe.JSONWriter{}
w.BeginObject()
idx, p := -1, types.Phase{}
for i, q := range mustSale(cid).phases {
if q.Covers(h) {
idx, p = i, q
break
}
}
w.IntField("phase", int64(idx))
if idx < 0 {
w.BoolField("eligible", false)
w.StrField("reason", "no sale phase is open at height "+itoa(h))
w.EndObject()
return w.String()
}
ok, reason := eligible(cid, p.Set, addr, proof)
remaining := int64(-1)
if p.WalletCap > 0 {
minted := core.MintedBy(cid, addr) // -1 once Final: nothing left to mint anyway
if minted < 0 {
minted = p.WalletCap
}
remaining = p.WalletCap - minted
if remaining < 0 {
remaining = 0
}
if remaining == 0 && ok {
ok, reason = false, "wallet cap reached"
}
}
if ok && core.Info(cid).State != types.StateMinting {
ok, reason = false, "collection is not minting"
}
w.StrField("kind", p.Kind)
w.BoolField("eligible", ok)
w.StrField("reason", reason)
w.IntField("remainingCap", remaining)
w.IntField("price", p.PriceAt(h))
w.EndObject()
return w.String()
}
// Quote is what Mint(cid, count, …) pays at height h, as JSON: {count,
// unitPrice, cost, protocolFee, protocolBps, engineFee, engineBps,
// engineAuthor, payees:[{address, amount}]}; unitPrice -1 outside phases.
func Quote(cid string, count, h int64) string {
price := Price(cid, h)
w := &safe.JSONWriter{}
w.BeginObject()
w.IntField("count", count)
w.IntField("unitPrice", price)
if price < 0 || count <= 0 || count > core.MaxMintPerTx {
w.EndObject()
return w.String()
}
cost := price * count
sp := split(cid, cost)
_, bps := core.EngineFee(cid)
w.IntField("cost", cost)
w.IntField("protocolFee", sp.protocol)
w.IntField("protocolBps", core.PrimaryFeeBps(cid))
w.IntField("engineFee", sp.engine)
w.IntField("engineBps", bps)
w.StrField("engineAuthor", sp.engineAuthor.String())
w.Key("payees")
w.BeginArray()
for i, p := range sp.payees {
w.BeginObject()
w.StrField("address", p.Addr.String())
w.IntField("amount", sp.shares[i])
w.EndObject()
}
w.EndArray()
w.EndObject()
return w.String()
}
func Render(path string) string {
if path == "" {
return "# mint/v1\n\nSale phases of the platform's collections. Use `:<cid>` for one collection.\n"
}
s := mustSale(path) // only known collection ids get this far
out := "# Sale of collection " + path + "\n\n"
for i, p := range s.phases {
out += ufmt.Sprintf("%d. %s phase, heights %d-%d, price %d -> %d ugnot, wallet cap %d\n",
i+1, p.Kind, p.StartHeight, p.EndHeight, p.StartPrice, p.FloorPrice, p.WalletCap)
}
return out
}
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
payments.gno
package mint
import (
"chain"
"chain/banker"
"chain/runtime/unsafe"
)
// I-3: this realm holds no balance. Each paying function receives the
// attached ugnot and pushes every unit out before returning: protocol fee,
// creator payees, and the refund. Nothing is ever kept for later.
// received returns the ugnot attached to a direct wallet call. Payments are
// accepted only when a wallet called us: the origin-send envelope is shared
// by every realm on the path, so a realm in between could have consumed it
// (chain/runtime/unsafe.OriginSend).
func received(cur realm) int64 {
if !cur.Previous().IsUserCall() {
panic("payments must come directly from a wallet, not through another realm")
}
sent := unsafe.OriginSend()
for _, c := range sent {
if c.Denom != "ugnot" && c.Amount != 0 {
panic("only ugnot is accepted")
}
}
return sent.AmountOf("ugnot")
}
// assertNoDeposit refuses coins on functions that take none (RA L-1).
func assertNoDeposit(cur realm) {
if cur.Previous().IsUserCall() && !unsafe.OriginSend().IsZero() {
panic("this function does not accept coins")
}
}
func pay(cur realm, to address, amount int64) {
if amount <= 0 {
return
}
if to == cur.Address() {
panic("refusing to pay the minter itself: the coins would be stranded (SA-L5)")
}
banker.NewBanker(banker.BankerTypeRealmSend, cur).
SendCoins(cur.Address(), to, chain.NewCoins(chain.NewCoin("ugnot", amount)))
}