-
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathexchange.go
More file actions
220 lines (190 loc) · 5.29 KB
/
exchange.go
File metadata and controls
220 lines (190 loc) · 5.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package hyperliquid
import (
"context"
"crypto/ecdsa"
"encoding/json"
"sync/atomic"
"time"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
)
type Exchange struct {
debug bool
client *client
privateKey *ecdsa.PrivateKey
vault string
accountAddr string
dex string
info *Info
expiresAfter *int64
lastNonce atomic.Int64
l1Signer L1ActionSigner
userSignedSigner UserSignedActionSigner
agentSigner AgentSigner
clientOpts []ClientOpt
infoOpts []InfoOpt
}
func NewExchange(
ctx context.Context,
privateKey *ecdsa.PrivateKey,
baseURL string,
meta *Meta,
vaultAddr, accountAddr string,
spotMeta *SpotMeta,
perpDexs *MixedArray,
opts ...ExchangeOpt,
) *Exchange {
ex := &Exchange{
privateKey: privateKey,
vault: vaultAddr,
accountAddr: accountAddr,
}
for _, opt := range opts {
opt.Apply(ex)
}
if ex.debug {
ex.clientOpts = append(ex.clientOpts, clientOptDebugMode())
ex.infoOpts = append(ex.infoOpts, InfoOptDebugMode())
}
ex.client = newClient(baseURL, ex.clientOpts...)
ex.info = NewInfo(ctx, baseURL, true, meta, spotMeta, perpDexs, ex.infoOpts...)
return ex
}
// nextNonce returns either the current timestamp in milliseconds or incremented by one to prevent duplicates
// Nonces must be within (T - 2 days, T + 1 day), where T is the unix millisecond timestamp on the block of the transaction.
// See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/nonces-and-api-wallets#hyperliquid-nonces
func (e *Exchange) nextNonce() int64 {
// it's possible that at exactly the same time a nextNonce is requested
for {
last := e.lastNonce.Load()
candidate := time.Now().UnixMilli()
if candidate <= last {
candidate = last + 1
}
// Try to publish our candidate; if someone beat us, retry.
if e.lastNonce.CompareAndSwap(last, candidate) {
return candidate
}
}
}
func (e *Exchange) Info() *Info {
return e.info
}
// PerpDex returns the configured builder perp dex name (e.g. "flx"), or empty string for default dex.
func (e *Exchange) PerpDex() string {
return e.dex
}
// SetExpiresAfter sets the expiration time for actions
// If expiresAfter is nil, actions will not have an expiration time
// If expiresAfter is set, actions will include this expiration nonce
func (e *Exchange) SetExpiresAfter(expiresAfter *int64) {
e.expiresAfter = expiresAfter
}
// SetLastNonce allows for resuming from a persisted nonce, e.g. the nonce was stored before a restart
// Only useful if a lot of increments happen for unique nonces. Most users do not need this.
func (e *Exchange) SetLastNonce(n int64) {
e.lastNonce.Store(n)
}
func (e *Exchange) signL1Action(
ctx context.Context,
action any,
vault string,
ts int64,
exp *int64,
mainnet bool,
) (SignatureResult, error) {
if e.l1Signer != nil {
return e.l1Signer.SignL1Action(ctx, action, vault, ts, exp, mainnet)
}
return SignL1Action(e.privateKey, action, vault, ts, exp, mainnet)
}
func (e *Exchange) signUserSignedAction(
ctx context.Context,
action map[string]any,
payloadTypes []apitypes.Type,
primaryType string,
mainnet bool,
) (SignatureResult, error) {
if e.userSignedSigner != nil {
return e.userSignedSigner.SignUserSignedAction(
ctx,
action,
payloadTypes,
primaryType,
mainnet,
)
}
return SignUserSignedAction(e.privateKey, action, payloadTypes, primaryType, mainnet)
}
func (e *Exchange) signAgent(
ctx context.Context,
agentAddress, agentName string,
nonce int64,
mainnet bool,
) (SignatureResult, error) {
if e.agentSigner != nil {
return e.agentSigner.SignAgent(ctx, agentAddress, agentName, nonce, mainnet)
}
return SignAgent(e.privateKey, agentAddress, agentName, nonce, mainnet)
}
// executeAction executes an action and unmarshals the response into the given result
func (e *Exchange) executeAction(ctx context.Context, action, result any) error {
nonce := e.nextNonce()
sig, err := e.signL1Action(
ctx,
action,
e.vault,
nonce,
e.expiresAfter,
e.client.baseURL == MainnetAPIURL,
)
if err != nil {
return err
}
resp, err := e.postAction(ctx, action, sig, nonce)
if err != nil {
return err
}
if err := json.Unmarshal(resp, result); err != nil {
return err
}
return nil
}
func (e *Exchange) postAction(
ctx context.Context,
action any,
signature SignatureResult,
nonce int64,
) ([]byte, error) {
payload := map[string]any{
"action": action,
"nonce": nonce,
"signature": signature,
}
if e.vault != "" {
// Handle vault address based on action type
if actionMap, ok := action.(map[string]any); ok {
if actionMap["type"] != "usdClassTransfer" {
payload["vaultAddress"] = e.vault
} else {
payload["vaultAddress"] = nil
}
} else {
// For struct types, we need to use reflection or type assertion
// For now, assume it's not usdClassTransfer
payload["vaultAddress"] = e.vault
}
}
// Add expiration time if set
if e.expiresAfter != nil {
payload["expiresAfter"] = *e.expiresAfter
}
// Debug logging
if e.debug { //nolint:staticcheck // Empty branch for future debugging
// if jsonPayload, err := json.MarshalIndent(payload, "", " "); err == nil {
// println("=== OUTGOING EXCHANGE PAYLOAD ===")
// println(string(jsonPayload))
// println("=================================")
// }
}
return e.client.post(ctx, "/exchange", payload)
}