Playground
assert.gno
package keeper
import (
"gno.land/p/gnoswap/order/access/manager/v0"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
)
// AssertIsAuthorizedCaller panics unless the caller of rlm may call selector
// on the realm of rlm. Order realms call it with their own realm value,
// so a realm can only assert for itself.
func AssertIsAuthorizedCaller(_ int, rlm realm, selector manager.Selector) {
if !rlm.IsCurrent() {
panic(errSpoofedRealm)
}
caller := rlm.Previous().Address()
target := rlm.PkgPath()
if !accessState.IsAuthorized(caller, target, selector) {
panic(makeErrorWithDetails(
errUnauthorizedCall,
ufmt.Sprintf("%s cannot call %s on %s", caller.String(), string(selector), target),
).Error())
}
}
// assertIsAdminOrGovernance checks that the caller of cur is the GnoSwap
// admin or governance.
func assertIsAdminOrGovernance(cur realm) {
access.AssertIsAdminOrGovernance(cur.Previous().Address())
}
// assertIsRegisteredRole rejects roles that were never registered.
// manager.AdminRole is never registered here.
func assertIsRegisteredRole(role manager.RoleId) {
if !isRegisteredRole(role) {
panic(makeErrorWithDetails(errInvalidRole, ufmt.Sprintf("role(%s) is not registered", role.String())).Error())
}
}
// assertIsAssignableRole accepts a registered role or PublicRole.
func assertIsAssignableRole(role manager.RoleId) {
if role != manager.PublicRole {
assertIsRegisteredRole(role)
}
}
func assertIsAvailableLabel(label string) {
if label == "" || len(label) > maxLabelLength {
panic(makeErrorWithDetails(errInvalidLabel, ufmt.Sprintf("label(%s) must be 1 to %d bytes", label, maxLabelLength)).Error())
}
if isLabelTaken(label) {
panic(makeErrorWithDetails(errInvalidLabel, ufmt.Sprintf("label(%s) already exists", label)).Error())
}
}
func assertIsValidAddress(account address) {
if !account.IsValid() {
panic(makeErrorWithDetails(errInvalidAddress, ufmt.Sprintf("account(%s)", account.String())).Error())
}
}
func assertIsValidTarget(target string) {
if target == "" {
panic(makeErrorWithDetails(errInvalidTarget, "empty target").Error())
}
}
consts.gno
package keeper import ( "gno.land/p/gnoswap/order/access/manager/v0" ) // Roles registered at deployment. const ( DCAKeeperRole manager.RoleId = 1 LimitKeeperRole manager.RoleId = 2 PoolManagerRole manager.RoleId = 3 ) // Role labels registered at deployment. const ( DCAKeeperLabel = "DCA_ORDER_KEEPER" LimitKeeperLabel = "LIMIT_ORDER_KEEPER" PoolManagerLabel = "POOL_MANAGER" ) // Order realm targets and keeper selectors. const ( DCATarget = "gno.land/r/gnoswap/order/dca" SelectorExecuteGroup manager.Selector = "ExecuteGroup" SelectorAddWhitelistedPool manager.Selector = "AddWhitelistedPool" SelectorRemoveWhitelistedPool manager.Selector = "RemoveWhitelistedPool" SelectorForceCancelOrder manager.Selector = "ForceCancelOrder" SelectorSetTokenMinAmountPerExecution manager.Selector = "SetTokenMinAmountPerExecution" SelectorSetPairPriceLimit manager.Selector = "SetPairPriceLimit" LimitTarget = "gno.land/r/gnoswap/order/limit" SelectorExecuteOrder manager.Selector = "ExecuteOrder" WhitelistTarget = "gno.land/r/gnoswap/order/whitelist" ) // maxLabelLength bounds a role label. const maxLabelLength = 64
doc.gno
// Package keeper is the role-based access realm of the GnoSwap order realms. // // It owns a manager.State (gno.land/p/gnoswap/order/access/manager/v0). // Roles are granted to keeper accounts, and each order realm function // (target package path and selector) is assigned the role allowed to call // it, or PublicRole for anyone. // // Administration is not a manager role: every management call is checked // against the GnoSwap admin or governance (gno.land/r/gnoswap/access). // manager.AdminRole is never granted here. // // Roles registered at deployment: // - DCAKeeperRole (1): DCA order keepers // - LimitKeeperRole (2): limit order keepers // - PoolManagerRole (3): DCA/Limit pool whitelist and DCA pool policy managers // // DCA ExecuteGroup and ForceCancelOrder are assigned to DCAKeeperRole at // deployment, so only granted keepers run DCA rounds and force-cancel orders that // block them. The whitelist realm's AddWhitelistedPool and RemoveWhitelistedPool, // and DCA's SetTokenMinAmountPerExecution and SetPairPriceLimit are assigned to // PoolManagerRole, so only granted managers pick the pools and the price // limits rounds trade with (admin and governance may call them too). // This role intentionally manages both targets' whitelists and DCA's token // minimums and pair price limits; target-specific manager roles are not required. // It does not grant ExecuteGroup, ForceCancelOrder, or ExecuteOrder. // Keeping the two roles on separate accounts means a single leaked key // cannot both choose a round's pool or price and run it. // // Admin or governance adds custom roles with AddRole. // // Order realms check authorization with IsAuthorized(target, selector, // caller), passing their own package path, or with the non-crossing // AssertIsAuthorizedCaller(0, cur, selector), which derives the target from cur. package keeper
emits.gno
package keeper
import (
"chain"
"strconv"
"gno.land/p/gnoswap/order/access/manager/v0"
)
func emitRoleLabel(role manager.RoleId, label string) {
chain.Emit(
manager.EventTypeRoleLabel,
manager.AttributeKeyRoleID, role.String(),
manager.AttributeKeyLabel, label,
)
}
func emitRoleGranted(role manager.RoleId, account address, since manager.TimePoint, newMember bool) {
chain.Emit(
manager.EventTypeRoleGranted,
manager.AttributeKeyRoleID, role.String(),
manager.AttributeKeyAccount, account.String(),
manager.AttributeKeySince, since.String(),
manager.AttributeKeyNewMember, strconv.FormatBool(newMember),
)
}
func emitRoleRevoked(role manager.RoleId, account address) {
chain.Emit(
manager.EventTypeRoleRevoked,
manager.AttributeKeyRoleID, role.String(),
manager.AttributeKeyAccount, account.String(),
)
}
func emitRoleGrantDelayChanged(role manager.RoleId, delay uint32, since manager.TimePoint) {
chain.Emit(
manager.EventTypeRoleGrantDelayChanged,
manager.AttributeKeyRoleID, role.String(),
manager.AttributeKeyDelay, strconv.FormatUint(uint64(delay), 10),
manager.AttributeKeySince, since.String(),
)
}
func emitTargetClosed(target string, closed bool) {
chain.Emit(
manager.EventTypeTargetClosed,
manager.AttributeKeyTarget, target,
manager.AttributeKeyClosed, strconv.FormatBool(closed),
)
}
func emitTargetFunctionRoleUpdated(target string, selector manager.Selector, role manager.RoleId) {
chain.Emit(
manager.EventTypeTargetFunctionRoleUpdated,
manager.AttributeKeyTarget, target,
manager.AttributeKeySelector, string(selector),
manager.AttributeKeyRoleID, role.String(),
)
}
errors.gno
package keeper
import (
ufmt "gno.land/p/nt/ufmt/v0"
)
const (
errUnauthorizedCall = "[GNOSWAP-ORDER-KEEPER-001] unauthorized call"
errInvalidRole = "[GNOSWAP-ORDER-KEEPER-002] invalid role"
errInvalidLabel = "[GNOSWAP-ORDER-KEEPER-003] invalid role label"
errInvalidAddress = "[GNOSWAP-ORDER-KEEPER-004] invalid address"
errSpoofedRealm = "[GNOSWAP-ORDER-KEEPER-005] rlm does not match the current crossing frame"
errInvalidTarget = "[GNOSWAP-ORDER-KEEPER-006] invalid target"
)
func makeErrorWithDetails(message string, details string) error {
return ufmt.Errorf("%s || %s", message, details)
}
getters.gno
package keeper
import (
"sort"
"gno.land/p/gnoswap/order/access/manager/v0"
"gno.land/p/onbloc/json/v0"
)
// IsAuthorized reports whether caller may call selector on target now.
func IsAuthorized(target string, selector manager.Selector, caller address) bool {
return accessState.IsAuthorized(caller, target, selector)
}
// HasRole reports whether account is an active member of role.
func HasRole(role manager.RoleId, account address) bool {
return accessState.HasRole(role, account).IsMember
}
// GetRoleMemberSince returns when account's membership of role becomes
// active, or 0 if account is not a member.
func GetRoleMemberSince(role manager.RoleId, account address) int64 {
return accessState.GetRoleMemberSince(role, account).Int64()
}
// GetRoleGrantDelay returns the grant delay of role in effect now, in seconds.
func GetRoleGrantDelay(role manager.RoleId) uint32 {
return accessState.GetRoleGrantDelay(role)
}
// GetRoleLabel returns the label of a registered role, or "".
func GetRoleLabel(role manager.RoleId) string {
return roleLabels[role]
}
// GetRolesJSON returns the registered roles as a JSON array of
// {"id", "label"} objects, ordered by id.
func GetRolesJSON() string {
ids := make([]int, 0, len(roleLabels))
for role := range roleLabels {
ids = append(ids, int(role))
}
sort.Ints(ids)
nodes := make([]*json.Node, 0, len(ids))
for _, id := range ids {
role := manager.RoleId(id)
nodes = append(nodes, json.ObjectNode("", map[string]*json.Node{
"id": json.StringNode("", role.String()),
"label": json.StringNode("", roleLabels[role]),
}))
}
encoded, err := json.Marshal(json.ArrayNode("", nodes))
if err != nil {
panic(err.Error())
}
return string(encoded)
}
// GetTargetFunctionRole returns the role assigned to selector on target.
// Unassigned selectors return manager.AdminRole, which no account holds.
func GetTargetFunctionRole(target string, selector manager.Selector) manager.RoleId {
return accessState.GetTargetFunctionRole(target, selector)
}
// IsTargetClosed reports whether target rejects every call.
func IsTargetClosed(target string) bool {
return accessState.IsTargetClosed(target)
}
gnomod.toml
module = "gno.land/r/gnoswap/order/keeper" gno = "0.9" [addpkg] creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04" height = 1108543 max_deposit = "100000000ugnot"
keeper.gno
package keeper
import (
"gno.land/p/gnoswap/order/access/manager/v0"
)
// AddRole registers a custom role with label and returns its id.
// Admin or governance only.
func AddRole(cur realm, label string) manager.RoleId {
assertIsAdminOrGovernance(cur)
assertIsAvailableLabel(label)
role := nextCustomRoleId()
registerRole(role, label)
return role
}
// SetRoleLabel renames a registered role. Admin or governance only.
func SetRoleLabel(cur realm, role manager.RoleId, label string) {
assertIsAdminOrGovernance(cur)
assertIsRegisteredRole(role)
assertIsAvailableLabel(label)
roleLabels[role] = label
emitRoleLabel(role, label)
}
// GrantRole grants role to account and reports whether account is a new
// member. Membership starts after the role's grant delay.
// Admin or governance only.
func GrantRole(cur realm, role manager.RoleId, account address) bool {
assertIsAdminOrGovernance(cur)
assertIsRegisteredRole(role)
assertIsValidAddress(account)
newMember := accessState.GrantRole(role, account)
emitRoleGranted(role, account, accessState.GetRoleMemberSince(role, account), newMember)
return newMember
}
// RevokeRole revokes role from account and reports whether it was a member.
// Admin or governance only.
func RevokeRole(cur realm, role manager.RoleId, account address) bool {
assertIsAdminOrGovernance(cur)
assertIsRegisteredRole(role)
revoked := accessState.RevokeRole(role, account)
if revoked {
emitRoleRevoked(role, account)
}
return revoked
}
// RenounceRole revokes role from the caller.
// callerConfirmation must be the caller's address.
func RenounceRole(cur realm, role manager.RoleId, callerConfirmation address) bool {
assertIsRegisteredRole(role)
account := cur.Previous().Address()
revoked := accessState.RenounceRole(role, account, callerConfirmation)
if revoked {
emitRoleRevoked(role, account)
}
return revoked
}
// SetRoleGrantDelay schedules the delay, in seconds, before new members of role
// become active. The change itself waits manager.MinSetback.
// Admin or governance only.
func SetRoleGrantDelay(cur realm, role manager.RoleId, delay uint32) {
assertIsAdminOrGovernance(cur)
assertIsRegisteredRole(role)
accessState.SetGrantDelay(role, delay)
emitRoleGrantDelayChanged(role, delay, accessState.GetRoleGrantDelayEffect(role))
}
// SetTargetFunctionRole assigns role, or manager.PublicRole for anyone, to
// selector on target (a realm package path). Admin or governance only.
func SetTargetFunctionRole(cur realm, target string, selector manager.Selector, role manager.RoleId) {
assertIsAdminOrGovernance(cur)
assertIsValidTarget(target)
assertIsAssignableRole(role)
accessState.SetTargetFunctionRole(target, selector, role)
emitTargetFunctionRoleUpdated(target, selector, role)
}
// SetTargetFunctionRoles assigns role to several selectors on target.
// Admin or governance only.
func SetTargetFunctionRoles(cur realm, target string, selectors []manager.Selector, role manager.RoleId) {
assertIsAdminOrGovernance(cur)
assertIsValidTarget(target)
assertIsAssignableRole(role)
accessState.SetTargetFunctionRoles(target, selectors, role)
for _, selector := range selectors {
emitTargetFunctionRoleUpdated(target, selector, role)
}
}
// SetTargetClosed closes or reopens target. A closed target rejects every
// call, whatever its selector roles. Admin or governance only.
func SetTargetClosed(cur realm, target string, closed bool) {
assertIsAdminOrGovernance(cur)
assertIsValidTarget(target)
accessState.SetTargetClosed(target, closed)
emitTargetClosed(target, closed)
}
state.gno
package keeper
import (
"gno.land/p/gnoswap/order/access/manager/v0"
)
var (
accessState manager.State
// roleLabels holds every registered role and its label.
roleLabels map[manager.RoleId]string
)
func init() {
resetState()
}
// resetState registers the deployment roles and wires the order realm
// selectors. DCA rounds are restricted to DCAKeeperRole from deployment:
// a public round could be sandwiched in one transaction, since the
// executor sets the swap's minimum output. Admin or governance grants the
// role to keepers, or reassigns ExecuteGroup. DCA keepers also force-cancel
// orders that block their group's rounds.
//
// PoolManagerRole manages both DCA and Limit pool whitelists and DCA's per-token
// minimum order sizes and pair price limits. It is kept apart from the keeper
// role so that neither key alone can both pick the pool and price a round:
// a keeper cannot swap below the manager's price limit,
// and a manager cannot run rounds. Limit fills require LimitKeeperRole.
func resetState() {
accessState = manager.NewState()
roleLabels = make(map[manager.RoleId]string)
registerRole(DCAKeeperRole, DCAKeeperLabel)
registerRole(LimitKeeperRole, LimitKeeperLabel)
registerRole(PoolManagerRole, PoolManagerLabel)
for _, selector := range []manager.Selector{SelectorExecuteGroup, SelectorForceCancelOrder} {
accessState.SetTargetFunctionRole(DCATarget, selector, DCAKeeperRole)
emitTargetFunctionRoleUpdated(DCATarget, selector, DCAKeeperRole)
}
for _, selector := range []manager.Selector{
SelectorSetTokenMinAmountPerExecution,
SelectorSetPairPriceLimit,
} {
accessState.SetTargetFunctionRole(DCATarget, selector, PoolManagerRole)
emitTargetFunctionRoleUpdated(DCATarget, selector, PoolManagerRole)
}
for _, selector := range []manager.Selector{SelectorAddWhitelistedPool, SelectorRemoveWhitelistedPool} {
accessState.SetTargetFunctionRole(WhitelistTarget, selector, PoolManagerRole)
emitTargetFunctionRoleUpdated(WhitelistTarget, selector, PoolManagerRole)
}
accessState.SetTargetFunctionRole(LimitTarget, SelectorExecuteOrder, LimitKeeperRole)
emitTargetFunctionRoleUpdated(LimitTarget, SelectorExecuteOrder, LimitKeeperRole)
}
func registerRole(role manager.RoleId, label string) {
roleLabels[role] = label
emitRoleLabel(role, label)
}
// nextCustomRoleId returns the id after the highest registered role,
// assigned by AddRole.
func nextCustomRoleId() manager.RoleId {
next := manager.RoleId(1)
for role := range roleLabels {
if role >= next {
next = role + 1
}
}
return next
}
func isRegisteredRole(role manager.RoleId) bool {
_, found := roleLabels[role]
return found
}
func isLabelTaken(label string) bool {
for _, existing := range roleLabels {
if existing == label {
return true
}
}
return false
}