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
//! ERC1155 token operations for Conditional Token Framework (CTF)
use alloy::network::TransactionBuilder;
use alloy::primitives::{Address, Bytes, U256};
use alloy::providers::{Provider, ProviderBuilder};
use crate::onchain::{
contracts::IERC1155, wallet::OnchainClient, OnchainError, PositionId, Result,
TransactionOptions,
};
/// ERC1155 (CTF token) operations
impl OnchainClient {
/// Get CTF token balance for a specific position
///
/// # Arguments
/// * `position_id` - The position ID (token ID in ERC1155)
///
/// # Example
/// ```no_run
/// # use polymarket_sdk::onchain::OnchainClientBuilder;
/// # use alloy::primitives::U256;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = OnchainClientBuilder::new()
/// .mainnet()
/// .private_key("0x1234...")?
/// .build()?;
///
/// let position_id = U256::from(12345);
/// let balance = client.get_ctf_balance(position_id).await?;
/// println!("Position balance: {}", balance);
/// # Ok(())
/// # }
/// ```
pub async fn get_ctf_balance(&self, position_id: PositionId) -> Result<U256> {
self.get_ctf_balance_of(self.address(), position_id).await
}
/// Get CTF token balance for a specific address and position
///
/// # Arguments
/// * `owner` - The address to check balance for
/// * `position_id` - The position ID (token ID in ERC1155)
pub async fn get_ctf_balance_of(
&self,
owner: Address,
position_id: PositionId,
) -> Result<U256> {
let contract = IERC1155::new(self.addresses().ctf, self.provider().provider());
let balance = contract
.balanceOf(owner, position_id)
.call()
.await
.map_err(|e| {
OnchainError::ContractError(format!("Failed to get CTF balance: {}", e))
})?;
Ok(balance)
}
/// Get batch balances for multiple positions
///
/// # Arguments
/// * `owners` - Array of owner addresses
/// * `position_ids` - Array of position IDs (must match owners length)
///
/// Returns a vector of balances corresponding to each (owner, position_id) pair
pub async fn get_ctf_batch_balances(
&self,
owners: Vec<Address>,
position_ids: Vec<PositionId>,
) -> Result<Vec<U256>> {
if owners.len() != position_ids.len() {
return Err(OnchainError::InvalidAmount(
"Owners and position_ids must have the same length".to_string(),
));
}
let contract = IERC1155::new(self.addresses().ctf, self.provider().provider());
let balances = contract
.balanceOfBatch(owners.clone(), position_ids.clone())
.call()
.await
.map_err(|e| {
OnchainError::ContractError(format!("Failed to get batch balances: {}", e))
})?;
Ok(balances)
}
/// Check if an operator is approved for all CTF tokens
///
/// # Arguments
/// * `operator` - The operator address (e.g., Exchange contract)
pub async fn is_ctf_approved_for_all(&self, operator: Address) -> Result<bool> {
self.is_ctf_approved_for_all_by(self.address(), operator)
.await
}
/// Check if an operator is approved for all CTF tokens for a specific owner
///
/// # Arguments
/// * `owner` - The token owner address
/// * `operator` - The operator address
pub async fn is_ctf_approved_for_all_by(
&self,
owner: Address,
operator: Address,
) -> Result<bool> {
let contract = IERC1155::new(self.addresses().ctf, self.provider().provider());
let approved = contract
.isApprovedForAll(owner, operator)
.call()
.await
.map_err(|e| {
OnchainError::ContractError(format!("Failed to check approval: {}", e))
})?;
Ok(approved)
}
/// Set approval for all CTF tokens
///
/// Grants or revokes permission for an operator to manage all CTF tokens
///
/// # Arguments
/// * `operator` - The operator address (e.g., Exchange contract)
/// * `approved` - True to grant approval, false to revoke
/// * `options` - Transaction options (gas, confirmations, etc.)
///
/// # Example
/// ```no_run
/// # use polymarket_sdk::onchain::OnchainClientBuilder;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = OnchainClientBuilder::new()
/// .mainnet()
/// .private_key("0x1234...")?
/// .build()?;
///
/// // Approve exchange to trade CTF tokens
/// client.set_ctf_approval_for_all(
/// client.addresses().exchange,
/// true,
/// None,
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_ctf_approval_for_all(
&self,
operator: Address,
approved: bool,
options: Option<TransactionOptions>,
) -> Result<alloy::primitives::TxHash> {
let wallet = self.ethereum_wallet();
// Build the provider with wallet
let url = self.network().rpc_url.parse().map_err(|e| {
OnchainError::NetworkError(format!("Invalid RPC URL: {}", e))
})?;
let provider = ProviderBuilder::new()
.wallet(wallet)
.connect_http(url);
let contract = IERC1155::new(self.addresses().ctf, &provider);
let call = contract.setApprovalForAll(operator, approved);
// Apply transaction options if provided
let tx = if let Some(opts) = options {
let mut builder = call.into_transaction_request();
if let Some(gas_price) = opts.gas_price {
builder = builder.with_gas_price(gas_price.to::<u128>());
}
if let Some(gas_limit) = opts.gas_limit {
builder = builder.with_gas_limit(gas_limit.to::<u64>());
}
// Send the transaction
let pending = provider
.send_transaction(builder)
.await
.map_err(|e| OnchainError::TransactionFailed(format!("Failed to send: {}", e)))?;
if opts.wait_for_confirmation {
let receipt = pending
.with_required_confirmations(opts.confirmations.unwrap_or(1))
.get_receipt()
.await
.map_err(|e| {
OnchainError::TransactionFailed(format!("Failed to confirm: {}", e))
})?;
receipt.transaction_hash
} else {
*pending.tx_hash()
}
} else {
// Send without custom options
let pending = call
.send()
.await
.map_err(|e| OnchainError::TransactionFailed(format!("Failed to send: {}", e)))?;
*pending.tx_hash()
};
Ok(tx)
}
/// Transfer a single CTF token to another address
///
/// # Arguments
/// * `to` - The recipient address
/// * `position_id` - The position ID to transfer
/// * `amount` - The amount to transfer
/// * `data` - Additional data (usually empty)
/// * `options` - Transaction options (gas, confirmations, etc.)
pub async fn transfer_ctf(
&self,
to: Address,
position_id: PositionId,
amount: U256,
data: Option<Bytes>,
options: Option<TransactionOptions>,
) -> Result<alloy::primitives::TxHash> {
let wallet = self.ethereum_wallet();
// Build the provider with wallet
let url = self.network().rpc_url.parse().map_err(|e| {
OnchainError::NetworkError(format!("Invalid RPC URL: {}", e))
})?;
let provider = ProviderBuilder::new()
.wallet(wallet)
.connect_http(url);
let contract = IERC1155::new(self.addresses().ctf, &provider);
let data = data.unwrap_or_default();
let call = contract.safeTransferFrom(self.address(), to, position_id, amount, data);
// Apply transaction options if provided
let tx = if let Some(opts) = options {
let mut builder = call.into_transaction_request();
if let Some(gas_price) = opts.gas_price {
builder = builder.with_gas_price(gas_price.to::<u128>());
}
if let Some(gas_limit) = opts.gas_limit {
builder = builder.with_gas_limit(gas_limit.to::<u64>());
}
// Send the transaction
let pending = provider
.send_transaction(builder)
.await
.map_err(|e| OnchainError::TransactionFailed(format!("Failed to send: {}", e)))?;
if opts.wait_for_confirmation {
let receipt = pending
.with_required_confirmations(opts.confirmations.unwrap_or(1))
.get_receipt()
.await
.map_err(|e| {
OnchainError::TransactionFailed(format!("Failed to confirm: {}", e))
})?;
receipt.transaction_hash
} else {
*pending.tx_hash()
}
} else {
// Send without custom options
let pending = call
.send()
.await
.map_err(|e| OnchainError::TransactionFailed(format!("Failed to send: {}", e)))?;
*pending.tx_hash()
};
Ok(tx)
}
/// Transfer multiple CTF tokens in a single transaction
///
/// # Arguments
/// * `to` - The recipient address
/// * `position_ids` - Array of position IDs to transfer
/// * `amounts` - Array of amounts (must match position_ids length)
/// * `data` - Additional data (usually empty)
/// * `options` - Transaction options (gas, confirmations, etc.)
pub async fn transfer_ctf_batch(
&self,
to: Address,
position_ids: Vec<PositionId>,
amounts: Vec<U256>,
data: Option<Bytes>,
options: Option<TransactionOptions>,
) -> Result<alloy::primitives::TxHash> {
if position_ids.len() != amounts.len() {
return Err(OnchainError::InvalidAmount(
"Position IDs and amounts must have the same length".to_string(),
));
}
let wallet = self.ethereum_wallet();
// Build the provider with wallet
let url = self.network().rpc_url.parse().map_err(|e| {
OnchainError::NetworkError(format!("Invalid RPC URL: {}", e))
})?;
let provider = ProviderBuilder::new()
.wallet(wallet)
.connect_http(url);
let contract = IERC1155::new(self.addresses().ctf, &provider);
let data = data.unwrap_or_default();
let call = contract.safeBatchTransferFrom(
self.address(),
to,
position_ids,
amounts,
data,
);
// Apply transaction options if provided
let tx = if let Some(opts) = options {
let mut builder = call.into_transaction_request();
if let Some(gas_price) = opts.gas_price {
builder = builder.with_gas_price(gas_price.to::<u128>());
}
if let Some(gas_limit) = opts.gas_limit {
builder = builder.with_gas_limit(gas_limit.to::<u64>());
}
// Send the transaction
let pending = provider
.send_transaction(builder)
.await
.map_err(|e| OnchainError::TransactionFailed(format!("Failed to send: {}", e)))?;
if opts.wait_for_confirmation {
let receipt = pending
.with_required_confirmations(opts.confirmations.unwrap_or(1))
.get_receipt()
.await
.map_err(|e| {
OnchainError::TransactionFailed(format!("Failed to confirm: {}", e))
})?;
receipt.transaction_hash
} else {
*pending.tx_hash()
}
} else {
// Send without custom options
let pending = call
.send()
.await
.map_err(|e| OnchainError::TransactionFailed(format!("Failed to send: {}", e)))?;
*pending.tx_hash()
};
Ok(tx)
}
}
#[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";
fn create_test_client() -> OnchainClient {
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();
OnchainClient::new(provider, signer)
}
#[test]
fn test_batch_validation() {
let client = create_test_client();
// Test mismatched lengths
let owners = vec![Address::ZERO];
let position_ids = vec![U256::ZERO, U256::from(1)];
let result = tokio::runtime::Runtime::new()
.unwrap()
.block_on(client.get_ctf_batch_balances(owners, position_ids));
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("must have the same length"));
}
#[test]
fn test_transfer_batch_validation() {
let client = create_test_client();
// Test mismatched lengths
let position_ids = vec![U256::ZERO];
let amounts = vec![U256::from(1), U256::from(2)];
let result = tokio::runtime::Runtime::new().unwrap().block_on(
client.transfer_ctf_batch(Address::ZERO, position_ids, amounts, None, None),
);
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("must have the same length"));
}
}