forked from Scottcjn/Rustchain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_client.rs
More file actions
321 lines (282 loc) · 9.48 KB
/
bridge_client.rs
File metadata and controls
321 lines (282 loc) · 9.48 KB
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
//! Bridge client for cross-chain lock/release operations
use crate::error::{AirdropError, Result};
use crate::models::{ClaimStatus, TargetChain};
use chrono::{DateTime, Utc};
use reqwest::Client;
use serde::{Deserialize, Serialize};
/// Bridge API client
pub struct BridgeClient {
client: Client,
base_url: String,
admin_key: Option<String>,
timeout_secs: u64,
}
impl BridgeClient {
pub fn new(base_url: String, admin_key: Option<String>, timeout_secs: u64) -> Self {
Self {
client: Client::builder()
.timeout(std::time::Duration::from_secs(timeout_secs))
.build()
.unwrap_or_default(),
base_url,
admin_key,
timeout_secs,
}
}
pub fn with_defaults(base_url: String) -> Self {
Self {
client: Client::new(),
base_url,
admin_key: None,
timeout_secs: 30,
}
}
/// Lock RTC for cross-chain bridge
pub async fn lock_rtc(
&self,
sender_wallet: &str,
amount: f64,
target_chain: TargetChain,
target_wallet: &str,
tx_hash: &str,
receipt_signature: Option<&str>,
) -> Result<BridgeLockResponse> {
let mut request = self
.client
.post(format!("{}/bridge/lock", self.base_url))
.header("Content-Type", "application/json");
let mut body = serde_json::json!({
"sender_wallet": sender_wallet,
"amount": amount,
"target_chain": target_chain.to_string(),
"target_wallet": target_wallet,
"tx_hash": tx_hash,
});
if let Some(sig) = receipt_signature {
body["receipt_signature"] = serde_json::json!(sig);
}
request = request.json(&body);
let response = request
.send()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to lock RTC: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(AirdropError::Bridge(format!(
"Bridge API error ({}): {}",
status, body
)));
}
let lock_response: BridgeLockResponse = response
.json()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to parse lock response: {}", e)))?;
Ok(lock_response)
}
/// Confirm a lock (admin only)
pub async fn confirm_lock(
&self,
lock_id: &str,
proof_ref: &str,
notes: Option<&str>,
) -> Result<BridgeLockResponse> {
let admin_key = self.admin_key.as_ref().ok_or_else(|| {
AirdropError::Bridge("Admin key required for confirm_lock".to_string())
})?;
let mut request = self
.client
.post(format!("{}/bridge/confirm", self.base_url))
.header("Content-Type", "application/json")
.header("X-Admin-Key", admin_key)
.json(&serde_json::json!({
"lock_id": lock_id,
"proof_ref": proof_ref,
"notes": notes,
}));
let response = request
.send()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to confirm lock: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(AirdropError::Bridge(format!(
"Bridge API error ({}): {}",
status, body
)));
}
let lock_response: BridgeLockResponse = response.json().await.map_err(|e| {
AirdropError::Bridge(format!("Failed to parse confirm response: {}", e))
})?;
Ok(lock_response)
}
/// Release wRTC on target chain (admin only)
pub async fn release_wrtc(
&self,
lock_id: &str,
release_tx: &str,
notes: Option<&str>,
) -> Result<BridgeLockResponse> {
let admin_key = self.admin_key.as_ref().ok_or_else(|| {
AirdropError::Bridge("Admin key required for release_wrtc".to_string())
})?;
let response = self
.client
.post(format!("{}/bridge/release", self.base_url))
.header("Content-Type", "application/json")
.header("X-Admin-Key", admin_key)
.json(&serde_json::json!({
"lock_id": lock_id,
"release_tx": release_tx,
"notes": notes,
}))
.send()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to release wRTC: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(AirdropError::Bridge(format!(
"Bridge API error ({}): {}",
status, body
)));
}
let lock_response: BridgeLockResponse = response.json().await.map_err(|e| {
AirdropError::Bridge(format!("Failed to parse release response: {}", e))
})?;
Ok(lock_response)
}
/// Get lock status
pub async fn get_lock_status(&self, lock_id: &str) -> Result<BridgeLockStatus> {
let response = self
.client
.get(format!("{}/bridge/status/{}", self.base_url, lock_id))
.send()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to get lock status: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(AirdropError::Bridge(format!(
"Bridge API error ({}): {}",
status, body
)));
}
let status: BridgeLockStatus = response
.json()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to parse lock status: {}", e)))?;
Ok(status)
}
/// Get bridge statistics
pub async fn get_stats(&self) -> Result<BridgeStats> {
let response = self
.client
.get(format!("{}/bridge/stats", self.base_url))
.send()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to get bridge stats: {}", e)))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(AirdropError::Bridge(format!(
"Bridge API error ({}): {}",
status, body
)));
}
let stats: BridgeStats = response
.json()
.await
.map_err(|e| AirdropError::Bridge(format!("Failed to parse bridge stats: {}", e)))?;
Ok(stats)
}
}
/// Bridge lock response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BridgeLockResponse {
pub lock_id: String,
pub state: String,
pub sender_wallet: String,
pub amount_rtc: f64,
pub target_chain: String,
pub target_wallet: String,
pub tx_hash: String,
pub proof_type: Option<String>,
pub proof_ref: Option<String>,
pub expires_at: u64,
pub message: Option<String>,
}
/// Bridge lock status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BridgeLockStatus {
pub lock_id: String,
pub state: String,
pub sender_wallet: String,
pub amount_rtc: f64,
pub target_chain: String,
pub target_wallet: String,
pub tx_hash: Option<String>,
pub proof_type: Option<String>,
pub proof_ref: Option<String>,
pub release_tx: Option<String>,
pub confirmed_at: Option<u64>,
pub confirmed_by: Option<String>,
pub created_at: u64,
pub updated_at: u64,
pub expires_at: u64,
pub events: Vec<BridgeEvent>,
}
/// Bridge event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BridgeEvent {
#[serde(rename = "type")]
pub event_type: String,
pub actor: Option<String>,
pub ts: u64,
pub details: serde_json::Value,
}
/// Bridge statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BridgeStats {
pub by_state: serde_json::Value,
pub by_chain: serde_json::Value,
pub all_time: BridgeAllTimeStats,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BridgeAllTimeStats {
pub total_locks: u64,
pub total_rtc_locked: f64,
}
/// Convert bridge state to claim status
pub fn bridge_state_to_claim_state(state: &str) -> ClaimStatus {
match state {
"requested" | "pending" => ClaimStatus::Pending,
"confirmed" => ClaimStatus::Verified,
"releasing" => ClaimStatus::Bridging,
"complete" => ClaimStatus::Complete,
"failed" => ClaimStatus::Failed,
"refunded" => ClaimStatus::Failed,
_ => ClaimStatus::Pending,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bridge_state_conversion() {
assert_eq!(
bridge_state_to_claim_state("requested"),
ClaimStatus::Pending
);
assert_eq!(
bridge_state_to_claim_state("confirmed"),
ClaimStatus::Verified
);
assert_eq!(
bridge_state_to_claim_state("complete"),
ClaimStatus::Complete
);
assert_eq!(bridge_state_to_claim_state("failed"), ClaimStatus::Failed);
}
}