mint.gno
11.95 Kb · 379 lines
1// Package mint is the platform's first minter (design §2.5.3): sale
2// phases, fixed price or Dutch auction, live and merkle allowlists, lifetime
3// wallet caps, and payment settlement. It is replaceable: core binds each
4// collection to the minter that created it, so a future mint/v2 serves new
5// collections without touching sales in progress.
6//
7// Creator flow (one multi-message transaction from the frontend; safety does
8// not depend on atomicity because nobody can mint a Draft):
9//
10// Create -> AddPhase x1..3 -> Launch
11//
12// Collector flow: Mint, with Price / Phases / Eligible as the read side.
13package mint
14
15import (
16 "chain"
17 "chain/runtime"
18 "strconv"
19
20 "gno.land/p/nt/avl/v0"
21 "gno.land/p/nt/ufmt/v0"
22
23 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
24 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
25 "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/core"
26)
27
28const MaxPhases = 3
29
30// sale is this minter's per-collection state. Phases can change only while
31// core says Draft; after Launch they are frozen with the rest (I-6).
32type sale struct {
33 phases []types.Phase
34}
35
36var sales avl.Tree // cid -> *sale
37
38// Create opens a Draft collection for the calling wallet and pays the
39// protocol's create fee from the attached ugnot (excess refunded).
40// Empty payee strings default to "creator:10000". expectedCID, when set,
41// makes the transaction fail instead of creating a different id than the
42// frontend showed (OA B2).
43func Create(cur realm, name, symbol, description, engineID, params string,
44 maxSupply, royaltyBps int64, primaryPayees, royaltyPayees, expectedCID string,
45) string {
46 paid := received(cur)
47 creator := cur.Previous().Address()
48 fee := core.FeeConfig()
49 if paid < fee.CreateFee {
50 panic("create fee is " + itoa(fee.CreateFee) + "ugnot, sent " + itoa(paid))
51 }
52 self := creator.String() + ":10000"
53 if primaryPayees == "" {
54 primaryPayees = self
55 }
56 if royaltyPayees == "" {
57 royaltyPayees = self
58 }
59
60 cid := core.CreateCollection(cross(cur), creator, types.CollectionSpec{
61 Name: name, Symbol: symbol, Description: description,
62 EngineID: engineID, Params: params,
63 MaxSupply: maxSupply, RoyaltyBps: royaltyBps,
64 PrimaryPayees: primaryPayees, RoyaltyPayees: royaltyPayees,
65 })
66 if expectedCID != "" && cid != expectedCID {
67 panic("collection id would be " + cid + ", expected " + expectedCID + "; retry")
68 }
69 sales.Set(cid, &sale{})
70
71 pay(cur, fee.Treasury, fee.CreateFee)
72 pay(cur, creator, paid-fee.CreateFee)
73 return cid
74}
75
76// AddPhase appends a sale phase. Phases are ordered and do not overlap.
77// kind is "allow" (set required) or "public" (set empty); a fixed price has
78// startPrice == floorPrice and zero steps; walletCap 0 means no cap.
79func AddPhase(cur realm, cid, kind, set string,
80 startHeight, endHeight, startPrice, floorPrice, stepBlocks, stepAmount, walletCap int64,
81) {
82 assertNoDeposit(cur)
83 s := mustDraftSale(cur, cid)
84 if len(s.phases) >= MaxPhases {
85 panic("at most " + itoa(MaxPhases) + " phases")
86 }
87 p := types.Phase{
88 Kind: kind, Set: set,
89 StartHeight: startHeight, EndHeight: endHeight,
90 StartPrice: startPrice, FloorPrice: floorPrice,
91 StepBlocks: stepBlocks, StepAmount: stepAmount,
92 WalletCap: walletCap,
93 }
94 if err := p.Validate(); err != nil {
95 panic(err)
96 }
97 if set != "" {
98 parseSet(set)
99 }
100 if n := len(s.phases); n > 0 && p.StartHeight <= s.phases[n-1].EndHeight {
101 panic("phases must not overlap: start after height " + itoa(s.phases[n-1].EndHeight))
102 }
103 s.phases = append(s.phases, p)
104 chain.Emit("PhaseAdded", "cid", cid, "index", itoa(int64(len(s.phases)-1)), "kind", kind, "set", set)
105}
106
107// ClearPhases removes every phase of a Draft.
108func ClearPhases(cur realm, cid string) {
109 assertNoDeposit(cur)
110 s := mustDraftSale(cur, cid)
111 s.phases = nil
112 chain.Emit("PhasesCleared", "cid", cid)
113}
114
115// Launch freezes the sale. creatorCommit is safe.Commit(chainID, cid,
116// "creator", secret), computed off-chain — never send the secret to a node
117// before reveal. beaconSource (with useBeacon) is "" / "committed" for the
118// platform beacon or an approved randomness provider's package path
119// (core.RandomnessProviders). The engine-author fee is snapshotted here.
120func Launch(cur realm, cid, creatorCommit string, revealWindow int64, useBeacon bool, beaconSource string) {
121 assertNoDeposit(cur)
122 s := mustDraftSale(cur, cid)
123 if len(s.phases) == 0 {
124 panic("add at least one phase before launching")
125 }
126 core.Launch(cross(cur), cid, types.LaunchSpec{
127 StartHeight: s.phases[0].StartHeight,
128 EndHeight: s.phases[len(s.phases)-1].EndHeight,
129 RevealWindow: revealWindow,
130 CreatorCommit: creatorCommit,
131 UseBeacon: useBeacon,
132 BeaconSource: beaconSource,
133 })
134}
135
136// Abort returns a launched collection with no mints to Draft (core rules).
137func Abort(cur realm, cid string) {
138 assertNoDeposit(cur)
139 assertCreator(cur, cid)
140 core.AbortLaunch(cross(cur), cid)
141}
142
143// Reserve mints the creator's reserve to the creator before the sale.
144func Reserve(cur realm, cid string, count int64) string {
145 assertNoDeposit(cur)
146 creator := assertCreator(cur, cid)
147 first, last := core.ReserveTo(cross(cur), cid, creator, count)
148 return itoa(first) + "-" + itoa(last)
149}
150
151// Mint buys count tokens in the phase open at this block, at that block's
152// unit price, never above maxUnitPrice (a Dutch step cannot surprise the
153// buyer). proof is the merkle proof for merkle sets, otherwise "". Returns
154// "first-last". Every attached unit is paid out or refunded (I-3, I-4).
155func Mint(cur realm, cid string, count, maxUnitPrice int64, proof string) string {
156 paid := received(cur)
157 buyer := cur.Previous().Address()
158 h := runtime.ChainHeight()
159 p, ok := mustSale(cid).phaseAt(h)
160 if !ok {
161 panic("no sale phase is open at height " + itoa(h))
162 }
163 if count <= 0 || count > core.MaxMintPerTx {
164 panic("count must be 1.." + itoa(core.MaxMintPerTx))
165 }
166 if ok, reason := eligible(cid, p.Set, buyer, proof); !ok {
167 panic(reason)
168 }
169 if p.WalletCap > 0 && core.MintedBy(cid, buyer)+count > p.WalletCap {
170 panic("wallet cap: " + itoa(p.WalletCap) + " per wallet, already minted " + itoa(core.MintedBy(cid, buyer)))
171 }
172 price := p.PriceAt(h)
173 if price > maxUnitPrice {
174 panic("unit price at this block is " + itoa(price) + "ugnot, above maxUnitPrice " + itoa(maxUnitPrice))
175 }
176 cost := price * count
177 if paid < cost {
178 panic("send " + itoa(cost) + "ugnot, sent " + itoa(paid))
179 }
180
181 first, last := core.MintTo(cross(cur), cid, buyer, count)
182
183 fee := core.FeeConfig()
184 sp := split(cid, cost)
185 pay(cur, fee.Treasury, sp.protocol)
186 pay(cur, sp.engineAuthor, sp.engine)
187 for i, payee := range sp.payees {
188 pay(cur, payee.Addr, sp.shares[i])
189 }
190 pay(cur, buyer, paid-cost)
191
192 chain.Emit("Sale", "cid", cid, "buyer", buyer.String(), "first", itoa(first), "last", itoa(last),
193 "unitPrice", itoa(price), "protocolFee", itoa(sp.protocol), "engineFee", itoa(sp.engine),
194 "engineAuthor", sp.engineAuthor.String())
195 return itoa(first) + "-" + itoa(last)
196}
197
198// primarySplit is how a primary sale of `amount` is paid (I-4: protocol +
199// engine + sum(shares) == amount): the protocol fee frozen at Launch
200// (SA-I5), the engine author's fee (snapshot at Launch, 0 when the creator
201// is the author), the rest split over the frozen primary payees.
202type primarySplit struct {
203 protocol, engine int64
204 engineAuthor address
205 payees []types.Payee
206 shares []int64
207}
208
209func split(cid string, amount int64) primarySplit {
210 sp := primarySplit{protocol: safe.BpsOf(amount, core.PrimaryFeeBps(cid))}
211 author, bps := core.EngineFee(cid)
212 sp.engineAuthor, sp.engine = author, safe.BpsOf(amount, bps)
213 sp.payees = core.PrimaryPayees(cid)
214 sp.shares = safe.SplitByBps(amount-sp.protocol-sp.engine, sp.payees)
215 return sp
216}
217
218func (s *sale) phaseAt(h int64) (types.Phase, bool) {
219 for _, p := range s.phases {
220 if p.Covers(h) {
221 return p, true
222 }
223 }
224 return types.Phase{}, false
225}
226
227func mustSale(cid string) *sale {
228 v := sales.Get(cid)
229 if v == nil {
230 panic("collection " + cid + " was not created by this minter")
231 }
232 return v.(*sale)
233}
234
235func mustDraftSale(cur realm, cid string) *sale {
236 assertCreator(cur, cid)
237 if core.Info(cid).State != types.StateDraft {
238 panic("phases are frozen after launch")
239 }
240 return mustSale(cid)
241}
242
243func assertCreator(cur realm, cid string) address {
244 who := cur.Previous().Address()
245 if core.Info(cid).Creator != who {
246 panic("only the collection's creator can do this")
247 }
248 return who
249}
250
251// --- reads -------------------------------------------------------------------
252
253// Price is the unit price at height h, or -1 when no phase covers h.
254func Price(cid string, h int64) int64 {
255 p, ok := mustSale(cid).phaseAt(h)
256 if !ok {
257 return -1
258 }
259 return p.PriceAt(h)
260}
261
262// Phases is the phase list as JSON.
263func Phases(cid string) string {
264 w := &safe.JSONWriter{}
265 w.BeginArray()
266 for _, p := range mustSale(cid).phases {
267 w.BeginObject()
268 w.StrField("kind", p.Kind)
269 w.StrField("set", p.Set)
270 w.IntField("startHeight", p.StartHeight)
271 w.IntField("endHeight", p.EndHeight)
272 w.IntField("startPrice", p.StartPrice)
273 w.IntField("floorPrice", p.FloorPrice)
274 w.IntField("stepBlocks", p.StepBlocks)
275 w.IntField("stepAmount", p.StepAmount)
276 w.IntField("walletCap", p.WalletCap)
277 w.EndObject()
278 }
279 w.EndArray()
280 return w.String()
281}
282
283// Eligible answers "can addr mint now, and how many?" with the same checks
284// Mint runs, so the UI never disagrees with the chain (OA B3). JSON:
285// {phase, kind, eligible, reason, remainingCap (-1 = no cap), price}.
286func Eligible(cid string, addr address, proof string) string {
287 h := runtime.ChainHeight()
288 w := &safe.JSONWriter{}
289 w.BeginObject()
290 idx, p := -1, types.Phase{}
291 for i, q := range mustSale(cid).phases {
292 if q.Covers(h) {
293 idx, p = i, q
294 break
295 }
296 }
297 w.IntField("phase", int64(idx))
298 if idx < 0 {
299 w.BoolField("eligible", false)
300 w.StrField("reason", "no sale phase is open at height "+itoa(h))
301 w.EndObject()
302 return w.String()
303 }
304 ok, reason := eligible(cid, p.Set, addr, proof)
305 remaining := int64(-1)
306 if p.WalletCap > 0 {
307 minted := core.MintedBy(cid, addr) // -1 once Final: nothing left to mint anyway
308 if minted < 0 {
309 minted = p.WalletCap
310 }
311 remaining = p.WalletCap - minted
312 if remaining < 0 {
313 remaining = 0
314 }
315 if remaining == 0 && ok {
316 ok, reason = false, "wallet cap reached"
317 }
318 }
319 if ok && core.Info(cid).State != types.StateMinting {
320 ok, reason = false, "collection is not minting"
321 }
322 w.StrField("kind", p.Kind)
323 w.BoolField("eligible", ok)
324 w.StrField("reason", reason)
325 w.IntField("remainingCap", remaining)
326 w.IntField("price", p.PriceAt(h))
327 w.EndObject()
328 return w.String()
329}
330
331// Quote is what Mint(cid, count, …) pays at height h, as JSON: {count,
332// unitPrice, cost, protocolFee, protocolBps, engineFee, engineBps,
333// engineAuthor, payees:[{address, amount}]}; unitPrice -1 outside phases.
334func Quote(cid string, count, h int64) string {
335 price := Price(cid, h)
336 w := &safe.JSONWriter{}
337 w.BeginObject()
338 w.IntField("count", count)
339 w.IntField("unitPrice", price)
340 if price < 0 || count <= 0 || count > core.MaxMintPerTx {
341 w.EndObject()
342 return w.String()
343 }
344 cost := price * count
345 sp := split(cid, cost)
346 _, bps := core.EngineFee(cid)
347 w.IntField("cost", cost)
348 w.IntField("protocolFee", sp.protocol)
349 w.IntField("protocolBps", core.PrimaryFeeBps(cid))
350 w.IntField("engineFee", sp.engine)
351 w.IntField("engineBps", bps)
352 w.StrField("engineAuthor", sp.engineAuthor.String())
353 w.Key("payees")
354 w.BeginArray()
355 for i, p := range sp.payees {
356 w.BeginObject()
357 w.StrField("address", p.Addr.String())
358 w.IntField("amount", sp.shares[i])
359 w.EndObject()
360 }
361 w.EndArray()
362 w.EndObject()
363 return w.String()
364}
365
366func Render(path string) string {
367 if path == "" {
368 return "# mint/v1\n\nSale phases of the platform's collections. Use `:<cid>` for one collection.\n"
369 }
370 s := mustSale(path) // only known collection ids get this far
371 out := "# Sale of collection " + path + "\n\n"
372 for i, p := range s.phases {
373 out += ufmt.Sprintf("%d. %s phase, heights %d-%d, price %d -> %d ugnot, wallet cap %d\n",
374 i+1, p.Kind, p.StartHeight, p.EndHeight, p.StartPrice, p.FloorPrice, p.WalletCap)
375 }
376 return out
377}
378
379func itoa(n int64) string { return strconv.FormatInt(n, 10) }