polyoxide-relay 0.22.0

Rust client library for Polymarket Relayer API
Documentation
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use crate::config::{AuthConfig, BuilderConfig, RelayerApiKeyConfig};
use crate::error::RelayError;
use alloy::primitives::Address;
use alloy::signers::local::PrivateKeySigner;

/// Keychain service name for Relay credentials.
#[cfg(feature = "keychain")]
pub const KEYCHAIN_SERVICE: &str = "polyoxide-relay";

/// Account credentials for authenticated relay operations.
///
/// Combines a private key signer (for EIP-712 transaction signing) with an optional
/// [`AuthConfig`] for relay submission. Two authentication schemes are supported:
/// [`AuthConfig::Builder`] (HMAC-signed builder API credentials) and
/// [`AuthConfig::RelayerApiKey`] (static relayer API key headers). The `Debug`
/// implementation redacts the private key to prevent accidental leakage in logs.
#[derive(Clone)]
pub struct BuilderAccount {
    pub(crate) signer: PrivateKeySigner,
    pub(crate) config: Option<AuthConfig>,
}

fn parse_signer(private_key: impl Into<String>) -> Result<PrivateKeySigner, RelayError> {
    private_key
        .into()
        .parse::<PrivateKeySigner>()
        .map_err(|e| RelayError::Signer(format!("Failed to parse private key: {}", e)))
}

impl std::fmt::Debug for BuilderAccount {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuilderAccount")
            .field("address", &self.signer.address())
            .field("config", &self.config)
            .finish()
    }
}

impl BuilderAccount {
    /// Create a new account from a hex-encoded private key and optional builder config.
    ///
    /// Wraps the `BuilderConfig` in [`AuthConfig::Builder`] internally.
    /// Accepts keys with or without a `0x` prefix.
    pub fn new(
        private_key: impl Into<String>,
        config: Option<BuilderConfig>,
    ) -> Result<Self, RelayError> {
        let signer = parse_signer(private_key)?;
        Ok(Self {
            signer,
            config: config.map(AuthConfig::Builder),
        })
    }

    /// Create a new account from a hex-encoded private key and relayer API key credentials.
    pub fn with_relayer_api_key(
        private_key: impl Into<String>,
        key: String,
        address: String,
    ) -> Result<Self, RelayError> {
        let signer = parse_signer(private_key)?;
        let relayer = RelayerApiKeyConfig::new(key, address)?;
        Ok(Self {
            signer,
            config: Some(AuthConfig::RelayerApiKey(relayer)),
        })
    }

    /// Create a new account from a hex-encoded private key and a pre-built [`AuthConfig`].
    pub fn with_auth_config(
        private_key: impl Into<String>,
        config: Option<AuthConfig>,
    ) -> Result<Self, RelayError> {
        let signer = parse_signer(private_key)?;
        Ok(Self { signer, config })
    }

    /// Returns the Ethereum address derived from the private key.
    pub fn address(&self) -> Address {
        self.signer.address()
    }

    /// Returns a reference to the underlying private key signer.
    pub fn signer(&self) -> &PrivateKeySigner {
        &self.signer
    }

    /// Returns the auth config, if one was provided.
    pub fn auth_config(&self) -> Option<&AuthConfig> {
        self.config.as_ref()
    }

    /// Load account from the OS keychain with builder API credentials.
    ///
    /// Reads from the `polyoxide-relay` keychain service:
    /// - `private_key`: Hex-encoded private key (required)
    /// - `api_key`, `api_secret`: Builder API credentials (optional — if `api_key` is
    ///   not found, the account is created without auth config)
    /// - `passphrase`: Builder API passphrase (optional)
    #[cfg(feature = "keychain")]
    pub fn from_keychain() -> Result<Self, RelayError> {
        Self::from_keychain_in_service(KEYCHAIN_SERVICE)
    }

    /// Implementation of [`BuilderAccount::from_keychain`] parameterized by
    /// service name. Tests pass an isolated service so they never read the real
    /// `polyoxide-relay` entries.
    #[cfg(feature = "keychain")]
    fn from_keychain_in_service(service: &str) -> Result<Self, RelayError> {
        use polyoxide_core::keychain;

        let private_key = keychain::get(service, "private_key")
            .map_err(|e| RelayError::Api(format!("Keychain error for private_key: {e}")))?;

        let config = match keychain::get(service, "api_key") {
            Ok(key) => {
                let secret = keychain::get(service, "api_secret")
                    .map_err(|e| RelayError::Api(format!("Keychain error for api_secret: {e}")))?;
                let passphrase = keychain::get(service, "passphrase").ok();
                Some(BuilderConfig::new(key, secret, passphrase))
            }
            Err(polyoxide_core::KeychainError::NotFound { .. }) => None,
            Err(e) => return Err(RelayError::Api(format!("Keychain error: {e}"))),
        };

        Self::new(private_key, config)
    }

    /// Load account from the OS keychain with relayer API key credentials.
    ///
    /// Reads from the `polyoxide-relay` keychain service:
    /// - `private_key`: Hex-encoded private key
    /// - `relayer_api_key`: Static relayer API key
    /// - `relayer_api_key_address`: On-chain address for the relayer API key
    #[cfg(feature = "keychain")]
    pub fn from_keychain_relayer_api_key() -> Result<Self, RelayError> {
        Self::from_keychain_relayer_api_key_in_service(KEYCHAIN_SERVICE)
    }

    /// Implementation of [`BuilderAccount::from_keychain_relayer_api_key`]
    /// parameterized by service name. Tests pass an isolated service so they
    /// never read the real `polyoxide-relay` entries.
    #[cfg(feature = "keychain")]
    fn from_keychain_relayer_api_key_in_service(service: &str) -> Result<Self, RelayError> {
        use polyoxide_core::keychain;

        let private_key = keychain::get(service, "private_key")
            .map_err(|e| RelayError::Api(format!("Keychain error for private_key: {e}")))?;
        let key = keychain::get(service, "relayer_api_key")
            .map_err(|e| RelayError::Api(format!("Keychain error for relayer_api_key: {e}")))?;
        let address = keychain::get(service, "relayer_api_key_address").map_err(|e| {
            RelayError::Api(format!("Keychain error for relayer_api_key_address: {e}"))
        })?;

        Self::with_relayer_api_key(private_key, key, address)
    }

    /// Delete all credentials from the OS keychain for this service.
    #[cfg(feature = "keychain")]
    pub fn delete_from_keychain() -> Result<(), RelayError> {
        Self::delete_from_keychain_in_service(KEYCHAIN_SERVICE)
    }

    /// Implementation of [`BuilderAccount::delete_from_keychain`] parameterized
    /// by service name. Tests pass an isolated service so they never delete the
    /// real `polyoxide-relay` entries.
    #[cfg(feature = "keychain")]
    fn delete_from_keychain_in_service(service: &str) -> Result<(), RelayError> {
        use polyoxide_core::keychain;

        for key in [
            "private_key",
            "api_key",
            "api_secret",
            "passphrase",
            "relayer_api_key",
            "relayer_api_key_address",
        ] {
            keychain::delete(service, key)
                .map_err(|e| RelayError::Api(format!("Keychain error: {e}")))?;
        }
        Ok(())
    }
}

/// Save a private key to the OS keychain under the `polyoxide-relay` service.
#[cfg(feature = "keychain")]
pub fn save_private_key_to_keychain(private_key: &str) -> Result<(), RelayError> {
    save_private_key_to_keychain_in_service(KEYCHAIN_SERVICE, private_key)
}

/// Implementation of [`save_private_key_to_keychain`] parameterized by service
/// name. Tests pass an isolated service so they never overwrite the real
/// `polyoxide-relay` private key.
#[cfg(feature = "keychain")]
fn save_private_key_to_keychain_in_service(
    service: &str,
    private_key: &str,
) -> Result<(), RelayError> {
    polyoxide_core::keychain::set(service, "private_key", private_key)
        .map_err(|e| RelayError::Api(format!("Keychain error: {e}")))?;
    Ok(())
}

/// Save builder API credentials to the OS keychain under the `polyoxide-relay` service.
///
/// When `config.passphrase` is `None`, any previously stored passphrase is deleted
/// to prevent stale values from persisting.
#[cfg(feature = "keychain")]
pub fn save_builder_config_to_keychain(config: &BuilderConfig) -> Result<(), RelayError> {
    save_builder_config_to_keychain_in_service(KEYCHAIN_SERVICE, config)
}

/// Implementation of [`save_builder_config_to_keychain`] parameterized by
/// service name. Tests pass an isolated service so they never overwrite the
/// real `polyoxide-relay` entries.
#[cfg(feature = "keychain")]
fn save_builder_config_to_keychain_in_service(
    service: &str,
    config: &BuilderConfig,
) -> Result<(), RelayError> {
    use polyoxide_core::keychain;

    keychain::set(service, "api_key", &config.key)
        .map_err(|e| RelayError::Api(format!("Keychain error: {e}")))?;
    keychain::set(service, "api_secret", &config.secret)
        .map_err(|e| RelayError::Api(format!("Keychain error: {e}")))?;
    match &config.passphrase {
        Some(passphrase) => {
            keychain::set(service, "passphrase", passphrase)
                .map_err(|e| RelayError::Api(format!("Keychain error: {e}")))?;
        }
        None => {
            keychain::delete(service, "passphrase")
                .map_err(|e| RelayError::Api(format!("Keychain error: {e}")))?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AuthConfig;

    // A well-known test private key (DO NOT use for real funds)
    // Address: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 (anvil/hardhat default #0)
    const TEST_PRIVATE_KEY: &str =
        "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

    #[test]
    fn test_new_valid_private_key() {
        let account = BuilderAccount::new(TEST_PRIVATE_KEY, None);
        assert!(account.is_ok());
    }

    #[test]
    fn test_new_with_0x_prefix() {
        let key = format!("0x{}", TEST_PRIVATE_KEY);
        let account = BuilderAccount::new(key, None);
        // alloy accepts 0x-prefixed keys
        assert!(account.is_ok());
    }

    #[test]
    fn test_new_invalid_private_key() {
        let result = BuilderAccount::new("not_a_valid_key", None);
        assert!(result.is_err());
        let err = result.unwrap_err();
        match err {
            RelayError::Signer(msg) => {
                assert!(
                    msg.contains("Failed to parse private key"),
                    "unexpected: {msg}"
                );
            }
            other => panic!("Expected Signer error, got: {other:?}"),
        }
    }

    #[test]
    fn test_new_empty_key() {
        let result = BuilderAccount::new("", None);
        assert!(result.is_err());
    }

    #[test]
    fn test_address_derivation_deterministic() {
        let a1 = BuilderAccount::new(TEST_PRIVATE_KEY, None).unwrap();
        let a2 = BuilderAccount::new(TEST_PRIVATE_KEY, None).unwrap();
        assert_eq!(a1.address(), a2.address());
    }

    #[test]
    fn test_address_matches_known_value() {
        // The first anvil/hardhat default account
        let account = BuilderAccount::new(TEST_PRIVATE_KEY, None).unwrap();
        let expected: Address = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
            .parse()
            .unwrap();
        assert_eq!(account.address(), expected);
    }

    #[test]
    fn test_debug_redacts_private_key() {
        let account = BuilderAccount::new(TEST_PRIVATE_KEY, None).unwrap();
        let debug_output = format!("{:?}", account);
        assert!(
            debug_output.contains("address"),
            "Debug should show address, got: {debug_output}"
        );
        assert!(
            !debug_output.contains(TEST_PRIVATE_KEY),
            "Debug should not contain the private key, got: {debug_output}"
        );
    }

    #[test]
    fn test_config_none() {
        let account = BuilderAccount::new(TEST_PRIVATE_KEY, None).unwrap();
        assert!(account.auth_config().is_none());
    }

    #[test]
    fn test_config_some() {
        let config = BuilderConfig::new("key".into(), "secret".into(), None);
        let account = BuilderAccount::new(TEST_PRIVATE_KEY, Some(config)).unwrap();
        assert!(account.auth_config().is_some());
    }

    #[test]
    fn test_with_relayer_api_key() {
        let account = BuilderAccount::with_relayer_api_key(
            TEST_PRIVATE_KEY,
            "my-key".to_string(),
            "0xaddr".to_string(),
        )
        .unwrap();
        assert!(account.auth_config().is_some());
        assert!(matches!(
            account.auth_config(),
            Some(AuthConfig::RelayerApiKey(_))
        ));
    }

    #[test]
    fn test_new_wraps_builder_config_in_auth_config() {
        let config = BuilderConfig::new("key".into(), "secret".into(), None);
        let account = BuilderAccount::new(TEST_PRIVATE_KEY, Some(config)).unwrap();
        assert!(matches!(
            account.auth_config(),
            Some(AuthConfig::Builder(_))
        ));
    }

    #[test]
    fn test_with_auth_config_none() {
        let account = BuilderAccount::with_auth_config(TEST_PRIVATE_KEY, None).unwrap();
        assert!(account.auth_config().is_none());
    }

    #[test]
    fn test_with_auth_config_relayer_api_key_variant() {
        let relayer =
            crate::config::RelayerApiKeyConfig::new("rk".into(), "0xaddr".into()).unwrap();
        let auth = AuthConfig::RelayerApiKey(relayer);
        let account = BuilderAccount::with_auth_config(TEST_PRIVATE_KEY, Some(auth)).unwrap();
        assert!(matches!(
            account.auth_config(),
            Some(AuthConfig::RelayerApiKey(_))
        ));
    }

    #[cfg(feature = "keychain")]
    mod keychain_tests {
        use super::*;

        const TEST_PRIVATE_KEY: &str =
            "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

        // Each test uses its OWN isolated keychain service (never the real
        // `polyoxide-relay` service), so it can neither read, overwrite, nor
        // delete a developer's stored credentials. Because no two tests share a
        // service, they also can't clobber each other's entries — making them
        // safe to run concurrently without serialization.
        #[test]
        #[ignore] // Requires OS keychain daemon
        fn builder_account_keychain_roundtrip() {
            const SERVICE: &str = "polyoxide-relay-test-builder-roundtrip";

            save_private_key_to_keychain_in_service(SERVICE, TEST_PRIVATE_KEY).unwrap();
            let config = BuilderConfig::new("rk".into(), "rs".into(), Some("rp".into()));
            save_builder_config_to_keychain_in_service(SERVICE, &config).unwrap();

            let account = BuilderAccount::from_keychain_in_service(SERVICE).unwrap();
            assert_eq!(
                account.address(),
                BuilderAccount::new(TEST_PRIVATE_KEY, None)
                    .unwrap()
                    .address()
            );
            assert!(account.auth_config().is_some());

            // Cleanup
            BuilderAccount::delete_from_keychain_in_service(SERVICE).unwrap();
        }

        #[test]
        #[ignore] // Requires OS keychain daemon
        fn builder_account_keychain_no_config() {
            use polyoxide_core::keychain;
            const SERVICE: &str = "polyoxide-relay-test-no-config";

            // Clear any leftover builder config entries so from_keychain()
            // exercises the "no api_key found" path.
            let _ = keychain::delete(SERVICE, "api_key");
            let _ = keychain::delete(SERVICE, "api_secret");
            let _ = keychain::delete(SERVICE, "passphrase");

            save_private_key_to_keychain_in_service(SERVICE, TEST_PRIVATE_KEY).unwrap();

            let account = BuilderAccount::from_keychain_in_service(SERVICE).unwrap();
            assert!(
                account.auth_config().is_none(),
                "Expected no auth config when api_key is absent"
            );

            // Cleanup
            let _ = keychain::delete(SERVICE, "private_key");
        }

        #[test]
        #[ignore] // Requires OS keychain daemon
        fn save_builder_config_none_passphrase_clears_stale() {
            use polyoxide_core::keychain;
            const SERVICE: &str = "polyoxide-relay-test-clears-stale";

            // Store config WITH passphrase
            save_private_key_to_keychain_in_service(SERVICE, TEST_PRIVATE_KEY).unwrap();
            let config_with = BuilderConfig::new("k".into(), "s".into(), Some("pp".into()));
            save_builder_config_to_keychain_in_service(SERVICE, &config_with).unwrap();

            // Verify passphrase is present
            assert!(keychain::get(SERVICE, "passphrase").is_ok());

            // Overwrite with None passphrase — should delete the stale entry
            let config_without = BuilderConfig::new("k".into(), "s".into(), None);
            save_builder_config_to_keychain_in_service(SERVICE, &config_without).unwrap();

            // Verify passphrase has been removed
            let result = keychain::get(SERVICE, "passphrase");
            assert!(
                matches!(result, Err(polyoxide_core::KeychainError::NotFound { .. })),
                "Expected passphrase to be deleted, got: {result:?}"
            );

            // And from_keychain should load account without passphrase in config
            let account = BuilderAccount::from_keychain_in_service(SERVICE).unwrap();
            if let Some(AuthConfig::Builder(bc)) = account.auth_config() {
                assert!(
                    bc.passphrase.is_none(),
                    "Expected passphrase=None after clearing"
                );
            } else {
                panic!("Expected Builder auth config");
            }

            // Cleanup
            BuilderAccount::delete_from_keychain_in_service(SERVICE).unwrap();
        }

        #[test]
        #[ignore] // Requires OS keychain daemon
        fn relayer_api_key_keychain_roundtrip() {
            use polyoxide_core::keychain;
            const SERVICE: &str = "polyoxide-relay-test-relayer-key";

            // Store relayer API key credentials
            save_private_key_to_keychain_in_service(SERVICE, TEST_PRIVATE_KEY).unwrap();
            keychain::set(SERVICE, "relayer_api_key", "test-rk").unwrap();
            keychain::set(SERVICE, "relayer_api_key_address", "0xaddr").unwrap();

            let account =
                BuilderAccount::from_keychain_relayer_api_key_in_service(SERVICE).unwrap();
            assert_eq!(
                account.address(),
                BuilderAccount::new(TEST_PRIVATE_KEY, None)
                    .unwrap()
                    .address()
            );
            assert!(matches!(
                account.auth_config(),
                Some(AuthConfig::RelayerApiKey(_))
            ));

            // Cleanup
            BuilderAccount::delete_from_keychain_in_service(SERVICE).unwrap();
        }
    }

    #[test]
    fn test_with_auth_config_invalid_private_key() {
        let result = BuilderAccount::with_auth_config("not_a_valid_key", None);
        assert!(result.is_err());
        match result.unwrap_err() {
            RelayError::Signer(msg) => {
                assert!(
                    msg.contains("Failed to parse private key"),
                    "unexpected: {msg}"
                );
            }
            other => panic!("Expected Signer error, got: {other:?}"),
        }
    }
}