forked from Txio-labs/txio-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoroban.rs
More file actions
209 lines (184 loc) · 6.72 KB
/
Copy pathsoroban.rs
File metadata and controls
209 lines (184 loc) · 6.72 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
use crate::chains::traits::ChainAdapter;
use crate::chains::validation::{build_url, build_url_with_query, validate_soroban_address};
use crate::cli::parser::Network;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use reqwest::Client;
use serde_json::{Value, json};
pub struct SorobanAdapter {
client: Client,
rpc_url: String,
network: Network,
}
impl SorobanAdapter {
#[allow(dead_code)]
pub fn new() -> Self {
Self::with_rpc(None, Network::Mainnet)
}
fn horizon_url(&self) -> Result<&'static str> {
match self.network {
Network::Mainnet => Ok("https://horizon.stellar.org"),
Network::Testnet => Ok("https://horizon-testnet.stellar.org"),
Network::Devnet | Network::Localnet => Err(anyhow!(
"Horizon API is not available for {:?} network; \
balance, account, and history commands require mainnet or testnet",
self.network
)),
}
}
pub fn with_rpc(rpc_url: Option<String>, network: Network) -> Self {
let url = rpc_url.unwrap_or_else(|| match network {
Network::Mainnet => "https://soroban-rpc.mainnet.stellar.org".to_string(),
Network::Testnet => "https://soroban-testnet.stellar.org".to_string(),
Network::Devnet => "https://futurenet.soroban-rpc.stellar.org".to_string(), // Futurenet is often used as devnet
Network::Localnet => "http://127.0.0.1:8000/soroban/rpc".to_string(),
});
Self {
client: Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| Client::new()),
rpc_url: url,
network,
}
}
}
#[async_trait]
impl ChainAdapter for SorobanAdapter {
fn name(&self) -> &'static str {
"Soroban"
}
fn default_rpc(&self) -> &'static str {
"https://soroban-rpc.mainnet.stellar.org"
}
async fn call_rpc(&self, method: &str, params: Value) -> Result<Value> {
let payload = json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params
});
let response = self
.client
.post(&self.rpc_url)
.json(&payload)
.send()
.await?;
let body: Value = response.json().await?;
if let Some(error) = body.get("error") {
let msg = error
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("Unknown RPC Error");
let code = error.get("code").and_then(|c| c.as_i64()).unwrap_or(0);
return Err(anyhow!("{msg} (Code: {code})"));
}
Ok(body.get("result").cloned().unwrap_or(Value::Null))
}
async fn get_balance(&self, address: &str) -> Result<Value> {
let address = validate_soroban_address(address)?;
let horizon = self.horizon_url()?;
let url = build_url(horizon, &["accounts", &address])?;
Ok(self.client.get(url).send().await?.json().await?)
}
async fn get_transaction(&self, hash: &str) -> Result<Value> {
self.call_rpc("getTransaction", json!({ "hash": hash }))
.await
}
async fn get_block(&self, block: Option<u64>) -> Result<Value> {
match block {
Some(seq) => {
self.call_rpc("getLedgers", json!({ "startLedger": seq, "limit": 1 }))
.await
}
None => self.call_rpc("getLatestLedger", json!({})).await,
}
}
async fn get_gas_price(&self) -> Result<Value> {
self.call_rpc("getFeeStats", json!({})).await
}
async fn get_account(&self, address: &str) -> Result<Value> {
let address = validate_soroban_address(address)?;
let horizon = self.horizon_url()?;
let url = build_url(horizon, &["accounts", &address])?;
Ok(self.client.get(url).send().await?.json().await?)
}
async fn get_history(&self, address: &str, limit: u32) -> Result<Value> {
let address = validate_soroban_address(address)?;
let horizon = self.horizon_url()?;
let url = build_url_with_query(
horizon,
&["accounts", &address, "transactions"],
&[("limit", limit.to_string()), ("order", "desc".to_string())],
)?;
Ok(self.client.get(url).send().await?.json().await?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn horizon_url_mainnet_returns_mainnet_horizon() {
let adapter = SorobanAdapter::with_rpc(None, Network::Mainnet);
assert_eq!(
adapter.horizon_url().unwrap(),
"https://horizon.stellar.org"
);
}
#[test]
fn horizon_url_mainnet_with_custom_rpc_still_returns_mainnet_horizon() {
let adapter = SorobanAdapter::with_rpc(
Some("https://my-node.example.com".to_string()),
Network::Mainnet,
);
assert_eq!(
adapter.horizon_url().unwrap(),
"https://horizon.stellar.org"
);
}
#[test]
fn horizon_url_testnet_returns_testnet_horizon() {
let adapter = SorobanAdapter::with_rpc(None, Network::Testnet);
assert_eq!(
adapter.horizon_url().unwrap(),
"https://horizon-testnet.stellar.org"
);
}
#[test]
fn horizon_url_devnet_returns_error() {
let adapter = SorobanAdapter::with_rpc(None, Network::Devnet);
let err = adapter.horizon_url().unwrap_err();
assert!(
err.to_string().contains("not available"),
"expected 'not available' error, got: {err}"
);
}
#[test]
fn horizon_url_localnet_returns_error() {
let adapter = SorobanAdapter::with_rpc(None, Network::Localnet);
let err = adapter.horizon_url().unwrap_err();
assert!(
err.to_string().contains("not available"),
"expected 'not available' error, got: {err}"
);
}
#[test]
fn with_rpc_stores_network() {
let adapter = SorobanAdapter::with_rpc(None, Network::Testnet);
assert_eq!(adapter.network, Network::Testnet);
}
#[test]
fn with_rpc_custom_url_uses_network_for_horizon() {
// The exact bug scenario: custom rpc_url that doesn't contain "mainnet"
// but user selected mainnet network — should still resolve to mainnet Horizon
let adapter = SorobanAdapter::with_rpc(
Some("https://custom-soroban-rpc.example.com".to_string()),
Network::Mainnet,
);
assert_eq!(
adapter.horizon_url().unwrap(),
"https://horizon.stellar.org"
);
assert_eq!(adapter.rpc_url, "https://custom-soroban-rpc.example.com");
}
}