Skip to main content

nautilus_polymarket/http/
auth.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! L1 API credential creation and derivation for the Polymarket CLOB.
17
18use std::collections::HashMap;
19
20use nautilus_core::{string::secret::SecretString, time::get_atomic_clock_realtime};
21use nautilus_network::http::{
22    HttpClient, HttpRedirectPolicy, Method, create_standard_nautilus_headers,
23};
24use serde::Deserialize;
25use zeroize::{Zeroize, ZeroizeOnDrop};
26
27use crate::{
28    common::{credential::EvmPrivateKey, urls::clob_http_url},
29    http::error::{Error, Result, decode_response},
30    signing::eip712::sign_clob_auth,
31};
32
33/// API credentials returned by the Polymarket CLOB auth endpoints.
34#[derive(Debug, Deserialize, Zeroize, ZeroizeOnDrop)]
35#[serde(rename_all = "camelCase")]
36pub struct ApiCredentials {
37    pub api_key: SecretString,
38    pub secret: SecretString,
39    pub passphrase: SecretString,
40}
41
42/// Creates new API credentials via `POST /auth/api-key` using L1 authentication.
43///
44/// Fails if credentials already exist for this `(address, nonce)` pair.
45/// Use [`derive_api_key`] to retrieve existing credentials, or
46/// [`create_or_derive_api_key`] for idempotent behavior.
47pub async fn create_api_key(
48    private_key: &EvmPrivateKey,
49    nonce: u64,
50    base_url: Option<&str>,
51) -> Result<ApiCredentials> {
52    let (client, headers, base) = prepare_l1_request(private_key, nonce, base_url)?;
53    let url = format!("{base}/auth/api-key");
54    let response = client
55        .request(Method::POST, url, None, Some(headers), None, None, None)
56        .await
57        .map_err(Error::from_http_client)?;
58
59    decode_response(&response)
60}
61
62/// Derives existing API credentials via `GET /auth/derive-api-key` using L1 authentication.
63///
64/// Fails if no credentials exist for this `(address, nonce)` pair.
65/// Use [`create_api_key`] to create new credentials, or
66/// [`create_or_derive_api_key`] for idempotent behavior.
67pub async fn derive_api_key(
68    private_key: &EvmPrivateKey,
69    nonce: u64,
70    base_url: Option<&str>,
71) -> Result<ApiCredentials> {
72    let (client, headers, base) = prepare_l1_request(private_key, nonce, base_url)?;
73    let url = format!("{base}/auth/derive-api-key");
74    let response = client
75        .request(Method::GET, url, None, Some(headers), None, None, None)
76        .await
77        .map_err(Error::from_http_client)?;
78
79    decode_response(&response)
80}
81
82/// Creates or derives API credentials using L1 (EIP-712) authentication.
83///
84/// First attempts `POST /auth/api-key` (create). On HTTP-level errors
85/// (e.g. nonce already used), falls back to `GET /auth/derive-api-key`
86/// (derive). Transport and network errors are propagated immediately
87/// without attempting the fallback.
88pub async fn create_or_derive_api_key(
89    private_key: &EvmPrivateKey,
90    nonce: u64,
91    base_url: Option<&str>,
92) -> Result<ApiCredentials> {
93    match create_api_key(private_key, nonce, base_url).await {
94        Ok(creds) => Ok(creds),
95        Err(e) if e.is_http_status_error() => derive_api_key(private_key, nonce, base_url).await,
96        Err(e) => Err(e),
97    }
98}
99
100fn prepare_l1_request(
101    private_key: &EvmPrivateKey,
102    nonce: u64,
103    base_url: Option<&str>,
104) -> Result<(HttpClient, HashMap<String, String>, String)> {
105    let base = base_url
106        .unwrap_or_else(|| clob_http_url())
107        .trim_end_matches('/')
108        .to_string();
109    let timestamp =
110        (get_atomic_clock_realtime().get_time_ns().as_u64() / 1_000_000_000).to_string();
111    let (address, signature) = sign_clob_auth(private_key, &timestamp, nonce)?;
112    let headers = l1_headers(&address, &signature, &timestamp, nonce);
113    let client = HttpClient::builder()
114        .redirect_policy(HttpRedirectPolicy::Reject)
115        .headers(create_standard_nautilus_headers().into_iter().collect())
116        .build()
117        .map_err(Error::from_http_client)?;
118    Ok((client, headers, base))
119}
120
121fn l1_headers(
122    address: &str,
123    signature: &str,
124    timestamp: &str,
125    nonce: u64,
126) -> HashMap<String, String> {
127    HashMap::from([
128        ("POLY_ADDRESS".to_string(), address.to_string()),
129        ("POLY_SIGNATURE".to_string(), signature.to_string()),
130        ("POLY_TIMESTAMP".to_string(), timestamp.to_string()),
131        ("POLY_NONCE".to_string(), nonce.to_string()),
132    ])
133}
134
135#[cfg(test)]
136mod tests {
137    use rstest::rstest;
138
139    use super::*;
140
141    #[rstest]
142    fn test_api_credentials_zeroize_and_redact_debug() {
143        fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
144
145        let mut credentials = ApiCredentials {
146            api_key: SecretString::from("api-key-sentinel"),
147            secret: SecretString::from("secret-sentinel"),
148            passphrase: SecretString::from("passphrase-sentinel"),
149        };
150
151        let debug = format!("{credentials:?}");
152        credentials.zeroize();
153
154        assert_zeroize_on_drop::<ApiCredentials>();
155        assert!(!debug.contains("api-key-sentinel"));
156        assert!(!debug.contains("secret-sentinel"));
157        assert!(!debug.contains("passphrase-sentinel"));
158        assert_eq!(credentials.api_key.expose_secret(), "");
159        assert_eq!(credentials.secret.expose_secret(), "");
160        assert_eq!(credentials.passphrase.expose_secret(), "");
161    }
162}