Search Apps Documentation Source Content File Folder Download Copy Actions Download

utils.gno

1.62 Kb ยท 63 lines
 1package pool
 2
 3import (
 4	"strconv"
 5	"strings"
 6
 7	"gno.land/p/nt/ufmt"
 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
25func ParsePoolPath(poolPath string) (string, string, uint32) {
26	parts := strings.Split(poolPath, ":")
27	if len(parts) != 3 {
28		panic(ufmt.Sprintf("invalid pool path: %s", poolPath))
29	}
30
31	fee, err := strconv.ParseUint(parts[2], 10, 32)
32	if err != nil {
33		panic(ufmt.Sprintf("invalid fee: %s", parts[2]))
34	}
35
36	return parts[0], parts[1], uint32(fee)
37}
38
39// EncodeTickKey encodes a tick to a string key for the tick tree.
40func EncodeTickKey(tick int32) string {
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	// Convert the value to a decimal string.
47	s := strconv.FormatInt(int64(adjustTick), 10)
48
49	// Zero-pad to a total length of 10 characters.
50	zerosNeeded := 10 - len(s)
51
52	return strings.Repeat("0", zerosNeeded) + s
53}
54
55// DecodeTickKey decodes a string key to a tick.
56func DecodeTickKey(s string) int32 {
57	adjustTick, err := strconv.ParseInt(s, 10, 32)
58	if err != nil {
59		panic(ufmt.Sprintf("invalid tick key: %s", s))
60	}
61
62	return int32(adjustTick) - ENCODED_TICK_OFFSET
63}