forked from Txio-labs/txio-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsui_service.rs
More file actions
215 lines (196 loc) · 6.59 KB
/
Copy pathsui_service.rs
File metadata and controls
215 lines (196 loc) · 6.59 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
use crate::model::rpc::RpcLog;
use crate::model::user::User;
use crate::repositories::rpc_repository::RpcRepository;
use crate::utils::error::AppError;
use mongodb::bson::oid::ObjectId;
use reqwest::Client;
use serde_json::Value;
#[derive(Clone)]
pub struct SuiService {
rpc_repo: RpcRepository,
client: Client,
}
#[derive(serde::Serialize)]
struct JsonRpcRequest<'a> {
jsonrpc: &'a str,
id: u64,
method: &'a str,
params: &'a Value,
}
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct JsonRpcResponse {
jsonrpc: String,
id: u64,
result: Option<Value>,
error: Option<Value>,
}
impl SuiService {
pub fn new(rpc_repo: RpcRepository, _rpc_url: String) -> Self {
Self {
rpc_repo,
// Disable automatic redirect-following so a redirected RPC response
// cannot silently send the request to an internal network address
// that passed the initial URL validation but is reachable after a
// redirect (SSRF-via-redirect). If a legitimate endpoint ever needs
// a redirect, the operator should configure the canonical URL
// directly rather than relying on client-side redirect chasing.
client: Client::builder()
.timeout(std::time::Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap_or_else(|_| Client::new()),
}
}
pub async fn call_rpc(
&self,
user: &User,
method: &str,
params: &Value,
) -> Result<Value, AppError> {
self.call_rpc_direct(
user.network.sui_url(),
user.id.unwrap_or_default(),
method,
params,
)
.await
}
pub async fn call_rpc_direct(
&self,
url: &str,
user_id: ObjectId,
method: &str,
params: &Value,
) -> Result<Value, AppError> {
let request_body = JsonRpcRequest {
jsonrpc: "2.0",
id: 1,
method,
params,
};
let response_result = self.client.post(url).json(&request_body).send().await;
let (success, full_resp_val, error_msg) = match response_result {
Ok(resp) => {
if resp.status().is_success() {
match resp.json::<Value>().await {
Ok(val) => {
// Check for "error" field in the JSON-RPC response
let has_error = val.get("error").is_some();
let rpc_error_msg = if has_error {
Some(format!("RPC Error: {}", val["error"]))
} else {
None
};
(!has_error, val, rpc_error_msg)
}
Err(e) => {
let msg = format!("Failed to parse JSON response: {e}");
(
false,
serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"error": { "code": -32700, "message": msg }
}),
Some(msg),
)
}
}
} else {
let msg = format!("HTTP Error: {}", resp.status());
(
false,
serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"error": { "code": -32000, "message": msg }
}),
Some(msg),
)
}
}
Err(e) => {
let msg = format!("Network Error: {e}");
(
false,
serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"error": { "code": -32001, "message": msg }
}),
Some(msg),
)
}
};
// Log the request
let log = RpcLog::new(
user_id,
method.to_string(),
params.clone(),
success,
error_msg.clone(),
);
if let Err(e) = self.rpc_repo.save(&log).await {
eprintln!("Failed to save RPC log: {e}");
}
// Return the full JSON object (either from Node or Synthesized)
Ok(full_resp_val)
}
pub fn error_response(&self, code: i32, message: &str) -> Value {
serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": code,
"message": message
}
})
}
pub async fn resolve_name_service_address(
&self,
url: &str,
name: &str,
) -> Result<String, AppError> {
// suix_resolveNameServiceAddress takes [name, null, null] usually, or just [name]
// Docs say: suix_resolveNameServiceAddress(name)
let params = serde_json::json!([name]);
let request_body = JsonRpcRequest {
jsonrpc: "2.0",
id: 1,
method: "suix_resolveNameServiceAddress",
params: ¶ms,
};
let response = self
.client
.post(url)
.json(&request_body)
.send()
.await
.map_err(|e| AppError::ExternalService(format!("Network Error: {e}")))?;
if !response.status().is_success() {
return Err(AppError::ExternalService(format!(
"HTTP Error: {}",
response.status()
)));
}
let rpc_resp = response
.json::<JsonRpcResponse>()
.await
.map_err(|e| AppError::InternalError(format!("Failed to parse JSON: {e}")))?;
if let Some(err) = rpc_resp.error {
return Err(AppError::ExternalService(format!(
"Resolution Error: {err}"
)));
}
match rpc_resp.result {
Some(Value::String(addr)) => Ok(addr),
Some(_) => Err(AppError::InternalError(
"Unexpected result type for address resolution".into(),
)),
None => Err(AppError::NotFound(format!(
"Could not resolve name: {name}"
))),
}
}
}