commondao.gno

2.51 Kb ยท 118 lines
  1package commondao
  2
  3import (
  4	"chain/runtime"
  5
  6	"gno.land/p/moul/txlink"
  7	"gno.land/p/nt/avl"
  8	"gno.land/p/nt/commondao"
  9	"gno.land/p/nt/seqid"
 10)
 11
 12// CommonDAOID is the ID of the realm's DAO.
 13const CommonDAOID uint64 = 1
 14
 15var (
 16	daoID     seqid.ID
 17	realmLink txlink.Realm
 18	daos      = avl.NewTree() // string(ID) -> *commondao.CommonDAO
 19	ownership = avl.NewTree() // string(address) -> []uint64(DAO ID)
 20	invites   = avl.NewTree() // string(address) -> address(inviter)
 21	trees     = avl.NewTree() // string(root ID) -> avl.Tree(string(DAO ID) -> *commondao.CommonDAO)
 22	options   = avl.NewTree() // string(ID) -> *Options
 23)
 24
 25func init() {
 26	// Save current realm path so it's available during render calls
 27	realmLink = txlink.Realm(runtime.CurrentRealm().PkgPath())
 28}
 29
 30func getDAO(daoID uint64) *commondao.CommonDAO {
 31	key := makeIDKey(daoID)
 32	if v, found := daos.Get(key); found {
 33		return v.(*commondao.CommonDAO)
 34	}
 35	return nil
 36}
 37
 38func mustGetDAO(daoID uint64) *commondao.CommonDAO {
 39	dao := getDAO(daoID)
 40	if dao == nil {
 41		panic("DAO not found")
 42	}
 43	return dao
 44}
 45
 46func getTree(rootID uint64) *avl.Tree {
 47	key := makeIDKey(rootID)
 48	if v, found := trees.Get(key); found {
 49		return v.(*avl.Tree)
 50	}
 51	return nil
 52}
 53
 54func getOwnership(addr address) []uint64 {
 55	if v, ok := ownership.Get(addr.String()); ok {
 56		return v.([]uint64)
 57	}
 58	return nil
 59}
 60
 61func getOptions(daoID uint64) *Options {
 62	key := makeIDKey(daoID)
 63	if v, found := options.Get(key); found {
 64		return v.(*Options)
 65	}
 66	return nil
 67}
 68
 69func makeIDKey(daoID uint64) string {
 70	return seqid.ID(daoID).String()
 71}
 72
 73func createDAO(name string, owner address, o []Option) *commondao.CommonDAO {
 74	id := daoID.Next()
 75	dao := commondao.New(
 76		commondao.WithID(uint64(id)),
 77		commondao.WithName(name),
 78	)
 79
 80	daoOptions := defaultOptions
 81	for _, apply := range o {
 82		apply(&daoOptions)
 83	}
 84
 85	ids := append(getOwnership(owner), uint64(id))
 86	ownership.Set(owner.String(), ids)
 87
 88	daos.Set(id.String(), dao)
 89	options.Set(id.String(), &daoOptions)
 90	return dao
 91}
 92
 93func createSubDAO(parent *commondao.CommonDAO, name string, o []Option) *commondao.CommonDAO {
 94	id := daoID.Next()
 95	dao := commondao.New(
 96		commondao.WithID(uint64(id)),
 97		commondao.WithParent(parent),
 98		commondao.WithName(name),
 99	)
100
101	daoOptions := defaultOptions
102	for _, apply := range o {
103		apply(&daoOptions)
104	}
105
106	options.Set(id.String(), &daoOptions)
107	daos.Set(id.String(), dao)
108
109	rootID := parent.TopParent().ID()
110	tree := getTree(rootID)
111	if tree == nil {
112		tree = avl.NewTree()
113		trees.Set(makeIDKey(rootID), tree)
114	}
115
116	tree.Set(id.String(), dao)
117	return dao
118}