1use std::sync::Arc;
2
3use longbridge_httpcli::{DcRegion, HttpClient, Json, Method};
4use serde::{Serialize, de::DeserializeOwned};
5use tracing::{Subscriber, dispatcher, instrument::WithSubscriber};
6
7use crate::{
8 Config, Error, Result,
9 asset::{
10 BankCard, BankCardsResponse, CouponOrder, CouponOrderType, CouponOrdersResponse,
11 CouponsResponse, DepositsResponse, EddaApplication, EddaApplicationsResponse,
12 GetCouponsOptions, GetDepositsOptions, GetRewardRecordsOptions, GetStatementListOptions,
13 GetStatementListResponse, GetStatementOptions, GetStatementResponse,
14 GetStockTransfersInOptions, GetStockTransfersOutOptions, GetWithdrawalsOptions,
15 RewardRecordsResponse, StockTransferInResponse, StockTransferOut, StockTransferOutResponse,
16 WithdrawalsResponse, core,
17 requests::{GetCouponOrdersQuery, GetEddaApplicationsQuery},
18 token,
19 },
20};
21
22struct InnerAssetContext {
23 http_cli: HttpClient,
24 log_subscriber: Arc<dyn Subscriber + Send + Sync>,
25}
26
27impl Drop for InnerAssetContext {
28 fn drop(&mut self) {
29 dispatcher::with_default(&self.log_subscriber.clone().into(), || {
30 tracing::info!("asset context dropped");
31 });
32 }
33}
34
35#[derive(Clone)]
37pub struct AssetContext(Arc<InnerAssetContext>);
38
39impl AssetContext {
40 pub fn new(config: Arc<Config>) -> Self {
42 let log_subscriber = config.create_log_subscriber("asset");
43
44 dispatcher::with_default(&log_subscriber.clone().into(), || {
45 tracing::info!(language = ?config.language, "creating asset context");
46 });
47
48 let ctx = Self(Arc::new(InnerAssetContext {
49 http_cli: config.create_http_client(),
50 log_subscriber,
51 }));
52
53 dispatcher::with_default(&ctx.0.log_subscriber.clone().into(), || {
54 tracing::info!("asset context created");
55 });
56
57 ctx
58 }
59
60 #[inline]
62 pub fn log_subscriber(&self) -> Arc<dyn Subscriber + Send + Sync> {
63 self.0.log_subscriber.clone()
64 }
65
66 async fn get<R, Q>(&self, path: &'static str, query: Q) -> Result<R>
67 where
68 R: DeserializeOwned + Send + Sync + 'static,
69 Q: Serialize + Send + Sync,
70 {
71 Ok(self
72 .0
73 .http_cli
74 .request(Method::GET, path)
75 .query_params(query)
76 .response::<Json<R>>()
77 .send()
78 .with_subscriber(self.0.log_subscriber.clone())
79 .await?
80 .0)
81 }
82
83 async fn get_account<R, Q>(&self, path: &'static str, query: Q) -> Result<R>
90 where
91 R: DeserializeOwned + Send + Sync + 'static,
92 Q: Serialize + Send + Sync,
93 {
94 self.get_account_route(path, query, true).await
95 }
96
97 async fn get_account_route<R, Q>(
100 &self,
101 path: &'static str,
102 query: Q,
103 send_channel: bool,
104 ) -> Result<R>
105 where
106 R: DeserializeOwned + Send + Sync + 'static,
107 Q: Serialize + Send + Sync,
108 {
109 #[derive(Serialize)]
110 struct AccountQuery<Q> {
111 #[serde(flatten)]
112 query: Q,
113 #[serde(skip_serializing_if = "Option::is_none")]
114 account_channel: Option<String>,
115 }
116
117 let account_channel = if send_channel {
118 self.0
119 .http_cli
120 .access_token()
121 .await
122 .ok()
123 .and_then(|token| token::account_channel(&token))
124 } else {
125 None
126 };
127 Ok(self
128 .0
129 .http_cli
130 .request(Method::GET, path)
131 .dc_restrict(DcRegion::Ap)
132 .query_params(AccountQuery {
133 query,
134 account_channel,
135 })
136 .response::<Json<R>>()
137 .send()
138 .with_subscriber(self.0.log_subscriber.clone())
139 .await?
140 .0)
141 }
142
143 pub async fn statements(
147 &self,
148 options: GetStatementListOptions,
149 ) -> Result<GetStatementListResponse> {
150 self.get(core::GET_STATEMENT_DATA_LIST_PATH, options).await
151 }
152
153 pub async fn statement_download_url(
157 &self,
158 options: GetStatementOptions,
159 ) -> Result<GetStatementResponse> {
160 self.get(core::GET_STATEMENT_DATA_DOWNLOAD_URL_PATH, options)
161 .await
162 }
163
164 pub async fn bank_cards(&self) -> Result<Vec<BankCard>> {
192 #[derive(Serialize)]
193 struct Query {
194 from_app_page: &'static str,
195 }
196 Ok(self
197 .get_account::<BankCardsResponse, _>(
198 core::BANK_CARDS_PATH,
199 Query {
200 from_app_page: "cards",
201 },
202 )
203 .await?
204 .list)
205 }
206
207 pub async fn edda_applications(
216 &self,
217 card_id: impl Into<String>,
218 currency: impl Into<String>,
219 ) -> Result<Vec<EddaApplication>> {
220 let card_id = card_id.into().trim().to_string();
221 if card_id.is_empty() || !card_id.bytes().all(|b| b.is_ascii_digit()) {
222 return Err(Error::ParseField {
223 name: "card_id",
224 error: format!(
225 "edda_applications requires the numeric bank card id (BankCard::id), got {card_id:?}"
226 ),
227 });
228 }
229 let query = GetEddaApplicationsQuery {
230 card_id,
231 currency: currency.into().trim().to_uppercase(),
232 };
233 Ok(self
234 .get_account::<EddaApplicationsResponse, _>(core::EDDA_STATUS_PATH, query)
235 .await?
236 .0)
237 }
238
239 pub async fn stock_transfers_in(
245 &self,
246 options: impl Into<Option<GetStockTransfersInOptions>>,
247 ) -> Result<StockTransferInResponse> {
248 self.get_account(
249 core::STOCK_TRANSFERS_IN_PATH,
250 options.into().unwrap_or_default(),
251 )
252 .await
253 }
254
255 pub async fn stock_transfers_out(
261 &self,
262 options: impl Into<Option<GetStockTransfersOutOptions>>,
263 ) -> Result<Vec<StockTransferOut>> {
264 Ok(self
265 .get_account::<StockTransferOutResponse, _>(
266 core::STOCK_TRANSFERS_OUT_PATH,
267 options.into().unwrap_or_default(),
268 )
269 .await?
270 .records)
271 }
272
273 pub async fn reward_records(
283 &self,
284 options: impl Into<Option<GetRewardRecordsOptions>>,
285 ) -> Result<RewardRecordsResponse> {
286 self.get_account(core::REWARDS_PATH, options.into().unwrap_or_default())
287 .await
288 }
289
290 pub async fn coupons(
300 &self,
301 options: impl Into<Option<GetCouponsOptions>>,
302 ) -> Result<CouponsResponse> {
303 self.get_account(core::COUPONS_PATH, options.into().unwrap_or_default())
304 .await
305 }
306
307 pub async fn coupon_orders(
317 &self,
318 card_id: impl Into<String>,
319 order_type: CouponOrderType,
320 ) -> Result<Vec<CouponOrder>> {
321 let card_id = card_id.into().trim().to_string();
322 if card_id.len() != 32 || !card_id.bytes().all(|b| b.is_ascii_hexdigit()) {
323 let hint = if !card_id.is_empty() && card_id.bytes().all(|b| b.is_ascii_digit()) {
324 " (this looks like a bank card id, BankCard::id)"
325 } else {
326 ""
327 };
328 return Err(Error::ParseField {
329 name: "card_id",
330 error: format!(
331 "coupon_orders requires the 32-character coupon id (Coupon::card_id), got {card_id:?}{hint}"
332 ),
333 });
334 }
335 let query = GetCouponOrdersQuery {
336 card_id,
337 order_type: order_type.as_str(),
338 };
339 Ok(self
340 .get_account_route::<CouponOrdersResponse, _>(core::COUPON_ORDERS_PATH, query, false)
343 .await?
344 .orders)
345 }
346
347 pub async fn deposits(
358 &self,
359 options: impl Into<Option<GetDepositsOptions>>,
360 ) -> Result<DepositsResponse> {
361 let options = options.into().unwrap_or_default();
362 let page_size = options.page_size();
363 let mut resp: DepositsResponse = self
364 .get_account(core::DEPOSITS_PATH, options.size(page_size))
365 .await?;
366 resp.has_more = usize::try_from(page_size).is_ok_and(|size| resp.items.len() >= size);
367 Ok(resp)
368 }
369
370 pub async fn withdrawals(
380 &self,
381 options: impl Into<Option<GetWithdrawalsOptions>>,
382 ) -> Result<WithdrawalsResponse> {
383 let options = options.into().unwrap_or_default();
384 let page_size = options.page_size();
385 let mut resp: WithdrawalsResponse = self
386 .get_account(core::WITHDRAWALS_PATH, options.size(page_size))
387 .await?;
388 resp.has_more = usize::try_from(page_size).is_ok_and(|size| resp.list.len() >= size);
389 Ok(resp)
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use longbridge_httpcli::HttpClientError;
396 use time::macros::datetime;
397
398 use super::*;
399 use crate::{
400 Error,
401 asset::{DepositState, RewardType, StockTransferInState, StockTransferOutState},
402 };
403
404 fn query(value: &impl Serialize) -> serde_json::Value {
405 serde_json::to_value(value).expect("options serialize")
406 }
407
408 fn json(text: &str) -> serde_json::Value {
409 serde_json::from_str(text).expect("valid JSON literal")
410 }
411
412 #[test]
413 fn account_options_serialize_upstream_names() {
414 let q = query(
415 &GetStockTransfersInOptions::new()
416 .market(" hk ")
417 .state(StockTransferInState::Completed)
418 .start(datetime!(2026-01-01 0:00 +8))
419 .page(2)
420 .size(50),
421 );
422 assert_eq!(
423 q,
424 json(r#"{"market":"HK","state":3,"start":1767196800,"page":2,"size":50}"#),
425 "transfer options"
426 );
427
428 let q = query(
429 &GetDepositsOptions::new()
430 .states([
431 DepositState::Processing,
432 DepositState::Unknown,
433 DepositState::Failed,
434 ])
435 .currencies(["usd", "HKD"])
436 .start(datetime!(2026-01-01 0:00 +8))
437 .end(datetime!(2026-01-01 23:59:59 +8)),
438 );
439 assert_eq!(
440 q,
441 json(
442 r#"{"states":"0,2","currencies":"USD,HKD","from_date":1767196800,"to_date":1767283199}"#
443 ),
444 "deposit options"
445 );
446 assert_eq!(
447 query(&GetDepositsOptions::new().size(50)),
448 json(r#"{"size":20}"#),
449 "deposit page size clamped to 20"
450 );
451 assert_eq!(
452 query(&GetDepositsOptions::new().size(15)),
453 json(r#"{"size":15}"#),
454 "smaller deposit page size kept"
455 );
456 assert_eq!(
457 query(&GetDepositsOptions::new().size(0)),
458 json(r#"{"size":20}"#),
459 "zero page size is the default"
460 );
461 assert_eq!(
462 query(&GetDepositsOptions::new().size(-3)),
463 json(r#"{"size":20}"#),
464 "negative page size is the default"
465 );
466 assert_eq!(
467 GetDepositsOptions::new().page_size(),
468 20,
469 "default page size"
470 );
471
472 let q = query(&GetWithdrawalsOptions::new().start(datetime!(2026-01-01 0:00 +8)));
473 assert_eq!(q, json(r#"{"begin":1767196800}"#), "withdrawal options");
474
475 let q = query(
476 &GetRewardRecordsOptions::new()
477 .page(1)
478 .page_size(20)
479 .reward_type(RewardType::Coupon),
480 );
481 assert_eq!(
482 q,
483 json(r#"{"current":1,"page_size":20,"reward_type":2}"#),
484 "reward options"
485 );
486
487 let q = query(
488 &GetStockTransfersOutOptions::new()
489 .state(StockTransferOutState::Failed)
490 .end(datetime!(2026-01-01 23:59:59 +8)),
491 );
492 assert_eq!(
493 q,
494 json(r#"{"state":6,"end":1767283199}"#),
495 "transfer-out state sent as its server code"
496 );
497 assert_eq!(
498 query(&GetStockTransfersInOptions::new().state(StockTransferInState::Failed)),
499 json(r#"{"state":8}"#),
500 "transfer-in failed is code 8"
501 );
502 assert_eq!(
503 query(&GetStockTransfersInOptions::new().state(StockTransferInState::Unknown)),
504 json("{}"),
505 "unknown state is not sent"
506 );
507 assert_eq!(
508 query(&GetRewardRecordsOptions::new().reward_type(RewardType::Unknown)),
509 json("{}"),
510 "unknown reward type is not sent"
511 );
512
513 assert_eq!(
514 query(&GetCouponsOptions::new()),
515 json(r#"{"card_status":-1}"#),
516 "valid coupons by default"
517 );
518 assert_eq!(
519 query(
520 &GetCouponsOptions::new()
521 .expired(true)
522 .card_type("commission")
523 ),
524 json(r#"{"card_status":2,"card_type":"commission"}"#),
525 "expired coupons"
526 );
527 }
528
529 #[tokio::test(flavor = "multi_thread")]
532 async fn account_routes_send_the_account_channel() {
533 use tokio::io::{AsyncReadExt, AsyncWriteExt};
534
535 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
536 .await
537 .expect("bind a local port");
538 let addr = listener.local_addr().expect("local address");
539 let server = tokio::spawn(async move {
540 let mut lines = Vec::new();
541 for _ in 0..2 {
542 let (mut socket, _) = listener.accept().await.expect("accept");
543 let mut buf = vec![0u8; 8192];
544 let n = socket.read(&mut buf).await.expect("read request");
545 let body = r#"{"code":0,"message":"","data":{}}"#;
546 let reply = format!(
547 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
548 body.len()
549 );
550 socket.write_all(reply.as_bytes()).await.expect("reply");
551 let request = String::from_utf8_lossy(&buf[..n]).to_string();
552 lines.push(request.lines().next().unwrap_or_default().to_string());
553 }
554 lines
555 });
556 let token = "eyJhbGciOiJub25lIn0.eyJhYyI6ImxiX3Rlc3QifQ.sig";
558 let config = Arc::new(
559 Config::from_apikey("app_key", "app_secret", token).http_url(format!("http://{addr}")),
560 );
561 let ctx = AssetContext::new(config);
562 let coupons = ctx.coupons(None).await.expect("coupons");
563 assert!(coupons.list.is_empty(), "empty list");
564 let orders = ctx
565 .coupon_orders("0123456789abcdef0123456789ABCDEF", CouponOrderType::Locked)
566 .await
567 .expect("coupon orders");
568 assert!(orders.is_empty(), "empty list");
569 let lines = server.await.expect("server task");
570 assert!(
571 lines[0].starts_with("GET /v1/account/cards?"),
572 "{}",
573 lines[0]
574 );
575 assert!(
576 lines[0].contains("card_status=-1"),
577 "own query kept: {}",
578 lines[0]
579 );
580 assert!(
581 lines[0].contains("account_channel=lb_test"),
582 "channel sent: {}",
583 lines[0]
584 );
585 assert!(
586 lines[1].starts_with("GET /v1/account/card-orders?"),
587 "{}",
588 lines[1]
589 );
590 assert!(
591 lines[1].contains("card_id=0123456789abcdef0123456789ABCDEF"),
592 "own query kept: {}",
593 lines[1]
594 );
595 assert!(
596 !lines[1].contains("account_channel"),
597 "no channel on card-orders: {}",
598 lines[1]
599 );
600 }
601
602 #[tokio::test(flavor = "multi_thread")]
604 async fn deposits_report_a_full_page() {
605 use tokio::io::{AsyncReadExt, AsyncWriteExt};
606
607 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
608 .await
609 .expect("bind a local port");
610 let addr = listener.local_addr().expect("local address");
611 let server = tokio::spawn(async move {
612 let mut lines = Vec::new();
613 for count in [20, 15] {
614 let (mut socket, _) = listener.accept().await.expect("accept");
615 let mut buf = vec![0u8; 8192];
616 let n = socket.read(&mut buf).await.expect("read request");
617 let items = vec![r#"{"id":"1"}"#; count].join(",");
618 let body = format!(r#"{{"code":0,"message":"","data":{{"items":[{items}]}}}}"#);
619 let reply = format!(
620 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
621 body.len()
622 );
623 socket.write_all(reply.as_bytes()).await.expect("reply");
624 let request = String::from_utf8_lossy(&buf[..n]).to_string();
625 lines.push(request.lines().next().unwrap_or_default().to_string());
626 }
627 lines
628 });
629 let config = Arc::new(
630 Config::from_apikey("app_key", "app_secret", "opaque")
631 .http_url(format!("http://{addr}")),
632 );
633 let ctx = AssetContext::new(config);
634 let full = ctx
635 .deposits(GetDepositsOptions::new().size(50))
636 .await
637 .expect("deposits");
638 assert_eq!(full.items.len(), 20, "a full capped page");
639 assert!(
640 full.has_more,
641 "size 50 is sent as 20, so 20 records is a full page"
642 );
643 let short = ctx.deposits(None).await.expect("deposits");
644 assert!(!short.has_more, "15 of the default 20 is the last page");
645 let lines = server.await.expect("server task");
646 assert!(
647 lines[0].contains("size=20"),
648 "capped size sent: {}",
649 lines[0]
650 );
651 assert!(
652 lines[1].contains("size=20"),
653 "default size sent: {}",
654 lines[1]
655 );
656 assert!(
657 !lines[1].contains("account_channel"),
658 "an opaque token sends no channel: {}",
659 lines[1]
660 );
661 }
662
663 #[tokio::test(flavor = "multi_thread")]
665 async fn card_ids_are_checked_locally() {
666 let config = Arc::new(
668 Config::from_apikey("app_key", "app_secret", "opaque").http_url("http://127.0.0.1:9"),
669 );
670 let ctx = AssetContext::new(config);
671 let err = ctx
672 .edda_applications("ab12", "HKD")
673 .await
674 .expect_err("non-numeric bank card id");
675 assert!(
676 matches!(
677 &err,
678 Error::ParseField {
679 name: "card_id",
680 ..
681 }
682 ),
683 "{err}"
684 );
685 assert!(err.to_string().contains("numeric bank card id"), "{err}");
686 let err = ctx
687 .coupon_orders("493082", CouponOrderType::Settled)
688 .await
689 .expect_err("bank card id passed as a coupon id");
690 assert!(
691 err.to_string().contains("32-character coupon id")
692 && err.to_string().contains("looks like a bank card id"),
693 "{err}"
694 );
695 let err = ctx
696 .coupon_orders("zz", CouponOrderType::Settled)
697 .await
698 .expect_err("not hex");
699 assert!(!err.to_string().contains("bank card"), "no hint: {err}");
700 }
701
702 #[tokio::test(flavor = "multi_thread")]
704 async fn withdrawals_report_a_full_page() {
705 use tokio::io::{AsyncReadExt, AsyncWriteExt};
706
707 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
708 .await
709 .expect("bind a local port");
710 let addr = listener.local_addr().expect("local address");
711 let server = tokio::spawn(async move {
712 let mut lines = Vec::new();
713 for count in [50, 3] {
714 let (mut socket, _) = listener.accept().await.expect("accept");
715 let mut buf = vec![0u8; 8192];
716 let n = socket.read(&mut buf).await.expect("read request");
717 let items = vec![r#"{"id":"w"}"#; count].join(",");
718 let body =
719 format!(r#"{{"code":0,"message":"","data":{{"list":[{items}],"total":99}}}}"#);
720 let reply = format!(
721 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
722 body.len()
723 );
724 socket.write_all(reply.as_bytes()).await.expect("reply");
725 let request = String::from_utf8_lossy(&buf[..n]).to_string();
726 lines.push(request.lines().next().unwrap_or_default().to_string());
727 }
728 lines
729 });
730 let config = Arc::new(
731 Config::from_apikey("app_key", "app_secret", "opaque")
732 .http_url(format!("http://{addr}")),
733 );
734 let ctx = AssetContext::new(config);
735 let full = ctx
736 .withdrawals(GetWithdrawalsOptions::new().size(80))
737 .await
738 .expect("withdrawals");
739 assert!(full.has_more, "size 80 is sent as 50, and 50 came back");
740 assert_eq!(full.total, 99, "total kept");
741 let short = ctx.withdrawals(None).await.expect("withdrawals");
742 assert!(!short.has_more, "3 of the default 20");
743 let lines = server.await.expect("server task");
744 assert!(
745 lines[0].contains("size=50"),
746 "capped size sent: {}",
747 lines[0]
748 );
749 assert!(
750 lines[1].contains("size=20"),
751 "default size sent: {}",
752 lines[1]
753 );
754 }
755
756 #[tokio::test(flavor = "multi_thread")]
758 async fn account_endpoints_reject_us_token() {
759 let config = Arc::new(Config::from_apikey("us_app_key", "app_secret", "us_token"));
760 let ctx = AssetContext::new(config);
761 match ctx.bank_cards().await {
762 Err(Error::HttpClient(HttpClientError::DcRegionRestricted {
763 path, required, ..
764 })) => {
765 assert_eq!(path, core::BANK_CARDS_PATH, "restricted path mismatch");
766 assert_eq!(required, DcRegion::Ap, "expected AP-only restriction");
767 }
768 other => panic!("expected DcRegionRestricted, got {other:?}"),
769 }
770 match ctx.deposits(None).await {
771 Err(Error::HttpClient(HttpClientError::DcRegionRestricted { path, .. })) => {
772 assert_eq!(path, core::DEPOSITS_PATH, "restricted path mismatch");
773 }
774 other => panic!("expected DcRegionRestricted, got {other:?}"),
775 }
776 }
777}