Playground
access.gno
package manager
type Access struct {
Since TimePoint
}
func NewAccess(since TimePoint) Access {
return Access{
Since: since,
}
}
func NewAccessWithDelay(since TimePoint, delay uint32) Access {
if since.IsZero() {
return Access{Since: 0}
}
return Access{
Since: since + TimePoint(delay),
}
}
func (access Access) isActiveAt(now TimePoint) bool {
if access.Since.IsZero() {
return false
}
return !access.Since.After(now)
}
consts.gno
package manager const ( AdminRole RoleId = 0 PublicRole RoleId = 1<<64 - 1 // uint64 max // MinSetback is the minimum setback for a grant delay change (5 days). // OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L164-L166 MinSetback uint32 = 5 * 24 * 60 * 60 )
delay.gno
package manager
// Delay is a value that changes only after a setback, mirroring
// OpenZeppelin's packed `Delay` type.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/utils/types/Time.sol#L61
type Delay struct {
effectDate TimePoint
valueBefore uint32
valueAfter uint32
}
func NewDelay(delay uint32) Delay {
return Delay{effectDate: 0, valueBefore: 0, valueAfter: delay}
}
// Get returns the value active at timestamp.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/utils/types/Time.sol#L86-L96
func (d Delay) Get(timestamp TimePoint) uint32 {
if d.effectDate.After(timestamp) {
return d.valueBefore
}
return d.valueAfter
}
// WithUpdate schedules newDelay to take effect at timestamp plus a setback:
// at least minSetback, or longer when newDelay decreases the active value
// by more than minSetback. Returns the updated Delay and the effect timePoint.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/utils/types/Time.sol#L103-L112
func (d Delay) WithUpdate(timestamp TimePoint, newDelay uint32, minSetback uint32) (Delay, TimePoint) {
value := d.Get(timestamp)
setback := minSetback
if value > newDelay {
if diff := value - newDelay; diff > setback {
setback = diff
}
}
effect := NewTimePoint(timestamp.Int64() + int64(setback))
return Delay{effectDate: effect, valueBefore: value, valueAfter: newDelay}, effect
}
doc.gno
// Package manager is a pure port of the core permission model of // OpenZeppelin Contracts AccessManager v5.6.1, taken from // gno.land/p/onbloc/access/manager (github.com/onbloc/gno-ibc, Apache-2.0). // // It is a state transition library, not a realm: it does not own storage, // inspect realms, or decide who the caller is. A realm stores a State, // passes the caller address, target, and selector into its methods, and // exposes the management API it needs (see gno.land/r/gnoswap/order/keeper). // // Model: // - roles are uint64 identifiers; AdminRole is 0 and PublicRole is // uint64 max, which every account holds; // - permissions are scoped by target and selector; an unset selector // defaults to AdminRole; // - a closed target rejects every call; // - each role has an admin role, a grant delay, and member records with // an activation time. // // Delayed operation scheduling (schedule, execute, cancel) is not ported. // Panics carry string messages so they can cross realm boundaries. package manager
errors.gno
package manager
import (
"errors"
"strings"
)
var (
errAccessManagerLockedRole = errors.New("access manager locked role")
errAccessManagerBadConfirmation = errors.New("access manager bad confirmation")
errAccessManagerLastAdmin = errors.New("access manager last admin")
)
func errorWithDetails(err error, msgs ...string) error {
if len(msgs) == 0 {
return err
}
return errors.New(err.Error() + ", " + strings.Join(msgs, ", "))
}
events.gno
package manager const ( EventTypeRoleLabel = "RoleLabel" EventTypeRoleGranted = "RoleGranted" EventTypeRoleRevoked = "RoleRevoked" EventTypeRoleAdminChanged = "RoleAdminChanged" EventTypeRoleGrantDelayChanged = "RoleGrantDelayChanged" EventTypeTargetClosed = "TargetClosed" EventTypeTargetFunctionRoleUpdated = "TargetFunctionRoleUpdated" ) const ( AttributeKeyTarget = "target" AttributeKeyRoleID = "role_id" AttributeKeyLabel = "label" AttributeKeyAccount = "account" AttributeKeyDelay = "delay" AttributeKeySince = "since" AttributeKeyNewMember = "new_member" AttributeKeyAdmin = "admin" AttributeKeyClosed = "closed" AttributeKeySelector = "selector" )
gnomod.toml
module = "gno.land/p/gnoswap/order/access/manager/v0" gno = "0.9" [addpkg] creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04" height = 1108535 max_deposit = "100000000ugnot"
requires.gno
package manager
import "gno.land/p/nt/ufmt/v0"
// RequireUnlockedConfigRole rejects role ids whose configuration is locked.
// Use this before emitting RoleLabel metadata from a realm.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L226-L230
func RequireUnlockedConfigRole(role RoleId) {
if role == AdminRole || role == PublicRole {
panic(errorWithDetails(errAccessManagerLockedRole, ufmt.Sprintf("role %d is locked", role)).Error())
}
}
state.gno
package manager
import "gno.land/p/nt/ufmt/v0"
type State struct {
Roles map[RoleId]*RoleConfig
Targets map[string]*TargetConfig
}
func NewState() State {
return State{
Roles: make(map[RoleId]*RoleConfig),
Targets: make(map[string]*TargetConfig),
}
}
// =================================================== GETTERS ====================================================
// CanCall reports whether caller can call target selector immediately.
// This Gno port returns only immediate authorization because scheduled
// execution and execution delay are intentionally not ported.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L140-L156
func (state *State) CanCall(caller address, target string, selector Selector) CanCallResult {
if state.IsTargetClosed(target) {
return NewCanCallResult(false)
}
role := state.GetTargetFunctionRole(target, selector)
membership := state.HasRole(role, caller)
if !membership.IsMember {
return NewCanCallResult(false)
}
return NewCanCallResult(true)
}
// IsAuthorized is a boolean convenience wrapper around CanCall.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L140-L156
func (state *State) IsAuthorized(caller address, target string, selector Selector) bool {
return state.CanCall(caller, target, selector).Immediate
}
// HasRole reports whether account currently has an active role membership.
// This Gno port returns membership only because execution delay is not ported.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L211-L220
func (state *State) HasRole(role RoleId, account address) HasRoleResult {
if role == PublicRole {
return NewHasRoleResult(true)
}
roleConfig := state.getRole(role)
if roleConfig == nil {
return NewHasRoleResult(false)
}
return NewHasRoleResult(roleConfig.hasMember(account, CurrentTimePoint()))
}
// GetRoleMemberSince returns when account's role membership became active,
// or zero if it is not a member. It corresponds to OpenZeppelin's since field;
// execution-delay fields are not ported here.
//
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L205
func (state *State) GetRoleMemberSince(role RoleId, account address) TimePoint {
roleConfig := state.getRole(role)
if roleConfig == nil {
return 0
}
access, found := roleConfig.Members[account]
if !found {
return 0
}
return access.Since
}
// GetRoleAdmin returns the admin role for role, defaulting to AdminRole.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L183-L186
func (state *State) GetRoleAdmin(role RoleId) RoleId {
roleConfig := state.getRole(role)
if roleConfig == nil {
return AdminRole
}
return roleConfig.adminRole()
}
// GetRoleGrantDelay returns the grant delay currently in effect for role. A
// change scheduled by SetGrantDelay is not reflected until its effect timePoint.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L194-L196
func (state *State) GetRoleGrantDelay(role RoleId) uint32 {
roleConfig := state.getRole(role)
if roleConfig == nil {
return 0
}
return roleConfig.grantDelay(CurrentTimePoint())
}
// GetRoleGrantDelayEffect returns when role's scheduled grant delay change
// takes effect. No OpenZeppelin equivalent; added to avoid direct field access.
func (state *State) GetRoleGrantDelayEffect(role RoleId) TimePoint {
roleConfig := state.getRole(role)
if roleConfig == nil {
return 0
}
return roleConfig.GrantDelay.effectDate
}
// GetTargetFunctionRole returns the role required for target selector.
// Unconfigured selectors default to AdminRole in this Gno representation.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L173-L176
func (state *State) GetTargetFunctionRole(target string, selector Selector) RoleId {
targetConfig := state.getTarget(target)
if targetConfig == nil {
return AdminRole
}
return targetConfig.functionRole(selector)
}
// IsTargetClosed reports whether target is closed.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L168-L171
func (state *State) IsTargetClosed(target string) bool {
targetConfig := state.getTarget(target)
return targetConfig != nil && targetConfig.isClosed()
}
// =============================================== ROLE MANAGEMENT ===============================================
// GrantRole grants role membership to account and returns true for a new member.
// This Gno port retains grant delay but intentionally omits OZ execution delay.
// OpenZeppelin references:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L233-L236
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L271-L298
func (state *State) GrantRole(role RoleId, account address) bool {
if role == PublicRole {
panic(errorWithDetails(errAccessManagerLockedRole, ufmt.Sprintf("role %d is locked", role)).Error())
}
state.ensureRole(role)
return state.getRole(role).grant(account, CurrentTimePoint())
}
// RevokeRole revokes role membership from account and reports whether it existed.
// OpenZeppelin references:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L238-L240
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L300-L319
func (state *State) RevokeRole(role RoleId, account address) bool {
if role == PublicRole {
panic(errorWithDetails(errAccessManagerLockedRole, ufmt.Sprintf("role %d is locked", role)).Error())
}
state.ensureRole(role)
if role == AdminRole && state.isLastAdmin(account) {
panic(errAccessManagerLastAdmin.Error())
}
return state.getRole(role).revoke(account)
}
// isLastAdmin reports whether account is the only currently active AdminRole
// member. Prevents bricking the system by removing the final admin.
func (state *State) isLastAdmin(account address) bool {
adminRole := state.getRole(AdminRole)
if adminRole == nil {
return false
}
now := CurrentTimePoint()
if !adminRole.hasMember(account, now) {
return false
}
for member, access := range adminRole.Members {
if member != account && access.isActiveAt(now) {
return false
}
}
return true
}
// RenounceRole revokes caller-confirmed role membership from account.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L243-L249
func (state *State) RenounceRole(role RoleId, account address, callerConfirmation address) bool {
if account != callerConfirmation {
panic(errAccessManagerBadConfirmation.Error())
}
return state.RevokeRole(role, account)
}
// SetRoleAdmin sets the admin role that can grant or revoke role.
// OpenZeppelin references:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L251-L254
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L321-L337
func (state *State) SetRoleAdmin(role RoleId, admin RoleId) {
RequireUnlockedConfigRole(role)
state.ensureRole(role)
state.getRole(role).setAdmin(admin)
}
// SetGrantDelay schedules newDelay behind a setback; it never overwrites the
// active delay on the spot. Callers read GetRoleGrantDelay for the current
// value or GetRoleGrantDelayEffect for the effect timePoint.
// AdminRole is not locked here (unlike SetRoleAdmin) — OpenZeppelin only rejects PublicRole.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L262-L264,L362-L371
func (state *State) SetGrantDelay(role RoleId, newDelay uint32) {
if role == PublicRole {
panic(errorWithDetails(errAccessManagerLockedRole, ufmt.Sprintf("role %d is locked", role)).Error())
}
state.ensureRole(role)
state.getRole(role).setGrantDelay(CurrentTimePoint(), newDelay)
}
// ============================================= FUNCTION MANAGEMENT ==============================================
// SetTargetFunctionRole sets the role required for target selector.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L385-L393
func (state *State) SetTargetFunctionRole(target string, selector Selector, role RoleId) {
state.ensureTarget(target)
state.getTarget(target).setFunctionRole(selector, role)
}
// SetTargetFunctionRoles sets the same role for multiple target selectors.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L373-L383
func (state *State) SetTargetFunctionRoles(target string, selectors []Selector, role RoleId) {
state.ensureTarget(target)
state.getTarget(target).setFunctionRoles(selectors, role)
}
// =============================================== MODE MANAGEMENT ================================================
// SetTargetClosed sets whether target rejects calls regardless of selector role.
// OpenZeppelin references:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L412-L416
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L418-L426
func (state *State) SetTargetClosed(target string, closed bool) {
state.ensureTarget(target)
state.getTarget(target).setClosed(closed)
}
// ================================================= ADMIN LOGIC ==================================================
// CanAdminRole reports whether caller has the admin role required for role.
// OpenZeppelin reference:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L652-L657
func (state *State) CanAdminRole(role RoleId, caller address) CanCallResult {
adminRole := state.GetRoleAdmin(role)
membership := state.HasRole(adminRole, caller)
if !membership.IsMember {
return NewCanCallResult(false)
}
return NewCanCallResult(true)
}
// CanManageTarget reports whether caller can manage target configuration.
// OpenZeppelin references:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L101-L105
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L640-L650
func (state *State) CanManageTarget(caller address) CanCallResult {
membership := state.HasRole(AdminRole, caller)
if !membership.IsMember {
return NewCanCallResult(false)
}
return NewCanCallResult(true)
}
func (state *State) getRole(role RoleId) *RoleConfig {
return state.Roles[role]
}
func (state *State) getTarget(target string) *TargetConfig {
return state.Targets[target]
}
func (state *State) ensureRole(role RoleId) {
roleConfig, found := state.Roles[role]
if !found || roleConfig == nil {
state.Roles[role] = NewRoleConfig(AdminRole, 0)
}
}
func (state *State) ensureTarget(target string) {
targetConfig, found := state.Targets[target]
if !found || targetConfig == nil {
state.Targets[target] = NewTargetConfig(false)
}
}
state_role.gno
package manager
import "strconv"
type RoleId uint64
func NewRoleId(id uint64) RoleId {
return RoleId(id)
}
func (r RoleId) Uint64() uint64 {
return uint64(r)
}
func (r RoleId) String() string {
return strconv.FormatUint(uint64(r), 10)
}
type RoleConfig struct {
Members map[address]Access
Admin RoleId
GrantDelay Delay
}
func NewRoleConfig(admin RoleId, grantDelay uint32) *RoleConfig {
return &RoleConfig{
Members: make(map[address]Access),
Admin: admin,
GrantDelay: NewDelay(grantDelay),
}
}
func (roleConfig *RoleConfig) grant(account address, now TimePoint) bool {
_, found := roleConfig.Members[account]
if found {
return false
}
roleConfig.Members[account] = NewAccessWithDelay(now, roleConfig.grantDelay(now))
return true
}
func (roleConfig *RoleConfig) revoke(account address) bool {
_, found := roleConfig.Members[account]
if found {
delete(roleConfig.Members, account)
}
return found
}
func (roleConfig *RoleConfig) hasMember(account address, now TimePoint) bool {
access, found := roleConfig.Members[account]
if !found {
return false
}
return access.isActiveAt(now)
}
func (roleConfig *RoleConfig) setAdmin(admin RoleId) {
roleConfig.Admin = admin
}
func (roleConfig *RoleConfig) adminRole() RoleId {
return roleConfig.Admin
}
// setGrantDelay schedules newDelay behind the MinSetback setback. Callers
// read the effect timePoint via State.GetRoleGrantDelayEffect.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L362-L371
func (roleConfig *RoleConfig) setGrantDelay(now TimePoint, newDelay uint32) {
updated, _ := roleConfig.GrantDelay.WithUpdate(now, newDelay, MinSetback)
roleConfig.GrantDelay = updated
}
// grantDelay returns the grant delay active at now.
// OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/5fd1781b1454fd1ef8e722282f86f9293cacf256/contracts/access/manager/AccessManager.sol#L194-L196
func (roleConfig *RoleConfig) grantDelay(now TimePoint) uint32 {
return roleConfig.GrantDelay.Get(now)
}
state_target.gno
package manager
type TargetConfig struct {
FunctionRoles map[Selector]RoleId
Closed bool
}
func NewTargetConfig(closed bool) *TargetConfig {
return &TargetConfig{
FunctionRoles: make(map[Selector]RoleId),
Closed: closed,
}
}
func (targetConfig *TargetConfig) setFunctionRole(selector Selector, role RoleId) {
targetConfig.ensureFunctionRoles()
targetConfig.FunctionRoles[selector] = role
}
func (targetConfig *TargetConfig) setFunctionRoles(selectors []Selector, role RoleId) {
for i := range selectors {
targetConfig.setFunctionRole(selectors[i], role)
}
}
func (targetConfig *TargetConfig) functionRole(selector Selector) RoleId {
targetConfig.ensureFunctionRoles()
role, found := targetConfig.FunctionRoles[selector]
if !found {
return AdminRole
}
return role
}
func (targetConfig *TargetConfig) setClosed(closed bool) {
targetConfig.Closed = closed
}
func (targetConfig *TargetConfig) isClosed() bool {
return targetConfig.Closed
}
func (targetConfig *TargetConfig) ensureFunctionRoles() {
if targetConfig.FunctionRoles == nil {
targetConfig.FunctionRoles = make(map[Selector]RoleId)
}
}
timepoint.gno
package manager
import (
"strconv"
"time"
)
type TimePoint int64
func NewTimePoint(timePoint int64) TimePoint {
return TimePoint(timePoint)
}
func CurrentTimePoint() TimePoint {
return TimePoint(time.Now().Unix())
}
func (t TimePoint) After(other TimePoint) bool {
return t > other
}
func (t TimePoint) Before(other TimePoint) bool {
return t < other
}
func (t TimePoint) Equal(other TimePoint) bool {
return t == other
}
func (t TimePoint) String() string {
return strconv.FormatInt(int64(t), 10)
}
func (t TimePoint) Int64() int64 {
return int64(t)
}
func (t TimePoint) IsZero() bool {
return t == 0
}
types.gno
package manager
type Selector string
func NewSelector(selector string) Selector {
return Selector(selector)
}
type CanCallResult struct {
Immediate bool
}
func NewCanCallResult(immediate bool) CanCallResult {
return CanCallResult{
Immediate: immediate,
}
}
type HasRoleResult struct {
IsMember bool
}
func NewHasRoleResult(isMember bool) HasRoleResult {
return HasRoleResult{
IsMember: isMember,
}
}