Skip to content

Commit 93ef7a5

Browse files
Update utils.go (#23)
1 parent b2f2b2d commit 93ef7a5

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

hyperliquid/utils.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,30 @@ import (
1313
var nonceCounter = time.Now().UnixMilli()
1414

1515
// Hyperliquid uses timestamps in milliseconds for nonce
16+
// GetNonce returns a unique nonce that is always at least the current time in milliseconds.
17+
// It ensures thread-safe updates using atomic operations.
1618
func GetNonce() uint64 {
17-
return uint64(atomic.AddInt64(&nonceCounter, 1))
19+
now := time.Now().UnixMilli()
20+
for {
21+
// Load the current nonce value atomically.
22+
current := atomic.LoadInt64(&nonceCounter)
23+
24+
// If the current time is greater than the stored nonce,
25+
// attempt to update the nonce to the current time.
26+
if current < now {
27+
if atomic.CompareAndSwapInt64(&nonceCounter, current, now) {
28+
return uint64(now)
29+
}
30+
// If the swap fails, retry.
31+
continue
32+
}
33+
34+
// Otherwise, increment the nonce by one.
35+
newNonce := current + 1
36+
if atomic.CompareAndSwapInt64(&nonceCounter, current, newNonce) {
37+
return uint64(newNonce)
38+
}
39+
}
1840
}
1941

2042
// Retruns a random cloid (Client Order ID)

0 commit comments

Comments
 (0)