polymarket 0.1.0

Rust SDK for Polymarket prediction market - CLOB trading, on-chain operations, and WebSocket streaming
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
516
517
518
519
520
521
522
523
524
525
526
//! Proxy wallet transaction execution
//!
//! For proxy wallets, all transactions must go through the Proxy Factory contract.

use alloy::primitives::{Address, Bytes, U256};
use alloy::signers::Signer;
use alloy::sol_types::{SolCall, SolValue};

use crate::onchain::{
    contracts::{IConditionalTokens, IProxyFactory},
    wallet::OnchainClient,
    OnchainError, Result, TransactionOptions,
};
use crate::relayer::{RelayerClient, RelayerSubmitRequest, SignatureParams};

impl OnchainClient {
    /// Execute a transaction through the Proxy Factory
    ///
    /// This method is used for proxy wallets to execute transactions.
    /// The transaction is encoded and sent through the Proxy Factory's `proxy()` function.
    ///
    /// # Arguments
    /// * `to` - Target contract address
    /// * `data` - Encoded call data
    /// * `value` - ETH value to send (usually 0 for token operations)
    /// * `options` - Transaction options (gas, confirmations, etc.)
    ///
    /// # Returns
    /// Transaction hash
    ///
    /// # Example
    /// ```no_run
    /// # use polymarket_sdk::onchain::OnchainClientBuilder;
    /// # use alloy::primitives::{Address, Bytes, U256};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = OnchainClientBuilder::new()
    ///     .mainnet()
    ///     .proxy_wallet("0x1234...", "0xABCD...".parse()?)?
    ///     .build()?;
    ///
    /// let target: Address = "0x...".parse()?;
    /// let data = Bytes::from(vec![/* encoded call data */]);
    /// let tx_hash = client.execute_via_proxy(target, data, U256::ZERO, None).await?;
    /// println!("Transaction: {:?}", tx_hash);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute_via_proxy(
        &self,
        to: Address,
        data: Bytes,
        value: U256,
        options: Option<TransactionOptions>,
    ) -> Result<alloy::primitives::TxHash> {
        // Verify this is a proxy wallet
        if !self.is_smart_wallet() {
            return Err(OnchainError::ProxyError(
                "execute_via_proxy can only be used with proxy wallets".to_string(),
            ));
        }

        // Get proxy factory address
        let proxy_factory_address = self.proxy_factory_address();

        // Build the ProxyTransaction struct
        // Note: The typeCode determines the execution mode:
        // - 0: CALL
        // - 1: DELEGATECALL
        // For CTF operations, we use DELEGATECALL (typeCode = 1)
        let proxy_txn = IProxyFactory::ProxyTransaction {
            typeCode: 1, // DELEGATECALL
            to,
            value,
            data,
        };

        // Get the shared wallet provider with built-in nonce management
        // This provider is created once and reused, so the CachedNonceManager
        // maintains state across multiple transactions
        let provider = self.wallet_provider().await?;

        // Create Proxy Factory contract instance
        let factory = IProxyFactory::new(proxy_factory_address, provider);

        // Build the call with all transaction parameters explicitly
        // Note: We don't set nonce manually - Alloy's CachedNonceManager handles it
        let gas_limit = options.as_ref()
            .and_then(|o| o.gas_limit)
            .map(|g| g.to::<u64>())
            .unwrap_or(500_000);

        // Fetch current gas price from the network (dynamic pricing)
        // Add 20% buffer to ensure transaction is processed quickly and can replace pending txs
        let base_gas_price = self.get_gas_price().await?;
        let gas_price = (base_gas_price * U256::from(120)) / U256::from(100); // +20% buffer

        let call = factory.proxy(vec![proxy_txn])
            .chain_id(self.network().chain_id)
            .gas(gas_limit)
            .gas_price(gas_price.to::<u128>());

        // Send the transaction
        // The shared CachedNonceManager automatically assigns sequential nonces
        let pending = call
            .send()
            .await
            .map_err(|e| OnchainError::TransactionFailed(format!("Failed to send proxy transaction: {}", e)))?;

        // Wait for confirmation if requested
        let tx_hash = if options.as_ref().map(|o| o.wait_for_confirmation).unwrap_or(false) {
            let confirmations = options.as_ref()
                .and_then(|o| o.confirmations)
                .unwrap_or(1);

            let timeout = options.as_ref()
                .and_then(|o| o.timeout)
                .unwrap_or(std::time::Duration::from_secs(300)); // 5 min default

            let receipt = pending
                .with_required_confirmations(confirmations)
                .with_timeout(Some(timeout)) // Alloy's built-in timeout
                .get_receipt()
                .await
                .map_err(|e| {
                    OnchainError::TransactionFailed(format!("Failed to confirm proxy transaction: {}", e))
                })?;

            receipt.transaction_hash
        } else {
            *pending.tx_hash()
        };

        Ok(tx_hash)
    }

    /// Redeem positions via proxy wallet
    ///
    /// This is a specialized version of redeem_positions that works with proxy wallets.
    /// It bypasses the balance check and executes redemption directly through the proxy factory.
    ///
    /// # Arguments
    /// * `condition_id` - The condition ID for the resolved market
    /// * `options` - Transaction options
    ///
    /// # Returns
    /// Transaction hash
    ///
    /// # Example
    /// ```no_run
    /// # use polymarket_sdk::onchain::OnchainClientBuilder;
    /// # use alloy::primitives::FixedBytes;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = OnchainClientBuilder::new()
    ///     .mainnet()
    ///     .proxy_wallet("0x1234...", "0xABCD...".parse()?)?
    ///     .build()?;
    ///
    /// let condition_id = FixedBytes::from([0u8; 32]);
    /// let tx_hash = client.redeem_via_proxy(condition_id, None).await?;
    /// println!("Redemption transaction: {:?}", tx_hash);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn redeem_via_proxy(
        &self,
        condition_id: alloy::primitives::FixedBytes<32>,
        options: Option<TransactionOptions>,
    ) -> Result<alloy::primitives::TxHash> {
        // Verify this is a proxy wallet
        if !self.is_smart_wallet() {
            return Err(OnchainError::ProxyError(
                "redeem_via_proxy can only be used with proxy wallets".to_string(),
            ));
        }

        // USDC.e address (Polymarket's collateral token)
        let collateral_token = self.usdc_address();

        // Parent collection ID is null (zero) for Polymarket
        let parent_collection_id = alloy::primitives::FixedBytes::<32>::ZERO;

        // Index sets: [1, 2] represents both outcomes (YES/NO or UP/DOWN)
        let index_sets = vec![U256::from(1), U256::from(2)];

        // Encode the CTF redeemPositions call using the imported interface
        let redeem_call = IConditionalTokens::redeemPositionsCall {
            collateralToken: collateral_token,
            parentCollectionId: parent_collection_id,
            conditionId: condition_id,
            indexSets: index_sets,
        };

        let call_data = Bytes::from(redeem_call.abi_encode());

        // Execute through proxy factory
        self.execute_via_proxy(self.ctf_address(), call_data, U256::ZERO, options)
            .await
    }

    /// Split USDC into outcome tokens via proxy wallet
    ///
    /// This is a specialized version of split_position that works with proxy wallets.
    /// It executes the split operation directly through the proxy factory.
    ///
    /// # Arguments
    /// * `condition_id` - The condition ID for the market
    /// * `amount` - Amount of USDC to split (in wei, 6 decimals)
    /// * `options` - Transaction options
    ///
    /// # Returns
    /// Transaction hash and position IDs (YES, NO)
    ///
    /// # Example
    /// ```no_run
    /// # use polymarket_sdk::onchain::OnchainClientBuilder;
    /// # use alloy::primitives::{FixedBytes, U256};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = OnchainClientBuilder::new()
    ///     .mainnet()
    ///     .proxy_wallet("0x1234...", "0xABCD...".parse()?)?
    ///     .build()?;
    ///
    /// let condition_id = FixedBytes::from([0u8; 32]);
    /// let amount = U256::from(100_000_000); // 100 USDC
    /// let tx_hash = client.split_via_proxy(condition_id, amount, None).await?;
    /// println!("Split transaction: {:?}", tx_hash);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Note
    /// This function returns only the transaction hash. To get the token IDs for the split positions,
    /// use the Gamma API (`TradingMarket.token_ids`), as calculating position IDs requires complex
    /// elliptic curve operations on the BN128 curve that are difficult to implement correctly in Rust.
    pub async fn split_via_proxy(
        &self,
        condition_id: alloy::primitives::FixedBytes<32>,
        amount: U256,
        options: Option<TransactionOptions>,
    ) -> Result<alloy::primitives::TxHash> {
        // Verify this is a proxy wallet
        if !self.is_smart_wallet() {
            return Err(OnchainError::ProxyError(
                "split_via_proxy can only be used with proxy wallets".to_string(),
            ));
        }

        // USDC.e address (Polymarket's collateral token)
        let collateral_token = self.usdc_address();

        // Parent collection ID is null (zero) for Polymarket
        let parent_collection_id = alloy::primitives::FixedBytes::<32>::ZERO;

        // Partition: [1, 2] represents binary outcomes (YES/NO or UP/DOWN)
        let partition = vec![U256::from(1), U256::from(2)];

        // Encode the CTF splitPosition call using the imported interface
        let split_call = IConditionalTokens::splitPositionCall {
            collateralToken: collateral_token,
            parentCollectionId: parent_collection_id,
            conditionId: condition_id,
            partition,
            amount,
        };

        let call_data = Bytes::from(split_call.abi_encode());

        // Execute through proxy factory
        let tx_hash = self.execute_via_proxy(self.ctf_address(), call_data, U256::ZERO, options)
            .await?;

        Ok(tx_hash)
    }

    /// Merge positions via proxy wallet
    ///
    /// Merges outcome tokens back into collateral using the proxy wallet.
    ///
    /// # Arguments
    /// * `condition_id` - The condition ID for the market
    /// * `amount` - Amount to merge (in wei, 6 decimals for USDC)
    /// * `options` - Optional transaction options
    ///
    /// # Returns
    /// Transaction hash
    pub async fn merge_via_proxy(
        &self,
        condition_id: alloy::primitives::FixedBytes<32>,
        amount: U256,
        options: Option<TransactionOptions>,
    ) -> Result<alloy::primitives::TxHash> {
        // Verify this is a proxy wallet
        if !self.is_smart_wallet() {
            return Err(OnchainError::ProxyError(
                "merge_via_proxy can only be used with proxy wallets".to_string(),
            ));
        }

        // USDC.e address (Polymarket's collateral token)
        let collateral_token = self.usdc_address();

        // Parent collection ID is null (zero) for Polymarket
        let parent_collection_id = alloy::primitives::FixedBytes::<32>::ZERO;

        // Partition: [1, 2] represents binary outcomes (YES/NO or UP/DOWN)
        let partition = vec![U256::from(1), U256::from(2)];

        // Encode the CTF mergePositions call using the imported interface
        let merge_call = IConditionalTokens::mergePositionsCall {
            collateralToken: collateral_token,
            parentCollectionId: parent_collection_id,
            conditionId: condition_id,
            partition,
            amount,
        };

        let call_data = Bytes::from(merge_call.abi_encode());

        // Execute through proxy factory
        let tx_hash = self.execute_via_proxy(self.ctf_address(), call_data, U256::ZERO, options)
            .await?;

        Ok(tx_hash)
    }

    /// Redeem positions via proxy wallet using the Polymarket relayer (gasless)
    ///
    /// This method uses Polymarket's relayer service to submit the transaction without
    /// requiring the user to pay gas fees. The relayer pays the gas and submits the transaction.
    ///
    /// # Arguments
    /// * `condition_id` - The condition ID for the resolved market
    /// * `relayer_url` - Optional custom relayer URL (defaults to mainnet relayer)
    ///
    /// # Returns
    /// Transaction hash
    ///
    /// # Example
    /// ```no_run
    /// # use polymarket_sdk::onchain::OnchainClientBuilder;
    /// # use alloy::primitives::FixedBytes;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = OnchainClientBuilder::new()
    ///     .mainnet()
    ///     .proxy_wallet("0x1234...", "0xABCD...".parse()?)?
    ///     .build()?;
    ///
    /// let condition_id = FixedBytes::from([0u8; 32]);
    /// let tx_hash = client.redeem_via_relayer(condition_id, None).await?;
    /// println!("Redemption transaction: {:?}", tx_hash);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn redeem_via_relayer(
        &self,
        condition_id: alloy::primitives::FixedBytes<32>,
        relayer_url: Option<String>,
    ) -> Result<alloy::primitives::TxHash> {
        // Verify this is a proxy wallet
        if !self.is_smart_wallet() {
            return Err(OnchainError::ProxyError(
                "redeem_via_relayer can only be used with proxy wallets".to_string(),
            ));
        }

        let proxy_wallet_address = self.address();
        let eoa_address = self.signer_address();

        // Create relayer client
        let relayer = if let Some(url) = relayer_url {
            RelayerClient::new(url)
        } else {
            RelayerClient::mainnet()
        };

        // Step 1: Get relay payload (relayer address and nonce)
        let relay_payload = relayer
            .get_relay_payload(&format!("{:?}", proxy_wallet_address), "PROXY")
            .await
            .map_err(|e| OnchainError::TransactionFailed(format!("Failed to get relay payload: {}", e)))?;

        // Step 2: Build the redemption call data using the imported interface
        let collateral_token = self.usdc_address();
        let parent_collection_id = alloy::primitives::FixedBytes::<32>::ZERO;
        let index_sets = vec![U256::from(1), U256::from(2)];

        let redeem_call = IConditionalTokens::redeemPositionsCall {
            collateralToken: collateral_token,
            parentCollectionId: parent_collection_id,
            conditionId: condition_id,
            indexSets: index_sets,
        };

        let redeem_data = Bytes::from(redeem_call.abi_encode());

        // Step 3: Build the ProxyTransaction
        let proxy_txn = IProxyFactory::ProxyTransaction {
            typeCode: 1, // DELEGATECALL
            to: self.ctf_address(),
            value: U256::ZERO,
            data: redeem_data,
        };

        // Encode the proxy() call using the ProxyTransaction array
        let proxy_call_data = alloy::primitives::Bytes::from(vec![proxy_txn].abi_encode());

        // The actual encoded data starts after the function selector
        let function_selector = alloy::primitives::FixedBytes::<4>::from([0x34, 0xee, 0x97, 0x91]); // proxy() selector
        let full_data = [function_selector.as_slice(), proxy_call_data.as_ref()].concat();

        // Step 4: Create the message to sign
        // The message format is: hash of the transaction parameters
        let message = alloy::primitives::keccak256(
            [
                proxy_wallet_address.as_slice(),
                self.proxy_factory_address().as_slice(),
                relay_payload.nonce.as_bytes(),
                full_data.as_slice(),
            ].concat()
        );

        // Create hex string for the data (after using full_data in the message)
        let data_hex = format!("0x{}", hex::encode(&full_data));

        // Sign the message
        let signer = self.signer().private_key_signer();
        let signature = signer
            .sign_message(message.as_slice())
            .await
            .map_err(|e| OnchainError::SignerError(format!("Failed to sign message: {}", e)))?;

        let signature_hex = format!("0x{}", hex::encode(signature.as_bytes()));

        // Step 5: Submit to relayer
        let submit_request = RelayerSubmitRequest {
            from: format!("{:?}", eoa_address),
            to: format!("{:?}", self.proxy_factory_address()),
            proxy_wallet: format!("{:?}", proxy_wallet_address),
            data: data_hex,
            nonce: relay_payload.nonce.clone(),
            signature: signature_hex,
            signature_params: SignatureParams {
                gas_price: "0".to_string(),
                gas_limit: "161135".to_string(), // From your captured request
                relayer_fee: "0".to_string(),
                relay_hub: "0xD216153c06E857cD7f72665E0aF1d7D82172F494".to_string(),
                relay: relay_payload.address,
            },
            tx_type: "PROXY".to_string(),
            metadata: String::new(),
        };

        let submit_response = relayer
            .submit(submit_request)
            .await
            .map_err(|e| OnchainError::TransactionFailed(format!("Failed to submit to relayer: {}", e)))?;

        // Step 6: Wait for execution
        let tx = relayer
            .wait_for_execution(&submit_response.transaction_id, Some(60), Some(1000))
            .await
            .map_err(|e| OnchainError::TransactionFailed(format!("Transaction execution failed: {}", e)))?;

        // Parse transaction hash
        let tx_hash = tx.transaction_hash
            .parse()
            .map_err(|e| OnchainError::TransactionFailed(format!("Invalid transaction hash: {:?}", e)))?;

        Ok(tx_hash)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::onchain::{NetworkConfig, OnchainProvider, OnchainSigner};
    use alloy::network::AnyNetwork;
    use alloy::providers::{ProviderBuilder, Provider};

    const TEST_PRIVATE_KEY: &str =
        "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    #[test]
    fn test_proxy_methods_exist() {
        let network = NetworkConfig::polygon_mainnet();
        let provider = OnchainProvider {
            provider: ProviderBuilder::new()
                .network::<AnyNetwork>()
                .connect_http(network.rpc_url.parse().unwrap())
                .erased(),
            network: network.clone(),
        };

        let proxy_address = Address::repeat_byte(0x42);
        let signer = OnchainSigner::from_proxy(TEST_PRIVATE_KEY, proxy_address).unwrap();

        let client = OnchainClient::new(provider, signer);

        // Verify this is a smart wallet
        assert!(client.is_smart_wallet());
        assert_eq!(client.proxy_address(), Some(proxy_address));
    }

    #[test]
    fn test_direct_wallet_cannot_use_proxy_methods() {
        let network = NetworkConfig::polygon_mainnet();
        let provider = OnchainProvider {
            provider: ProviderBuilder::new()
                .network::<AnyNetwork>()
                .connect_http(network.rpc_url.parse().unwrap())
                .erased(),
            network: network.clone(),
        };

        let signer = OnchainSigner::from_private_key(TEST_PRIVATE_KEY).unwrap();
        let client = OnchainClient::new(provider, signer);

        // Verify this is NOT a smart wallet
        assert!(!client.is_smart_wallet());
        assert_eq!(client.proxy_address(), None);
    }
}