utils.gno
1.57 Kb · 60 lines
1package pool
2
3import (
4 "strconv"
5 "strings"
6
7 ufmt "gno.land/p/nt/ufmt/v0"
8)
9
10const (
11 MAX_TICK int32 = 887272
12 ENCODED_TICK_OFFSET int32 = MAX_TICK
13)
14
15// GetPoolPath generates a unique pool path string based on the token paths and fee tier.
16func GetPoolPath(token0Path, token1Path string, fee uint32) string {
17 // All the token paths in the pool are sorted in alphabetical order.
18 if strings.Compare(token1Path, token0Path) < 0 {
19 token0Path, token1Path = token1Path, token0Path
20 }
21
22 return token0Path + ":" + token1Path + ":" + strconv.FormatUint(uint64(fee), 10)
23}
24
25// EncodeTickKey encodes a tick to a string key for the tick tree.
26func EncodeTickKey(tick int32) string {
27 var buf [10]byte
28 encodeTickKeyToBuffer(buf[:], tick)
29 return string(buf[:])
30}
31
32// EncodePositionKey encodes a position range into a fixed-width 20-byte string.
33func EncodePositionKey(tickLower, tickUpper int32) string {
34 var buf [20]byte
35 encodeTickKeyToBuffer(buf[:10], tickLower)
36 encodeTickKeyToBuffer(buf[10:], tickUpper)
37 return string(buf[:])
38}
39
40func encodeTickKeyToBuffer(dst []byte, tick int32) {
41 adjustTick := tick + ENCODED_TICK_OFFSET
42 if adjustTick < 0 {
43 panic(ufmt.Sprintf("tick(%d) + ENCODED_TICK_OFFSET(%d) < 0", tick, ENCODED_TICK_OFFSET))
44 }
45
46 for i := len(dst) - 1; i >= 0; i-- {
47 dst[i] = byte('0' + adjustTick%10)
48 adjustTick /= 10
49 }
50}
51
52// DecodeTickKey decodes a string key to a tick.
53func DecodeTickKey(s string) int32 {
54 adjustTick, err := strconv.ParseInt(s, 10, 32)
55 if err != nil {
56 panic(ufmt.Sprintf("invalid tick key: %s", s))
57 }
58
59 return int32(adjustTick) - ENCODED_TICK_OFFSET
60}