Skip to content

Commit 33b464c

Browse files
committed
docs: comments, docs, ...
1 parent d4aa3cb commit 33b464c

29 files changed

+152
-66
lines changed

Diff for: contract/r/gnoswap/common/tick_math.gno

+16-16
Original file line numberDiff line numberDiff line change
@@ -270,23 +270,23 @@ func adjustRatio(ratio, msb *u256.Uint) *u256.Uint {
270270
//
271271
// This function iteratively squares the ratio and adjusts the result to compute the log base 2, which will determine the tick value.
272272
func calculateLog2(msb, ratio *u256.Uint) *i256.Int {
273-
_msb := i256.FromUint256(msb)
274-
_128 := i256.NewInt(128)
273+
msbInt := i256.FromUint256(msb)
274+
constant128 := i256.NewInt(128)
275275

276-
log_2 := i256.Zero().Sub(_msb, _128)
277-
log_2 = log_2.Lsh(log_2, 64)
276+
log2Result := i256.Zero().Sub(msbInt, constant128)
277+
log2Result = log2Result.Lsh(log2Result, 64)
278278

279-
for i := 63; i >= 51; i-- {
279+
for bitPosition := 63; bitPosition >= 51; bitPosition-- {
280280
ratio = new(u256.Uint).Mul(ratio, ratio)
281281
ratio = ratio.Rsh(ratio, 127)
282282

283-
f := i256.FromUint256(new(u256.Uint).Rsh(ratio, 128))
283+
shiftFactor := i256.FromUint256(new(u256.Uint).Rsh(ratio, 128))
284284

285-
// log_2 = log_2 | (f << i)
286-
log_2 = i256.Zero().Or(log_2, i256.Zero().Lsh(f, uint(i)))
285+
// log2Result = log2Result | (shiftFactor << bitPosition)
286+
log2Result = i256.Zero().Or(log2Result, i256.Zero().Lsh(shiftFactor, uint(bitPosition)))
287287

288-
// ratio = ratio >> uint64(f)
289-
ratio = ratio.Rsh(ratio, uint(f.Uint64()))
288+
// ratio = ratio >> uint64(shiftFactor)
289+
ratio = ratio.Rsh(ratio, uint(shiftFactor.Uint64()))
290290
}
291291

292292
// handle the remaining bits
@@ -295,12 +295,12 @@ func calculateLog2(msb, ratio *u256.Uint) *i256.Int {
295295
ratio = new(u256.Uint).Mul(ratio, ratio)
296296
ratio = new(u256.Uint).Rsh(ratio, 127)
297297

298-
f := i256.FromUint256(new(u256.Uint).Rsh(ratio, 128))
298+
shiftFactor := i256.FromUint256(new(u256.Uint).Rsh(ratio, 128))
299299

300-
log_2 = i256.Zero().Or(log_2, i256.Zero().Lsh(f, 50))
300+
log2Result = i256.Zero().Or(log2Result, i256.Zero().Lsh(shiftFactor, 50))
301301
}
302302

303-
return log_2
303+
return log2Result
304304
}
305305

306306
// getTickValue determines the tick value corresponding to a given sqrtPriveX96.
@@ -310,17 +310,17 @@ func calculateLog2(msb, ratio *u256.Uint) *i256.Int {
310310
func getTickValue(log2 *i256.Int, sqrtPriceX96 *u256.Uint) int32 {
311311
// ref: https://github.com/Uniswap/v3-core/issues/500
312312
// 2^64 / log2 (√1.0001) = 255738958999603826347141
313-
log_sqrt10001 := i256.Zero().Mul(log2, i256.MustFromDecimal("255738958999603826347141"))
313+
logSqrtRatioMultiplier := i256.Zero().Mul(log2, i256.MustFromDecimal("255738958999603826347141"))
314314

315315
// ref: https://ethereum.stackexchange.com/questions/113844/how-does-uniswap-v3s-logarithm-library-tickmath-sol-work/113912#113912
316316
// 0.010000497 x 2^128 = 3402992956809132418596140100660247210
317-
tickLow256 := i256.Zero().Sub(log_sqrt10001, i256.MustFromDecimal("3402992956809132418596140100660247210"))
317+
tickLow256 := i256.Zero().Sub(logSqrtRatioMultiplier, i256.MustFromDecimal("3402992956809132418596140100660247210"))
318318
tickLow256 = tickLow256.Rsh(tickLow256, 128)
319319
tickLow := int32(tickLow256.Int64())
320320

321321
// ref: https://ethereum.stackexchange.com/questions/113844/how-does-uniswap-v3s-logarithm-library-tickmath-sol-work/113912#113912
322322
// 0.856 x 2^128 = 291339464771989622907027621153398088495
323-
tickHi256 := i256.Zero().Add(log_sqrt10001, i256.MustFromDecimal("291339464771989622907027621153398088495"))
323+
tickHi256 := i256.Zero().Add(logSqrtRatioMultiplier, i256.MustFromDecimal("291339464771989622907027621153398088495"))
324324
tickHi256 = tickHi256.Rsh(tickHi256, 128)
325325
tickHi := int32(tickHi256.Int64())
326326

Diff for: contract/r/gnoswap/gns/gns.gno

+4-4
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ var (
2525
privateLedger *grc20.PrivateLedger
2626
UserTeller grc20.Teller
2727

28-
leftEmissionAmount uint64
29-
mintedEmissionAmount uint64
30-
lastMintedHeight int64
28+
leftEmissionAmount uint64 // amount of GNS can be minted for emission
29+
mintedEmissionAmount uint64 // amount of GNS that has been minted for emission
30+
lastMintedHeight int64 // last block height that gns was minted for emission
3131

32-
burnAmount uint64
32+
burnAmount uint64 // amount of GNS that has been burned
3333
)
3434

3535
func init() {

Diff for: contract/r/gnoswap/gns/halving.gno

+2
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,8 @@ func (h *HalvingData) setAmountPerBlock(year int64, amount uint64) {
162162
h.amountPerBlock[year-1] = amount
163163
}
164164

165+
// initialize initializes the halving data based on release schedule
166+
// ref: https://docs.gnoswap.io/gnoswap-token/release-schedule
165167
func (h *HalvingData) initialize(startHeight, startTimestamp int64) {
166168
for year := HALVING_START_YEAR; year <= HALVING_END_YEAR; year++ {
167169
// set max emission amount per year

Diff for: contract/r/gnoswap/gov/doc.gno

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
1-
// Package gov manages the governance of the gnoswap protocol, including proposal creation, voting, and execution.
1+
// Package gov provides Gnoswap's governance system through three packages:
2+
// 1. governance: Handles proposal creation, voting, and execution
3+
// 2. staker: Manages GNS staking, delegation, and reward distribution
4+
// 3. xgns: Implements the xGNS token representing staked GNS
25
package gov

Diff for: contract/r/gnoswap/gov/governance/doc.gno

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Package governance implements proposal lifecycle management and voting.
2+
// It supports text proposals, parameter changes, and community pool spending.
3+
// Proposals go through creation, voting, and execution phases with configurable
4+
// parameters for voting delays, periods, and thresholds.
5+
package governance

Diff for: contract/r/gnoswap/gov/governance/execute.gno

+5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ import (
1414
en "gno.land/r/gnoswap/v1/emission"
1515
)
1616

17+
// Governance can execute multiple messages in a single proposal
18+
// each message is a string with the following format:
19+
// <pkgPath>*EXE*<function>*EXE*<params>
20+
// To execute a message, we need to parse the message and call the corresponding function
21+
// with the given parameters
1722
const (
1823
EXECUTE_SEPARATOR = "*EXE*"
1924
)

Diff for: contract/r/gnoswap/gov/governance/proposal.gno

+10
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ var (
2222
latestProposalByProposer = avl.NewTree() // proposer -> proposalId
2323
)
2424

25+
// Governance can execute multiple messages in a single proposal
26+
// To separate the messages, we use this separator
27+
// Look for ProposeParameterChange() for more details
2528
const (
2629
GOV_SPLIT = "*GOV*"
2730
)
@@ -175,6 +178,10 @@ func ProposeCommunityPoolSpend(
175178

176179
// ProposeParameterChange creates a new parameter change with the given data
177180
// It checks if the proposer is eligible to create a proposal and if they don't have an active proposal.
181+
// Through gnoswap interface, following string will be passed in for executions:
182+
// <pkgPath>*EXE*<function>*EXE*<params>*GOV*<pkgPath>*EXE*<function>*EXE*<params>
183+
// *GOV* is used to separate the messages
184+
//
178185
// Returns the proposal ID
179186
// ref: https://docs.gnoswap.io/contracts/governance/proposal.gno#proposeparameterchange
180187
func ProposeParameterChange(
@@ -392,6 +399,9 @@ func (u *proposalStateUpdater) updateExecutionState() {
392399
}
393400
}
394401

402+
// checkEnoughXGnsToPropose checks if the proposer has enough xGNS to propose a proposal.
403+
// ref: https://docs.gnoswap.io/core-concepts/governance#scope-of-proposals-5
404+
// It returns a boolean indicating if the proposer has enough xGNS, the balance of xGNS, and the threshold of xGNS.
395405
func checkEnoughXGnsToPropose(proposer std.Address) (bool, uint64, uint64) {
396406
xGNSBalance := xgns.BalanceOf(proposer)
397407

Diff for: contract/r/gnoswap/gov/governance/type.gno

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
)
88

99
// Config represents the configuration of the governor contract
10+
// ref: https://docs.gnoswap.io/core-concepts/governance#scope-of-proposals-5
1011
type Config struct {
1112
// How long after a proposal is created does voting starrt
1213
VotingStartDelay uint64

Diff for: contract/r/gnoswap/gov/governance/utils.gno

+18
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"gno.land/p/demo/ufmt"
1212
)
1313

14+
// Retrieves a proposal by its ID
1415
func mustGetProposal(proposalId uint64) ProposalInfo {
1516
result, exists := proposals.Get(formatUint(proposalId))
1617
if !exists {
@@ -23,6 +24,7 @@ func mustGetProposal(proposalId uint64) ProposalInfo {
2324
return result.(ProposalInfo)
2425
}
2526

27+
// Retrieves a vote by its key
2628
func mustGetVote(key string) bool {
2729
vote, exists := votes.Get(key)
2830
if !exists {
@@ -38,8 +40,10 @@ func mustGetVote(key string) bool {
3840
func getVoteInfoFromKey(voteKey string) (voteWithWeight, bool) {
3941
mustGetVote(voteKey)
4042

43+
// Splits the vote key into proposal ID and user address
4144
pid, addr := divideVoteKeyToProposalIdAndUser(voteKey)
4245

46+
// Retrieves user vote information
4347
voteInfo, exists := getUserVote(addr, pid)
4448
if !exists {
4549
panic(addDetailToError(
@@ -51,15 +55,18 @@ func getVoteInfoFromKey(voteKey string) (voteWithWeight, bool) {
5155
return voteInfo, true
5256
}
5357

58+
// Retrieves vote information by key
5459
func mustGetVoteInfo(voteKey string) voteWithWeight {
5560
voteInfo, _ := getVoteInfoFromKey(voteKey)
5661
return voteInfo
5762
}
5863

64+
// Iterates over an AVL tree and applies a callback function to each element
5965
func iterTree(tree *avl.Tree, cb func(key string, value interface{}) bool) {
6066
tree.Iterate("", "", cb)
6167
}
6268

69+
// Converts a string to an integer, panics if conversion fails
6370
func strToInt(str string) int {
6471
res, err := strconv.Atoi(str)
6572
if err != nil {
@@ -69,13 +76,15 @@ func strToInt(str string) int {
6976
return res
7077
}
7178

79+
// Converts a boolean vote to a string representation
7280
func voteToString(b bool) string {
7381
if b {
7482
return "yes"
7583
}
7684
return "no"
7785
}
7886

87+
// Marshals a JSON node to a string, panics if marshalling fails
7988
func marshal(data *json.Node) string {
8089
b, err := json.Marshal(data)
8190
if err != nil {
@@ -85,10 +94,12 @@ func marshal(data *json.Node) string {
8594
return string(b)
8695
}
8796

97+
// Encodes a string to base64
8898
func b64Encode(data string) string {
8999
return string(base64.StdEncoding.EncodeToString([]byte(data)))
90100
}
91101

102+
// Decodes a base64 string, panics if decoding fails
92103
func b64Decode(data string) string {
93104
decoded, err := base64.StdEncoding.DecodeString(data)
94105
if err != nil {
@@ -97,15 +108,18 @@ func b64Decode(data string) string {
97108
return string(decoded)
98109
}
99110

111+
// Returns the package path of the previous realm
100112
func prevRealm() string {
101113
return std.PrevRealm().PkgPath()
102114
}
103115

116+
// Returns the address and package path of the previous realm
104117
func getPrev() (string, string) {
105118
prev := std.PrevRealm()
106119
return prev.Addr().String(), prev.PkgPath()
107120
}
108121

122+
// Formats an unsigned integer to a string
109123
func formatUint(v interface{}) string {
110124
switch v := v.(type) {
111125
case uint8:
@@ -119,10 +133,12 @@ func formatUint(v interface{}) string {
119133
}
120134
}
121135

136+
// Formats a boolean to a string
122137
func formatBool(v bool) string {
123138
return strconv.FormatBool(v)
124139
}
125140

141+
// Parses a string to an integer, panics if parsing fails
126142
func parseInt(s string) int {
127143
num, err := strconv.ParseInt(s, 10, 64)
128144
if err != nil {
@@ -131,6 +147,7 @@ func parseInt(s string) int {
131147
return int(num)
132148
}
133149

150+
// Parses a string to an unsigned 64-bit integer, panics if parsing fails
134151
func parseUint64(s string) uint64 {
135152
num, err := strconv.ParseUint(s, 10, 64)
136153
if err != nil {
@@ -139,6 +156,7 @@ func parseUint64(s string) uint64 {
139156
return num
140157
}
141158

159+
// Parses a string to a boolean, panics if parsing fails
142160
func parseBool(s string) bool {
143161
switch s {
144162
case "true":

Diff for: contract/r/gnoswap/gov/governance/vote.gno

+6
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,15 @@ var (
2929
accumNoVotes = make(map[uint64]uint64) // proposalId -> no
3030
)
3131

32+
// createVoteKey creates a vote key for a given proposal ID and voter address
3233
func createVoteKey(pid uint64, voter string) string {
3334
return ufmt.Sprintf("%d:%s", pid, voter)
3435
}
3536

37+
// getVote gets a vote for a given proposal ID and voter address
38+
// Returns:
39+
// - vote: the vote for the given proposal ID and voter address
40+
// - exists: a boolean indicating if user has voted on the proposal
3641
func getVote(pid uint64, voter string) (bool, bool) {
3742
value, exists := votes.Get(createVoteKey(pid, voter))
3843
if !exists {
@@ -46,6 +51,7 @@ func setVote(pid uint64, voter string, vote bool) {
4651
votes.Set(voteKey, vote)
4752
}
4853

54+
// createUserVoteKey creates a user vote key for a given voter address and proposal ID
4955
func createUserVoteKey(voter std.Address, pid uint64) string {
5056
return ufmt.Sprintf("%s:%d", voter.String(), pid)
5157
}

Diff for: contract/r/gnoswap/gov/staker/doc.gno

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Package staker manages GNS token staking and delegation functionality.
2+
// It handles delegation of voting power, distribution of protocol rewards,
3+
// and implements a 7-day lockup period for unstaking operations.
4+
package staker

Diff for: contract/r/gnoswap/gov/staker/reward_calculation.gno

+9-15
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,23 @@ import (
1515
)
1616

1717
var (
18-
currentGNSBalance uint64 = 0
19-
currentProtocolFeeBalance map[string]uint64 = make(map[string]uint64)
18+
currentGNSBalance uint64 = 0 // GNS balance of gov/staker minted by emission
19+
currentProtocolFeeBalance map[string]uint64 = make(map[string]uint64) // protocol fee balance of gov/staker (tokenPath -> balance)
2020
)
2121

22+
// getCurrentBalance gets the acuumulated GNS balance from emission to gov/staker
23+
// Need to clear the distributed GNS to gov/staker in emission to get the latest accumulated GNS balance
2224
func getCurrentBalance() uint64 {
23-
gotGnsForEmission = en.GetDistributedToGovStaker()
25+
gotGnsForEmission := en.GetDistributedToGovStaker()
2426
en.ClearDistributedToGovStaker()
2527

2628
currentGNSBalance += gotGnsForEmission
2729

2830
return currentGNSBalance
2931
}
3032

33+
// getCurrentProtocolFeeBalance gets the accumulated protocol fee balance from protocol_fee to gov/staker
34+
// Need to clear the accumulated protocol fee to gov/staker in protocol fee to get the latest accumulated protocol fee balance
3135
func getCurrentProtocolFeeBalance() map[string]uint64 {
3236
pf.DistributeProtocolFee()
3337
gotAccuProtocolFee := pf.GetAccuTransferToGovStaker()
@@ -62,7 +66,7 @@ func (self *StakerRewardInfo) PriceDebtUint64() uint64 {
6266

6367
type RewardState struct {
6468
// CurrentBalance is sum of all the previous balances, including the reward distribution.
65-
CurrentBalance uint64 // current balance of gov_staker, used to calculate RewardAccumulation
69+
CurrentBalance uint64 // current balance of gov/staker, used to calculate RewardAccumulation
6670
CurrentProtocolFeeBalance map[string]uint64 // current protocol fee balance per token
6771
PriceAccumulation *u256.Uint // claimable GNS per xGNS stake, Q128
6872
ProtocolFeePriceAccumulation map[string]*u256.Uint // protocol fee debt per xGNS stake, Q128
@@ -275,17 +279,7 @@ func (self *RewardState) RemoveStake(staker std.Address, amount uint64, currentB
275279
}
276280

277281
var (
278-
q96 = u256.MustFromDecimal(consts.Q96)
279-
lastCalculatedHeight uint64 // flag to prevent same block calculation
280-
)
281-
282-
var (
283-
gotGnsForEmission uint64
284-
leftGnsEmissionFromLast uint64
285-
alreadyCalculatedGnsEmission uint64
286-
287-
leftProtocolFeeFromLast = avl.NewTree() // tokenPath -> tokenAmount
288-
alreadyCalculatedProtocolFee = avl.NewTree() // tokenPath -> tokenAmount
282+
q96 = u256.MustFromDecimal(consts.Q96)
289283
)
290284

291285
// === LAUNCHPAD DEPOSIT

Diff for: contract/r/gnoswap/gov/staker/staker.gno

+3-2
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,14 @@ import (
1818
en "gno.land/r/gnoswap/v1/emission"
1919
)
2020

21+
// lockedGNS represents a locked GNS with its amount, unlock time, and collected status
2122
type lockedGNS struct {
2223
amount uint64
2324
unlock uint64
2425
collected bool
2526
}
2627

27-
const TIMESTAMP_7_DAYS = uint64(604800) // 7 days in seconds
28+
const SECONDS_IN_7_DAYS = uint64(604800)
2829

2930
var (
3031
addrLockedGns = avl.NewTree() // address -> []lockedGNS
@@ -217,7 +218,7 @@ func Undelegate(from std.Address, amount uint64) {
217218
// lock up
218219
userLocked := lockedGNS{
219220
amount: amount,
220-
unlock: uint64(time.Now().Unix()) + TIMESTAMP_7_DAYS, // after 7 days, call Collect() to receive GNS
221+
unlock: uint64(time.Now().Unix()) + SECONDS_IN_7_DAYS, // after 7 days, call Collect() to receive GNS
221222
}
222223

223224
var lockedList []lockedGNS

0 commit comments

Comments
 (0)