rs-builder-relayer-client 0.1.0

A Rust SDK for Polymarket's Builder Relayer — gasless on-chain operations
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
use crate::auth::AuthMethod;
use crate::builder::{create, derive, proxy, safe};
use crate::contracts;
use crate::error::{RelayerError, Result};
use crate::types::*;
use ethers::signers::{LocalWallet, Signer};
use reqwest::Client;
use std::sync::Arc;
use tokio::time::{sleep, Duration};
use tracing::{debug, info};

const DEFAULT_GAS_LIMIT: u64 = 10_000_000;
const POLL_INTERVAL: Duration = Duration::from_secs(2);
const MAX_POLL_ATTEMPTS: u32 = 100;

/// Client for interacting with the Polymarket Builder Relayer.
#[derive(Clone)]
pub struct RelayClient {
    http: Client,
    base_url: String,
    chain_id: u64,
    signer: Arc<LocalWallet>,
    auth: AuthMethod,
    tx_type: RelayerTxType,
}

impl RelayClient {
    /// Create a new RelayClient.
    ///
    /// # Arguments
    /// * `chain_id` - Chain ID (137 for Polygon mainnet)
    /// * `signer` - Ethers LocalWallet for signing transactions
    /// * `auth` - Authentication method (Builder or RelayerKey)
    /// * `tx_type` - Wallet type (Safe or Proxy)
    pub async fn new(
        chain_id: u64,
        signer: LocalWallet,
        auth: AuthMethod,
        tx_type: RelayerTxType,
    ) -> Result<Self> {
        let http = Client::builder()
            .timeout(Duration::from_secs(30))
            .build()?;

        Ok(Self {
            http,
            base_url: contracts::RELAYER_URL.trim_end_matches('/').to_string(),
            chain_id,
            signer: Arc::new(signer),
            auth,
            tx_type,
        })
    }

    /// Set a custom relayer URL.
    pub fn set_url(&mut self, url: String) {
        self.base_url = url.trim_end_matches('/').to_string();
    }

    /// Get the signer's EOA address.
    pub fn signer_address(&self) -> ethers::types::Address {
        self.signer.address()
    }

    /// Get the derived wallet address (Safe or Proxy).
    pub fn wallet_address(&self) -> Result<ethers::types::Address> {
        match self.tx_type {
            RelayerTxType::Safe => derive::derive_safe_address(self.signer.address()),
            RelayerTxType::Proxy => derive::derive_proxy_address(self.signer.address()),
        }
    }

    /// Check if the Safe wallet is deployed.
    pub async fn is_deployed(&self) -> Result<bool> {
        let wallet = self.wallet_address()?;
        let url = format!("{}/deployed?address={:?}", self.base_url, wallet);
        let resp = self.http.get(&url).send().await?;
        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let body = resp.text().await.unwrap_or_default();
            return Err(RelayerError::Api { status, message: body });
        }
        let body: serde_json::Value = resp.json().await?;
        // Handle multiple response formats:
        //   true / false                → bare bool
        //   "true" / "false"            → string
        //   {"deployed": true}          → object
        Ok(body.as_bool()
            .or_else(|| body.as_str().map(|s| s == "true"))
            .or_else(|| body.get("deployed").and_then(|v| v.as_bool()))
            .unwrap_or(false))
    }

    /// Get the current nonce for the signer.
    pub async fn get_nonce(&self) -> Result<u64> {
        let url = format!(
            "{}/nonce?address={:?}&type={}",
            self.base_url,
            self.signer.address(),
            self.tx_type.as_str()
        );
        let resp = self.http.get(&url).send().await?;
        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let body = resp.text().await.unwrap_or_default();
            return Err(RelayerError::Api { status, message: body });
        }
        let body: serde_json::Value = resp.json().await?;
        let nonce = body
            .as_u64()
            .or_else(|| body.as_str().and_then(|s| s.parse().ok()))
            .unwrap_or(0);
        Ok(nonce)
    }

    /// Get relay payload (for Proxy transactions).
    async fn get_relay_payload(&self) -> Result<RelayPayload> {
        let url = format!(
            "{}/relay-payload?address={:?}&type=PROXY",
            self.base_url,
            self.signer.address()
        );
        let resp = self.http.get(&url).send().await?;
        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let body = resp.text().await.unwrap_or_default();
            return Err(RelayerError::Api { status, message: body });
        }
        Ok(resp.json().await?)
    }

    /// Get a transaction's status by ID.
    pub async fn get_transaction(&self, tx_id: &str) -> Result<TxResult> {
        let url = format!("{}/transaction?id={}", self.base_url, tx_id);
        let resp = self.http.get(&url).send().await?;
        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let body = resp.text().await.unwrap_or_default();
            return Err(RelayerError::Api { status, message: body });
        }
        let data: RelayerTransactionResponse = resp.json().await?;
        let state = match data.state.to_uppercase().as_str() {
            "NEW" => TxState::New,
            "EXECUTED" => TxState::Executed,
            "MINED" => TxState::Mined,
            "CONFIRMED" => TxState::Confirmed,
            "FAILED" => TxState::Failed,
            "INVALID" => TxState::Invalid,
            _ => TxState::New,
        };
        Ok(TxResult {
            state,
            tx_hash: data.transaction_hash.or(data.hash),
            proxy_address: None,
            error: None,
        })
    }

    /// Deploy a Safe wallet (one-time, Safe wallet type only).
    pub async fn deploy(&self) -> Result<TxResult> {
        if self.tx_type != RelayerTxType::Safe {
            return Err(RelayerError::Other(
                "deploy() is only for Safe wallet type".to_string(),
            ));
        }

        if self.is_deployed().await? {
            let wallet = self.wallet_address()?;
            return Err(RelayerError::WalletAlreadyDeployed(format!("{:?}", wallet)));
        }

        let safe_address = self.wallet_address()?;
        let (signature, params) =
            create::build_create_transaction(self.signer.as_ref(), self.chain_id).await?;

        let request = TransactionRequest {
            tx_type: "SAFE-CREATE".to_string(),
            from: format!("{:?}", self.signer.address()),
            to: contracts::SAFE_FACTORY.to_string(),
            proxy_wallet: Some(format!("{:?}", safe_address)),
            data: "0x".to_string(),
            signature,
            nonce: None,
            signature_params: serde_json::to_value(&params)
                .map_err(|e| RelayerError::Abi(e.to_string()))?,
            metadata: Some("Deploy Safe wallet".to_string()),
            value: Some("0".to_string()),
        };

        let response = self.submit(request).await?;
        info!(tx_id = %response.transaction_id, "Safe deploy submitted");

        let result = self.wait_for_tx(&response.transaction_id).await?;
        Ok(TxResult {
            proxy_address: Some(format!("{:?}", safe_address)),
            ..result
        })
    }

    /// Execute one or more transactions through the relayer.
    pub async fn execute(
        &self,
        txs: Vec<Transaction>,
        description: &str,
    ) -> Result<TransactionResponseHandle> {
        if txs.is_empty() {
            return Err(RelayerError::Other("No transactions to execute".to_string()));
        }

        let request = match self.tx_type {
            RelayerTxType::Safe => self.build_safe_request(&txs, description).await?,
            RelayerTxType::Proxy => self.build_proxy_request(&txs, description).await?,
        };

        let response = self.submit(request).await?;
        info!(tx_id = %response.transaction_id, description, "Transaction submitted");

        Ok(TransactionResponseHandle {
            tx_id: response.transaction_id,
            client: self.clone(),
        })
    }

    /// Build a Safe transaction request with full EIP-712 signing.
    async fn build_safe_request(
        &self,
        txs: &[Transaction],
        metadata: &str,
    ) -> Result<TransactionRequest> {
        let safe_address = self.wallet_address()?;

        // Don't block on is_deployed() — the relayer will reject if not deployed.
        // This matches the Python SDK behavior.

        let nonce = self.get_nonce().await?;

        let (data, to, signature, sig_params) = safe::build_safe_transaction(
            self.signer.as_ref(),
            self.chain_id,
            safe_address,
            txs,
            nonce,
        )
        .await?;

        Ok(TransactionRequest {
            tx_type: "SAFE".to_string(),
            from: format!("{:?}", self.signer.address()),
            to: format!("{:?}", to),
            proxy_wallet: Some(format!("{:?}", safe_address)),
            data,
            signature,
            nonce: Some(nonce.to_string()),
            signature_params: serde_json::to_value(&sig_params)
                .map_err(|e| RelayerError::Abi(e.to_string()))?,
            metadata: Some(metadata.to_string()),
            value: Some("0".to_string()),
        })
    }

    /// Build a Proxy transaction request with keccak256 signing.
    async fn build_proxy_request(
        &self,
        txs: &[Transaction],
        metadata: &str,
    ) -> Result<TransactionRequest> {
        let proxy_address = self.wallet_address()?;
        let relay_payload = self.get_relay_payload().await?;

        let (data, signature, sig_params) = proxy::build_proxy_transaction(
            self.signer.as_ref(),
            self.signer.address(),
            txs,
            &relay_payload,
            DEFAULT_GAS_LIMIT,
        )
        .await?;

        Ok(TransactionRequest {
            tx_type: "PROXY".to_string(),
            from: format!("{:?}", self.signer.address()),
            to: contracts::PROXY_FACTORY.to_string(),
            proxy_wallet: Some(format!("{:?}", proxy_address)),
            data,
            signature,
            nonce: Some(relay_payload.nonce),
            signature_params: serde_json::to_value(&sig_params)
                .map_err(|e| RelayerError::Abi(e.to_string()))?,
            metadata: Some(metadata.to_string()),
            value: Some("0".to_string()),
        })
    }

    /// Submit a transaction request to the relayer.
    async fn submit(&self, request: TransactionRequest) -> Result<RelayerTransactionResponse> {
        let url = format!("{}/submit", self.base_url);
        let body = serde_json::to_string(&request)
            .map_err(|e| RelayerError::Abi(e.to_string()))?;

        debug!(url = %url, body_len = body.len(), "Submitting to relayer");

        let auth_headers = self.auth.headers("POST", "/submit", &body)?;

        debug!(
            headers = ?auth_headers.keys().map(|k| k.as_str()).collect::<Vec<_>>(),
            "Auth headers"
        );

        let resp = self
            .http
            .post(&url)
            .headers(auth_headers)
            .header("Content-Type", "application/json")
            .body(body)
            .send()
            .await?;

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let err = resp.text().await.unwrap_or_default();
            if status == 429 {
                return Err(RelayerError::QuotaExhausted);
            }
            return Err(RelayerError::Api { status, message: err });
        }

        Ok(resp.json().await?)
    }

    /// Poll for transaction confirmation.
    async fn wait_for_tx(&self, tx_id: &str) -> Result<TxResult> {
        for attempt in 0..MAX_POLL_ATTEMPTS {
            sleep(POLL_INTERVAL).await;
            let result = self.get_transaction(tx_id).await?;
            debug!(attempt, state = ?result.state, tx_id, "Polling transaction");

            if result.state.is_terminal() {
                if result.state == TxState::Failed {
                    return Err(RelayerError::TransactionFailed(format!(
                        "Transaction {} failed",
                        tx_id
                    )));
                }
                if result.state == TxState::Invalid {
                    return Err(RelayerError::TransactionInvalid(format!(
                        "Transaction {} rejected",
                        tx_id
                    )));
                }
                return Ok(result);
            }
        }
        Err(RelayerError::Timeout)
    }

    // ── Convenience methods ──

    /// Approve USDC.e for CTF Exchange.
    pub async fn approve_usdc_for_ctf(&self) -> Result<TransactionResponseHandle> {
        let tx = crate::operations::approve_usdc_for_ctf_exchange();
        self.execute(vec![tx], "Approve USDC for CTF Exchange").await
    }

    /// Approve USDC.e for Neg Risk CTF Exchange.
    pub async fn approve_usdc_for_negrisk(&self) -> Result<TransactionResponseHandle> {
        let tx = crate::operations::approve_usdc_for_neg_risk_exchange();
        self.execute(vec![tx], "Approve USDC for NegRisk Exchange").await
    }

    /// Approve CTF tokens (ERC1155) for CTF Exchange.
    pub async fn approve_ctf_for_exchange(&self) -> Result<TransactionResponseHandle> {
        let tx = crate::operations::approve_ctf_for_ctf_exchange();
        self.execute(vec![tx], "Approve CTF for Exchange").await
    }

    /// Set up all standard approvals in a single batch.
    pub async fn setup_approvals(&self) -> Result<TransactionResponseHandle> {
        let txs = vec![
            crate::operations::approve_usdc_for_ctf_exchange(),
            crate::operations::approve_usdc_for_neg_risk_exchange(),
            crate::operations::approve_ctf_for_ctf_exchange(),
            crate::operations::approve_ctf_for_neg_risk_exchange(),
            crate::operations::approve_ctf_for_neg_risk_adapter(),
        ];
        self.execute(txs, "Setup all approvals").await
    }
}

/// Handle for a submitted transaction, with polling support.
pub struct TransactionResponseHandle {
    pub tx_id: String,
    client: RelayClient,
}

impl TransactionResponseHandle {
    /// Poll the transaction until it reaches a terminal state.
    pub async fn wait(self) -> Result<TxResult> {
        self.client.wait_for_tx(&self.tx_id).await
    }

    /// Get the transaction ID.
    pub fn id(&self) -> &str {
        &self.tx_id
    }
}