|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/ed25519" |
| 5 | + "encoding/base64" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "log/slog" |
| 10 | + "net/http" |
| 11 | + "net/url" |
| 12 | + "sort" |
| 13 | + "strings" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +type Client struct { |
| 18 | + apiKey string // Base64 encoded public key |
| 19 | + privateKey ed25519.PrivateKey |
| 20 | + baseURL string |
| 21 | + httpClient *http.Client |
| 22 | + window int64 // Time window in milliseconds |
| 23 | +} |
| 24 | + |
| 25 | +// NewClient creates a new Backpack API client |
| 26 | +func NewClient(apiKey string, privateKey ed25519.PrivateKey) (*Client, error) { |
| 27 | + return &Client{ |
| 28 | + apiKey: apiKey, |
| 29 | + privateKey: privateKey, |
| 30 | + baseURL: "https://api.backpack.exchange", |
| 31 | + httpClient: &http.Client{}, |
| 32 | + window: 5000, // Default window value |
| 33 | + }, nil |
| 34 | +} |
| 35 | + |
| 36 | +func (c *Client) SetBaseURL(baseURL string) { |
| 37 | + c.baseURL = baseURL |
| 38 | +} |
| 39 | + |
| 40 | +func (c *Client) SetWindow(window int64) { |
| 41 | + if window > 60000 { |
| 42 | + window = 60000 // Maximum allowed window |
| 43 | + } |
| 44 | + c.window = window |
| 45 | +} |
| 46 | + |
| 47 | +// createSigningString creates the string to be signed for authentication |
| 48 | +func createSigningString(instruction string, params map[string]string, timestamp int64, window int64) string { |
| 49 | + // Sort keys alphabetically |
| 50 | + var keys []string |
| 51 | + for k := range params { |
| 52 | + keys = append(keys, k) |
| 53 | + } |
| 54 | + sort.Strings(keys) |
| 55 | + |
| 56 | + // Build query string from sorted parameters |
| 57 | + var parts []string |
| 58 | + for _, k := range keys { |
| 59 | + parts = append(parts, fmt.Sprintf("%s=%s", k, params[k])) |
| 60 | + } |
| 61 | + |
| 62 | + // Create the signing string with instruction, params, timestamp and window |
| 63 | + signingString := fmt.Sprintf("instruction=%s", instruction) |
| 64 | + if len(parts) > 0 { |
| 65 | + signingString += "&" + strings.Join(parts, "&") |
| 66 | + } |
| 67 | + signingString += fmt.Sprintf("×tamp=%d&window=%d", timestamp, window) |
| 68 | + |
| 69 | + return signingString |
| 70 | +} |
| 71 | + |
| 72 | +// sign creates the signature for authentication |
| 73 | +func (c *Client) sign(instruction string, params map[string]string, timestamp int64) string { |
| 74 | + signingString := createSigningString(instruction, params, timestamp, c.window) |
| 75 | + fmt.Println("signingString", signingString) |
| 76 | + signature := ed25519.Sign(c.privateKey, []byte(signingString)) |
| 77 | + return base64.StdEncoding.EncodeToString(signature) |
| 78 | +} |
| 79 | + |
| 80 | +// Request makes an authenticated HTTP request to the Backpack API |
| 81 | +func (c *Client) Request(method, path, instruction string, input interface{}, output interface{}, query url.Values) ([]byte, error) { |
| 82 | + method = strings.ToUpper(method) |
| 83 | + apiUrl := c.baseURL + path |
| 84 | + |
| 85 | + log := slog.With("method", method, "url", apiUrl, "instruction", instruction) |
| 86 | + |
| 87 | + // Prepare parameters for signing |
| 88 | + params := make(map[string]string) |
| 89 | + |
| 90 | + // Handle input body parameters |
| 91 | + var bodyStr string |
| 92 | + if input != nil { |
| 93 | + jsonBody, err := json.Marshal(input) |
| 94 | + if err != nil { |
| 95 | + return nil, fmt.Errorf("failed to marshal request body: %w", err) |
| 96 | + } |
| 97 | + bodyStr = string(jsonBody) |
| 98 | + |
| 99 | + // Parse JSON body into map for signing |
| 100 | + var bodyMap map[string]interface{} |
| 101 | + if err := json.Unmarshal(jsonBody, &bodyMap); err != nil { |
| 102 | + return nil, fmt.Errorf("failed to unmarshal request body for signing: %w", err) |
| 103 | + } |
| 104 | + |
| 105 | + // Convert all values to strings for the signing map |
| 106 | + for k, v := range bodyMap { |
| 107 | + params[k] = fmt.Sprintf("%v", v) |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + // Handle query parameters |
| 112 | + for k, values := range query { |
| 113 | + if len(values) > 0 { |
| 114 | + params[k] = values[0] |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + log.Debug("request", "body", bodyStr, "params", params) |
| 119 | + |
| 120 | + // Generate timestamp |
| 121 | + timestamp := time.Now().UnixMilli() |
| 122 | + |
| 123 | + // Generate signature |
| 124 | + signature := c.sign(instruction, params, timestamp) |
| 125 | + |
| 126 | + // Create request |
| 127 | + var reqBody io.Reader |
| 128 | + if bodyStr != "" { |
| 129 | + reqBody = strings.NewReader(bodyStr) |
| 130 | + } |
| 131 | + |
| 132 | + // Append query to URL if needed |
| 133 | + if len(query) > 0 { |
| 134 | + apiUrl += "?" + query.Encode() |
| 135 | + } |
| 136 | + |
| 137 | + req, err := http.NewRequest(method, apiUrl, reqBody) |
| 138 | + if err != nil { |
| 139 | + return nil, fmt.Errorf("failed to create request: %w", err) |
| 140 | + } |
| 141 | + |
| 142 | + // Set headers |
| 143 | + req.Header.Set("Content-Type", "application/json") |
| 144 | + req.Header.Set("X-API-Key", c.apiKey) |
| 145 | + req.Header.Set("X-Timestamp", fmt.Sprintf("%d", timestamp)) |
| 146 | + req.Header.Set("X-Window", fmt.Sprintf("%d", c.window)) |
| 147 | + req.Header.Set("X-Signature", signature) |
| 148 | + |
| 149 | + resp, err := c.httpClient.Do(req) |
| 150 | + if err != nil { |
| 151 | + return nil, fmt.Errorf("failed to send request: %w", err) |
| 152 | + } |
| 153 | + defer resp.Body.Close() |
| 154 | + |
| 155 | + respBody, err := io.ReadAll(resp.Body) |
| 156 | + if err != nil { |
| 157 | + return nil, fmt.Errorf("failed to read response body: %w", err) |
| 158 | + } |
| 159 | + log.Debug("response", "status", resp.StatusCode, "body", string(respBody)) |
| 160 | + |
| 161 | + if resp.StatusCode != http.StatusOK { |
| 162 | + var backpackError struct { |
| 163 | + Code int `json:"code"` |
| 164 | + Message string `json:"message"` |
| 165 | + } |
| 166 | + if err := json.Unmarshal(respBody, &backpackError); err == nil { |
| 167 | + return nil, fmt.Errorf("request failed with code %d: %s", backpackError.Code, backpackError.Message) |
| 168 | + } |
| 169 | + return nil, fmt.Errorf("request failed %d: %s", resp.StatusCode, string(respBody)) |
| 170 | + } |
| 171 | + |
| 172 | + if output != nil { |
| 173 | + err = json.Unmarshal(respBody, output) |
| 174 | + if err != nil { |
| 175 | + return nil, fmt.Errorf("failed to unmarshal response body: %w", err) |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + return respBody, nil |
| 180 | +} |
0 commit comments