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.

views.gno

7.96 Kb · 272 lines
  1package treasury
  2
  3import (
  4	"chain"
  5	"chain/banker"
  6	"chain/runtime"
  7
  8	"gno.land/p/g1aj9pzthj36aav0kff2zcmx9llapa7ng7xzcfct/shared_budget/budget/v3"
  9)
 10
 11const MaxPageSize = 20
 12
 13type PolicyView struct {
 14	Lane             string
 15	Path             string
 16	Address          address
 17	PeriodCap        int64
 18	ItemCap          int64
 19	CanBreachFloor   bool
 20	Registered       bool
 21	Used             int64
 22	PendingPeriodCap int64
 23	PendingItemCap   int64
 24	PendingCapsETA   int64
 25}
 26
 27type ProgramView struct {
 28	ID                 int64
 29	Title              string
 30	Sponsor            address
 31	PendingSponsor     address
 32	Status             string
 33	Asset              string
 34	AssetSymbol        string
 35	AssetDecimals      int
 36	ReserveFloor       int64
 37	GovDelay           int64
 38	PendingFloor       int64
 39	PendingFloorETA    int64
 40	CurrentHeight      int64
 41	StartHeight        int64
 42	IssueEndHeight     int64
 43	IssueClosedHeight  int64
 44	IssueBlocks        int64
 45	PeriodBlocks       int64
 46	MaxHoldBlocks      int64
 47	CurrentPeriod      int64
 48	ClosedHeight       int64
 49	ClosedPeriod       int64
 50	Pruned             bool
 51	ActiveReservations int64
 52	Balance            budget.Ledger
 53	Policies           []PolicyView
 54}
 55
 56type LaneUsageView struct {
 57	Lane      string
 58	Used      int64
 59	PeriodCap int64
 60}
 61
 62type ReservationView struct {
 63	ID              int64
 64	Lane            string
 65	Recipient       address
 66	Amount          int64
 67	Status          string
 68	Period          int64
 69	Deadline        int64
 70	Memo            string
 71	ExpiredAtHeight bool
 72	Paid            bool
 73}
 74
 75type ClaimView struct {
 76	Exists    bool
 77	Recipient address
 78	Amount    int64
 79	Paid      bool
 80}
 81
 82type TokenView struct {
 83	Exists   bool
 84	ID       string
 85	Name     string
 86	Symbol   string
 87	Decimals int
 88}
 89
 90func GetTokenMetadata(key string) TokenView {
 91	token := GetRegisteredToken(key)
 92	if token == nil {
 93		return TokenView{}
 94	}
 95	return TokenView{Exists: true, ID: token.ID(), Name: token.GetName(), Symbol: token.GetSymbol(), Decimals: token.GetDecimals()}
 96}
 97
 98func LatestProgramID() int64 {
 99	return latestProgramID
100}
101
102// ListPrograms returns programs in descending ID order.
103func ListPrograms(offset, limit int) []ProgramView {
104	requirePage(offset, limit)
105	height := runtime.ChainHeight()
106	page := make([]ProgramView, 0, limit)
107	programs.ReverseIterateByOffset(offset, limit, func(_ string, value any) bool {
108		page = append(page, value.(*program).view(height))
109		return false
110	})
111	return page
112}
113
114func GetProgram(programID int64) ProgramView {
115	return mustProgram(programID).view(runtime.ChainHeight())
116}
117
118// PolicyRenderRoute resolves a policy route against the lanes registered to its realm.
119// A bare program route may return several lanes for the caller to display.
120func PolicyRenderRoute(path, policyPath string) (ProgramView, []string, int64) {
121	id, lane, itemID := budget.ParsePolicyLanePath(path)
122	p := findProgram(id)
123	if p == nil {
124		return ProgramView{}, nil, 0
125	}
126	var lanes []string
127	for _, rule := range p.policies {
128		if rule.path == policyPath && rule.registered && (lane == "" || lane == rule.lane) {
129			lanes = append(lanes, rule.lane)
130		}
131	}
132	return p.view(runtime.ChainHeight()), lanes, itemID
133}
134
135func (p *program) view(height int64) ProgramView {
136	period := p.periodAt(height)
137	rules := make([]PolicyView, 0, len(p.policies))
138	for _, rule := range p.policies {
139		rules = append(rules, PolicyView{
140			Lane: rule.lane, Path: rule.path, Address: rule.addr, PeriodCap: rule.periodCap, ItemCap: rule.itemCap,
141			CanBreachFloor: rule.canBreachFloor, Registered: rule.registered, Used: rule.used(period),
142			PendingPeriodCap: rule.pendingCaps.periodCap, PendingItemCap: rule.pendingCaps.itemCap,
143			PendingCapsETA: rule.pendingCaps.eta,
144		})
145	}
146	status := p.statusAt(height)
147	symbol, decimals := p.assetDisplay()
148	issueClosedHeight := int64(0)
149	if status == IssuanceClosed || status == Closed {
150		issueClosedHeight = p.issuanceCutoff()
151	}
152	return ProgramView{
153		ID: p.id, Title: p.title, Sponsor: p.sponsor, PendingSponsor: p.pendingSponsor, Status: status,
154		Asset: p.asset, AssetSymbol: symbol, AssetDecimals: decimals, ReserveFloor: p.reserveFloor,
155		GovDelay: p.govDelay, PendingFloor: p.pendingFloor, PendingFloorETA: p.pendingFloorETA, CurrentHeight: height,
156		StartHeight: p.start, IssueEndHeight: p.issueEnd, IssueClosedHeight: issueClosedHeight, IssueBlocks: p.issueBlocks,
157		PeriodBlocks: p.periodBlocks, MaxHoldBlocks: p.maxHold, CurrentPeriod: period,
158		ClosedHeight: p.closedHeight, ClosedPeriod: p.closedPeriod, Pruned: p.pruned,
159		ActiveReservations: p.activeCount, Balance: p.ledger, Policies: rules,
160	}
161}
162
163func (p *program) assetDisplay() (string, int) {
164	if isTokenAsset(p.asset) {
165		token := tokenForAsset(p.asset)
166		return token.GetSymbol(), token.GetDecimals()
167	}
168	if p.asset == budget.Denom {
169		return p.asset, 6
170	}
171	return p.asset, 0
172}
173
174func (view ProgramView) FormatAmount(amount int64) string {
175	if view.Asset == budget.Denom {
176		return budget.FormatUGNOT(amount)
177	}
178	return budget.FormatAsset(amount, view.AssetSymbol, view.AssetDecimals)
179}
180
181// CheckSpend preflights a reservation amount against an active, registered lane.
182func CheckSpend(programID int64, lane string, amount int64) budget.SpendCheck {
183	p := mustProgram(programID)
184	rule := p.rule(lane)
185	height := runtime.ChainHeight()
186	if p.statusAt(height) != Active || !rule.registered {
187		panic("program is not accepting reservations")
188	}
189	return p.evaluate(rule, p.periodAt(height), amount)
190}
191
192func GetLanePeriodUsage(programID int64, lane string, period int64) int64 {
193	requirePeriod(period)
194	return mustProgram(programID).rule(lane).used(period)
195}
196
197func GetPeriodUsage(programID, period int64) []LaneUsageView {
198	requirePeriod(period)
199	p := mustProgram(programID)
200	usage := make([]LaneUsageView, 0, len(p.policies))
201	for _, rule := range p.policies {
202		usage = append(usage, LaneUsageView{Lane: rule.lane, Used: rule.used(period), PeriodCap: rule.periodCap})
203	}
204	return usage
205}
206
207func GetReservation(programID int64, lane string, itemID int64) ReservationView {
208	item := mustProgram(programID).rule(lane).item(itemID)
209	if item == nil {
210		panic("reservation not found")
211	}
212	return item.view(lane, runtime.ChainHeight())
213}
214
215// ListReservations returns a lane's items in ascending ID order.
216func ListReservations(programID int64, lane string, offset, limit int) []ReservationView {
217	requirePage(offset, limit)
218	rule := mustProgram(programID).rule(lane)
219	page := make([]ReservationView, 0, limit)
220	if rule.items == nil {
221		return page
222	}
223	height := runtime.ChainHeight()
224	rule.items.IterateByOffset(offset, limit, func(_ string, value any) bool {
225		page = append(page, value.(*reservation).view(lane, height))
226		return false
227	})
228	return page
229}
230
231func GetClaim(programID int64, lane string, itemID int64) ClaimView {
232	c := mustProgram(programID).findClaim(lane, itemID)
233	if c == nil {
234		return ClaimView{}
235	}
236	return ClaimView{Exists: true, Recipient: c.recipient, Amount: c.amount, Paid: c.paid}
237}
238
239// GetTreasuryBalance returns total bank cash and the portion owed to programs.
240func GetTreasuryBalance() (int64, int64) {
241	return GetTreasuryAssetBalance(budget.Denom)
242}
243
244// GetTreasuryAssetBalance returns physical custody and outstanding claims and allocations.
245func GetTreasuryAssetBalance(asset string) (int64, int64) {
246	budget.RequireAsset(asset)
247	addr := chain.PackageAddress(realmPath)
248	if isTokenAsset(asset) {
249		return tokenForAsset(asset).BalanceOf(addr), assetOutstanding(asset)
250	}
251	return banker.NewReadonlyBanker().GetCoin(addr, asset), assetOutstanding(asset)
252}
253
254func (item *reservation) view(lane string, height int64) ReservationView {
255	return ReservationView{
256		ID: item.id, Lane: lane, Recipient: item.payment.recipient, Amount: item.payment.amount,
257		Status: item.status, Period: item.period, Deadline: item.deadline, Memo: item.memo,
258		ExpiredAtHeight: item.status == Reserved && height >= item.deadline, Paid: item.payment.paid,
259	}
260}
261
262func requirePage(offset, limit int) {
263	if offset < 0 || limit < 1 || limit > MaxPageSize {
264		panic("offset must be non-negative and limit must be 1 to 20")
265	}
266}
267
268func requirePeriod(period int64) {
269	if period < 0 {
270		panic("period must be non-negative")
271	}
272}