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.

admin.gno

13.18 Kb · 430 lines
  1package core
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6	"strconv"
  7	"strings"
  8
  9	"gno.land/p/nt/avl/v0"
 10
 11	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
 12	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
 13)
 14
 15// Admin (design §2.5.2, §7.5). The admin can only change the parameters
 16// listed in validateOp, each inside a hard cap, after a public timelock;
 17// it can pause new activity for a bounded time. It can never move, approve
 18// or burn a token, touch a collection's configuration, or receive funds
 19// (I-1). With no collection yet there is nothing to protect, so ops execute
 20// without delay — that is how the platform is configured after deploy.
 21//
 22// The initial admin and treasury come from config.gno (per chain; the
 23// admin is the bootstrap deployer and is handed to the 2/3 multisig with
 24// admin.transfer before minter.add, plan §5.7).
 25// SA-I6: CreateFee starts at 0 here so tests and bootstrap stay simple;
 26// the bootstrap sets fee.create (1 GNOT, decision §6-5).
 27var (
 28	admin        = initialAdmin
 29	pendingAdmin address
 30	fees         = types.Fees{
 31		PrimaryBps: 250, SecondaryBps: 250, EngineCapBps: EngineFeeCapBps,
 32		Treasury: initialTreasury,
 33	}
 34	beacon address
 35	// listingDeposit is the deposit return market/v1 pins into each new
 36	// listing at List and charges the buyer for the seller (CV-L2): the
 37	// listing's storage (4,077 B, measured) x the chain's storage price
 38	// (100 ugnot/B on Onyx and gnoland-1). Re-set with listing.deposit
 39	// (timelocked, <= ListingDepositCap) if the vm storage_price changes.
 40	listingDeposit int64    = 407_700
 41	minters        avl.Tree // minter pkgpath -> *minterRecord
 42	ops            avl.Tree // safe.PadInt(op id) -> *pendingOp
 43	opCount        int64
 44	pauses         avl.Tree // scope -> *pauseRecord
 45
 46	// deniedPayees is every address refused as a payee or treasury beyond
 47	// core's own (SA-L5, M-17): the static platform realms (config.gno),
 48	// every minter ever approved, and payee.deny entries. It only grows
 49	// (I-18).
 50	deniedPayees avl.Tree // address -> *deniedPayee
 51	deniedOrder  avl.Tree // safe.PadInt(seq) -> address (DeniedPayees pages)
 52	deniedCount  int64
 53	deniedByOps  int64
 54)
 55
 56type deniedPayee struct {
 57	path, source string // source: "static", "minter" or "op"
 58}
 59
 60// pauseRecord is one scope's pause and its budget (SA-L2): within a window
 61// of PauseWindowBlocks a scope can be paused for at most MaxPauseBlocks in
 62// total; a pause cannot be renewed while it runs. Worst case two budgets
 63// meet at a window boundary (<= 2 x MaxPauseBlocks in a row), never more.
 64type pauseRecord struct {
 65	windowStart int64
 66	used        int64 // blocks of budget charged in this window
 67	until       int64 // exclusive
 68}
 69
 70type minterRecord struct {
 71	deprecated bool
 72}
 73
 74type pendingOp struct {
 75	id       int64
 76	op, arg  string
 77	proposed int64
 78}
 79
 80// Ops and their argument formats.
 81const (
 82	OpFeeCreate       = "fee.create"           // ugnot, <= CreateFeeCap
 83	OpFeePrimary      = "fee.primary"          // bps, <= ProtocolFeeCapBps
 84	OpFeeSecondary    = "fee.secondary"        // bps, <= ProtocolFeeCapBps
 85	OpFeeEngine       = "fee.engine"           // bps, <= EngineFeeCapBps: platform cap on engine-author fees
 86	OpTreasury        = "treasury"             // address
 87	OpBeacon          = "beacon"               // address, or "" to disable new beacon launches
 88	OpMinterAdd       = "minter.add"           // realm pkgpath
 89	OpMinterDeprecate = "minter.deprecate"     // realm pkgpath: no new collections
 90	OpEngineReview    = "engine.review"        // engine id: reviewed badge (UI only)
 91	OpAdminTransfer   = "admin.transfer"       // address; the new admin must AcceptAdmin
 92	OpRandomnessAdd   = "randomness.add"       // registered provider path: creators may launch with it
 93	OpRandomnessDepr  = "randomness.deprecate" // provider path: no new launches; running ones finish
 94	OpListingDeposit  = "listing.deposit"      // ugnot, <= ListingDepositCap: market deposit return for new listings
 95	OpEngineDeprecate = "engine.deprecate"     // engine id: no new collections (proven re-wrap or squat, ENG-M1)
 96	OpPayeeDeny       = "payee.deny"           // realm pkgpath: refused as payee/treasury from now on (I-18: no op removes)
 97)
 98
 99var pauseScopes = []string{"create", "mint", "trade"}
100
101func ProposeOp(cur realm, op, arg string) string {
102	assertNoDeposit(cur)
103	assertAdmin(cur)
104	validateOp(op, arg)
105	opCount++
106	p := &pendingOp{id: opCount, op: op, arg: arg, proposed: height()}
107	ops.Set(safe.PadInt(p.id, cidWidth), p)
108	id := itoa(p.id)
109	chain.Emit("OpProposed", "id", id, "op", op, "arg", arg, "earliest", itoa(earliestExecution(p)))
110	return id
111}
112
113// ExecuteOp applies a proposed op once its timelock has passed. The delay is
114// judged at execution, so an op proposed during bootstrap still waits the
115// full timelock if a collection appeared in the meantime.
116func ExecuteOp(cur realm, opID string) {
117	assertNoDeposit(cur)
118	assertAdmin(cur)
119	p := mustOp(opID)
120	if height() < earliestExecution(p) {
121		panic("timelocked until height " + itoa(earliestExecution(p)))
122	}
123	validateOp(p.op, p.arg)
124	applyOp(p.op, p.arg)
125	ops.Remove(safe.PadInt(p.id, cidWidth))
126	chain.Emit("OpExecuted", "id", opID, "op", p.op, "arg", p.arg)
127}
128
129func CancelOp(cur realm, opID string) {
130	assertNoDeposit(cur)
131	assertAdmin(cur)
132	p := mustOp(opID)
133	ops.Remove(safe.PadInt(p.id, cidWidth))
134	chain.Emit("OpCancelled", "id", opID)
135}
136
137func AcceptAdmin(cur realm) {
138	assertNoDeposit(cur)
139	who := caller(cur)
140	if pendingAdmin == "" || who != pendingAdmin {
141		panic("no pending admin transfer to this address")
142	}
143	chain.Emit("AdminTransferred", "from", admin.String(), "to", who.String())
144	admin = who
145	pendingAdmin = ""
146}
147
148// Pause stops new activity in one scope for the rest of its budget (at
149// most MaxPauseBlocks per PauseWindowBlocks). It never blocks exits (I-2)
150// and cannot be renewed while it runs (SA-L2).
151func Pause(cur realm, scope string) {
152	assertNoDeposit(cur)
153	assertAdmin(cur)
154	assertScope(scope)
155	h := height()
156	r := pauseOf(scope)
157	if h < r.until {
158		panic("already paused until height " + itoa(r.until) + "; a pause cannot be renewed")
159	}
160	if h >= r.windowStart+PauseWindowBlocks {
161		r.windowStart, r.used = h, 0
162	}
163	left := MaxPauseBlocks - r.used
164	if left <= 0 {
165		panic("pause budget of " + scope + " is spent until height " + itoa(r.windowStart+PauseWindowBlocks))
166	}
167	r.used += left
168	r.until = h + left
169	pauses.Set(scope, r)
170	chain.Emit("Paused", "scope", scope, "until", itoa(r.until))
171}
172
173// Unpause ends a pause early and gives the unused blocks back to the budget.
174func Unpause(cur realm, scope string) {
175	assertNoDeposit(cur)
176	assertAdmin(cur)
177	assertScope(scope)
178	h := height()
179	r := pauseOf(scope)
180	if h < r.until {
181		r.used -= r.until - h
182	}
183	r.until = 0
184	chain.Emit("Unpaused", "scope", scope)
185}
186
187func pauseOf(scope string) *pauseRecord {
188	if v := pauses.Get(scope); v != nil {
189		return v.(*pauseRecord)
190	}
191	return &pauseRecord{windowStart: -PauseWindowBlocks}
192}
193
194// Paused reports whether scope ("create", "mint", "trade") is paused now.
195func Paused(scope string) bool {
196	v := pauses.Get(scope)
197	return v != nil && height() < v.(*pauseRecord).until
198}
199
200// PauseBudget is the scope's pause record as JSON: {until, used,
201// windowStart, windowEnd, left}.
202func PauseBudget(scope string) string {
203	assertScope(scope)
204	r := pauseOf(scope)
205	used := r.used
206	if height() >= r.windowStart+PauseWindowBlocks && height() >= r.until {
207		used = 0
208	}
209	w := &safe.JSONWriter{}
210	w.BeginObject()
211	w.IntField("until", r.until)
212	w.IntField("used", used)
213	w.IntField("windowStart", r.windowStart)
214	w.IntField("windowEnd", r.windowStart+PauseWindowBlocks)
215	w.IntField("left", MaxPauseBlocks-used)
216	w.EndObject()
217	return w.String()
218}
219
220func assertNotPaused(scope string) {
221	if Paused(scope) {
222		panic("paused: " + scope)
223	}
224}
225
226func assertScope(scope string) {
227	for _, s := range pauseScopes {
228		if s == scope {
229			return
230		}
231	}
232	panic("pause scope must be one of " + strings.Join(pauseScopes, ", "))
233}
234
235func assertAdmin(cur realm) {
236	if caller(cur) != admin {
237		panic("admin only")
238	}
239}
240
241func bootstrapping() bool { return collCount == 0 }
242
243func earliestExecution(p *pendingOp) int64 {
244	if bootstrapping() {
245		return p.proposed
246	}
247	return p.proposed + TimelockBlocks
248}
249
250func mustOp(opID string) *pendingOp {
251	v := ops.Get(safe.PadInt(safe.ParseID("opID", opID), cidWidth))
252	if v == nil {
253		panic("unknown op " + opID)
254	}
255	return v.(*pendingOp)
256}
257
258// validateOp is the closed list of admin powers (I-1).
259func validateOp(op, arg string) {
260	switch op {
261	case OpFeeCreate:
262		n := parseAmount(arg)
263		if n > CreateFeeCap {
264			panic("create fee above cap " + itoa(CreateFeeCap))
265		}
266	case OpFeePrimary, OpFeeSecondary:
267		safe.AssertBps(op, parseAmount(arg), ProtocolFeeCapBps)
268	case OpFeeEngine:
269		safe.AssertBps(op, parseAmount(arg), EngineFeeCapBps)
270	case OpListingDeposit:
271		if parseAmount(arg) > ListingDepositCap {
272			panic("listing deposit above cap " + itoa(ListingDepositCap))
273		}
274	case OpTreasury, OpAdminTransfer:
275		if !address(arg).IsValid() {
276			panic(op + ": invalid address")
277		}
278		if op == OpTreasury {
279			assertSpendable(op, address(arg), "", "") // SA-L5
280		}
281	case OpBeacon:
282		if arg != "" && !address(arg).IsValid() {
283			panic(op + ": invalid address")
284		}
285	case OpMinterAdd:
286		safe.AssertText("minter", arg, 256)
287		if !strings.HasPrefix(arg, runtime.ChainDomain()+"/r/") || strings.Contains(arg, "#") {
288			panic("minter must be a realm path")
289		}
290		if minters.Has(arg) {
291			panic("minter already added")
292		}
293	case OpMinterDeprecate:
294		if !minters.Has(arg) {
295			panic("unknown minter")
296		}
297	case OpEngineReview:
298		mustEngine(arg)
299	case OpEngineDeprecate:
300		if mustEngine(arg).deprecated {
301			panic("engine is already deprecated")
302		}
303	case OpPayeeDeny:
304		safe.AssertText("payee realm", arg, 256)
305		if !strings.HasPrefix(arg, runtime.ChainDomain()+"/r/") || strings.Contains(arg, "#") {
306			panic("payee.deny takes a realm path")
307		}
308		if deniedPayees.Has(chain.PackageAddress(arg).String()) {
309			panic("realm is already denied as a payee")
310		}
311		if deniedByOps >= MaxDeniedPayees {
312			panic("payee deny list is full (" + itoa(MaxDeniedPayees) + " entries)")
313		}
314	case OpRandomnessAdd:
315		if mustProvider(arg).active {
316			panic("randomness provider already approved")
317		}
318	case OpRandomnessDepr:
319		if !mustProvider(arg).active {
320			panic("randomness provider is not approved")
321		}
322	default:
323		panic("unknown op " + strconv.Quote(op))
324	}
325}
326
327func applyOp(op, arg string) {
328	switch op {
329	case OpFeeCreate:
330		fees.CreateFee = parseAmount(arg)
331	case OpFeePrimary:
332		fees.PrimaryBps = parseAmount(arg)
333	case OpFeeSecondary:
334		fees.SecondaryBps = parseAmount(arg)
335	case OpFeeEngine:
336		fees.EngineCapBps = parseAmount(arg)
337	case OpListingDeposit:
338		listingDeposit = parseAmount(arg)
339	case OpTreasury:
340		fees.Treasury = address(arg)
341	case OpBeacon:
342		beacon = address(arg)
343	case OpMinterAdd:
344		minters.Set(arg, &minterRecord{})
345		denyPayee(arg, "minter")
346	case OpMinterDeprecate:
347		minters.Get(arg).(*minterRecord).deprecated = true
348	case OpEngineReview:
349		mustEngine(arg).reviewed = true
350	case OpEngineDeprecate:
351		rec := mustEngine(arg)
352		rec.deprecated, rec.deprecatedBy = true, "admin"
353		chain.Emit("EngineDeprecated", "id", arg, "by", "admin")
354	case OpPayeeDeny:
355		denyPayee(arg, "op")
356		deniedByOps++
357		chain.Emit("PayeeDenied", "path", arg, "address", chain.PackageAddress(arg).String())
358	case OpAdminTransfer:
359		pendingAdmin = address(arg)
360	case OpRandomnessAdd:
361		mustProvider(arg).active = true
362		activeProviders++
363	case OpRandomnessDepr:
364		mustProvider(arg).active = false
365		activeProviders--
366	}
367}
368
369func assertActiveMinter(path string) {
370	v := minters.Get(path)
371	if v == nil {
372		panic("caller " + strconv.Quote(path) + " is not an approved minter")
373	}
374	if v.(*minterRecord).deprecated {
375		panic("minter " + path + " is deprecated")
376	}
377}
378
379func parseAmount(s string) int64 {
380	n, err := strconv.ParseInt(s, 10, 64)
381	if err != nil || n < 0 {
382		panic("expected a non-negative integer, got " + strconv.Quote(s))
383	}
384	return n
385}
386
387// --- payee deny set (SA-L5, M-17, I-18) -----------------------------------------
388
389// initDeniedPayees adds the static platform realms next to core.
390func initDeniedPayees() {
391	base := strings.TrimSuffix(selfPath, "/core")
392	for _, sib := range staticDeniedRealms {
393		denyPayee(base+"/"+sib, "static")
394	}
395}
396
397// denyPayee adds path's package address to the deny set (idempotent).
398func denyPayee(path, source string) {
399	key := chain.PackageAddress(path).String()
400	if deniedPayees.Has(key) {
401		return
402	}
403	deniedPayees.Set(key, &deniedPayee{path: path, source: source})
404	deniedCount++
405	deniedOrder.Set(safe.PadInt(deniedCount, cidWidth), key)
406}
407
408// IsDeniedPayee reports whether addr is in the payee deny set (static
409// platform realms, approved minters, payee.deny). Core's own addresses and
410// a collection's sub-addresses and engine adapter are refused as well
411// (assertSpendable) but are not listed here.
412func IsDeniedPayee(addr address) bool { return deniedPayees.Has(addr.String()) }
413
414// DeniedPayees pages the deny set as JSON: [{path, address, source}].
415func DeniedPayees(offset, limit int64) string {
416	w := &safe.JSONWriter{}
417	w.BeginArray()
418	deniedOrder.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
419		key := v.(string)
420		d := deniedPayees.Get(key).(*deniedPayee)
421		w.BeginObject()
422		w.StrField("path", d.path)
423		w.StrField("address", key)
424		w.StrField("source", d.source)
425		w.EndObject()
426		return false
427	})
428	w.EndArray()
429	return w.String()
430}