1use bytes::Bytes;
4use http::Method;
5use http::header::{CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8
9use crate::OkxRegion;
10use crate::api::account::Account;
11use crate::api::convert::Convert;
12use crate::api::finance::Finance;
13use crate::api::funding::Funding;
14use crate::api::market::Market;
15use crate::api::public_data::PublicData;
16use crate::api::trade::Trade;
17use crate::credentials::Credentials;
18use crate::error::{Error, RestError};
19use crate::model::OkxResponse;
20use crate::signing;
21use crate::transport::{DefaultTransport, Transport};
22
23pub struct OkxClient<T = DefaultTransport> {
35 transport: T,
36 credentials: Option<Credentials>,
37 base_url: String,
38 demo: bool,
39}
40
41#[cfg(feature = "reqwest")]
42impl OkxClient {
43 pub fn builder() -> OkxClientBuilder<DefaultTransport> {
46 OkxClientBuilder::from_transport(crate::transport::ReqwestTransport::new())
47 }
48}
49
50impl<T> OkxClient<T> {
51 pub fn with_transport(transport: T) -> OkxClientBuilder<T> {
53 OkxClientBuilder::from_transport(transport)
54 }
55}
56
57impl<T: Transport> OkxClient<T> {
58 pub fn market(&self) -> Market<'_, T> {
60 Market::new(self)
61 }
62
63 pub fn public_data(&self) -> PublicData<'_, T> {
65 PublicData::new(self)
66 }
67
68 pub fn account(&self) -> Account<'_, T> {
70 Account::new(self)
71 }
72
73 pub fn funding(&self) -> Funding<'_, T> {
75 Funding::new(self)
76 }
77
78 pub fn convert(&self) -> Convert<'_, T> {
80 Convert::new(self)
81 }
82
83 pub fn finance(&self) -> Finance<'_, T> {
85 Finance::new(self)
86 }
87
88 pub fn trade(&self) -> Trade<'_, T> {
90 Trade::new(self)
91 }
92
93 pub(crate) async fn get<Q, D>(
96 &self,
97 endpoint: &'static str,
98 query: &Q,
99 authenticated: bool,
100 ) -> Result<D, Error>
101 where
102 Q: Serialize,
103 D: DeserializeOwned,
104 {
105 let qs = serde_urlencoded::to_string(query)
106 .map_err(|e| RestError::Encode { source: e.into() })?;
107 let request_path = if qs.is_empty() {
108 endpoint.to_owned()
109 } else {
110 format!("{endpoint}?{qs}")
111 };
112 self.send(endpoint, Method::GET, &request_path, Bytes::new(), authenticated)
113 .await
114 }
115
116 pub(crate) async fn post<B, D>(
119 &self,
120 endpoint: &'static str,
121 body: &B,
122 authenticated: bool,
123 ) -> Result<D, Error>
124 where
125 B: Serialize,
126 D: DeserializeOwned,
127 {
128 let body = serde_json::to_vec(body)
129 .map_err(|e| RestError::Encode { source: e.into() })?;
130 self.send(endpoint, Method::POST, endpoint, Bytes::from(body), authenticated)
131 .await
132 }
133
134 async fn send<D>(
135 &self,
136 endpoint: &'static str,
137 method: Method,
138 request_path: &str,
139 body: Bytes,
140 authenticated: bool,
141 ) -> Result<D, Error>
142 where
143 D: DeserializeOwned,
144 {
145 let url = format!("{}{}", self.base_url, request_path);
146 let mut builder = http::Request::builder().method(method.clone()).uri(url);
147
148 let headers = builder
149 .headers_mut()
150 .expect("a freshly constructed request builder has no error");
151 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
152 if self.demo {
153 headers.insert(
154 HeaderName::from_static("x-simulated-trading"),
155 HeaderValue::from_static("1"),
156 );
157 }
158 if authenticated {
159 let credentials = self.credentials.as_ref().ok_or_else(|| {
160 RestError::Configuration(
161 "authenticated endpoint requires credentials".to_owned(),
162 )
163 })?;
164 let timestamp = signing::timestamp();
165 let body_str = std::str::from_utf8(&body).unwrap_or_default();
166 let prehash = signing::pre_hash(×tamp, method.as_str(), request_path, body_str);
167 let signature = signing::sign(&prehash, credentials.secret_key());
168 insert_header(headers, "ok-access-key", credentials.api_key())?;
169 insert_header(headers, "ok-access-sign", &signature)?;
170 insert_header(headers, "ok-access-timestamp", ×tamp)?;
171 insert_header(headers, "ok-access-passphrase", credentials.passphrase())?;
172 }
173
174 let request = builder
175 .body(body)
176 .map_err(|e| RestError::Encode { source: e.into() })?;
177 let response = self.transport.send(request).await.map_err(RestError::from)?;
178 let status = response.status();
179 let bytes = response.into_body();
180 if !status.is_success() {
181 return Err(RestError::HttpStatus {
182 endpoint,
183 status,
184 body: String::from_utf8_lossy(&bytes).into_owned(),
185 }
186 .into());
187 }
188 let envelope: OkxResponse<D> = serde_json::from_slice(&bytes)
189 .map_err(|e| RestError::Decode { endpoint, source: e })?;
190 if envelope.code != "0" {
191 return Err(RestError::Okx {
192 endpoint,
193 code: envelope.code,
194 message: envelope.msg,
195 }
196 .into());
197 }
198 Ok(envelope.data)
199 }
200}
201
202fn insert_header(headers: &mut HeaderMap, name: &'static str, value: &str) -> Result<(), Error> {
203 let value = HeaderValue::from_str(value).map_err(|e| {
204 RestError::Configuration(format!("invalid header value for {name}: {e}"))
205 })?;
206 headers.insert(HeaderName::from_static(name), value);
207 Ok(())
208}
209
210pub struct OkxClientBuilder<T = DefaultTransport> {
214 transport: T,
215 credentials: Option<Credentials>,
216 base_url: String,
217 demo: bool,
218}
219
220impl<T> OkxClientBuilder<T> {
221 fn from_transport(transport: T) -> Self {
222 Self {
223 transport,
224 credentials: None,
225 base_url: crate::API_URL.to_owned(),
226 demo: false,
227 }
228 }
229
230 pub fn credentials(mut self, credentials: Credentials) -> Self {
232 self.credentials = Some(credentials);
233 self
234 }
235
236 pub fn region(mut self, region: OkxRegion) -> Self {
242 self.base_url = region.api_url().to_owned();
243 self
244 }
245
246 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
251 self.base_url = base_url.into();
252 self
253 }
254
255 pub fn demo_trading(mut self, demo: bool) -> Self {
257 self.demo = demo;
258 self
259 }
260
261 pub fn transport<U>(self, transport: U) -> OkxClientBuilder<U> {
263 OkxClientBuilder {
264 transport,
265 credentials: self.credentials,
266 base_url: self.base_url,
267 demo: self.demo,
268 }
269 }
270
271 pub fn build(self) -> OkxClient<T> {
273 OkxClient {
274 transport: self.transport,
275 credentials: self.credentials,
276 base_url: self.base_url,
277 demo: self.demo,
278 }
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use crate::error::{Error, RestError};
285 use crate::test_util::MockTransport;
286 use crate::{OkxClient, OkxRegion};
287
288 #[tokio::test]
292 async fn non_zero_code_is_api_error() {
293 let mock = MockTransport::new(r#"{"code":"51000","msg":"Parameter error","data":[]}"#);
294 let client = OkxClient::with_transport(mock).build();
295 let err = client.market().get_ticker("BAD").await.unwrap_err();
296 match err {
297 Error::Rest(RestError::Okx { code, message, .. }) => {
298 assert_eq!(code, "51000");
299 assert_eq!(message, "Parameter error");
300 }
301 other => panic!("expected Error::Rest(RestError::Okx), got {other:?}"),
302 }
303 }
304
305 #[test]
306 fn okx_region_returns_expected_api_urls() {
307 assert_eq!(OkxRegion::Global.api_url(), "https://www.okx.com");
308 assert_eq!(OkxRegion::Us.api_url(), "https://us.okx.com");
309 assert_eq!(OkxRegion::Eea.api_url(), "https://eea.okx.com");
310 }
311
312 #[tokio::test]
313 async fn region_sets_request_base_url() {
314 let mock = MockTransport::new(r#"{"code":"0","msg":"","data":[]}"#);
315 let client = OkxClient::with_transport(mock.clone())
316 .region(OkxRegion::Us)
317 .build();
318
319 client.market().get_ticker("BTC-USDT").await.unwrap();
320
321 let req = mock.captured();
322 assert!(
323 req.uri
324 .starts_with("https://us.okx.com/api/v5/market/ticker"),
325 "unexpected URI: {}",
326 req.uri
327 );
328 }
329
330 #[tokio::test]
331 async fn base_url_overrides_selected_region() {
332 let mock = MockTransport::new(r#"{"code":"0","msg":"","data":[]}"#);
333 let client = OkxClient::with_transport(mock.clone())
334 .region(OkxRegion::Eea)
335 .base_url("https://example.test")
336 .build();
337
338 client.market().get_ticker("BTC-USDT").await.unwrap();
339
340 let req = mock.captured();
341 assert!(
342 req.uri
343 .starts_with("https://example.test/api/v5/market/ticker"),
344 "unexpected URI: {}",
345 req.uri
346 );
347 }
348}