浏览代码

准备与go进行对比,虽然是服务器上的环境,但是将就下吧

skyfffire 3 周之前
父节点
当前提交
bfb0b0c73d
共有 3 个文件被更改,包括 38 次插入9 次删除
  1. 29 8
      src/exchange/extended_rest_client.rs
  2. 4 1
      src/utils/lib.rs
  3. 5 0
      src/utils/starknet_messages.rs

+ 29 - 8
src/exchange/extended_rest_client.rs

@@ -1,10 +1,10 @@
 use std::str::FromStr;
-use chrono::Utc;
-use anyhow::{anyhow, bail, Result};
+use chrono::{Duration, Timelike, Utc};
+use anyhow::{anyhow, bail, Context, Result};
 use reqwest::Client;
 use reqwest::header::HeaderMap;
 use rust_decimal::Decimal;
-use rust_decimal::prelude::FromPrimitive;
+use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
 use rust_decimal_macros::dec;
 use serde_json::{json, Value};
 use starknet::core::types::Felt;
@@ -154,6 +154,20 @@ impl ExtendedRestClient {
     pub async fn post_order(&mut self, order_type: &str, side: &str, qty: &str, price: &str) -> Result<Response> {
         let account = self.account.clone().ok_or_else(|| anyhow!("请将账户传入再进行下单操作"))?;
 
+        // 时间戳处理
+        // 1. 获取当前时间,并增加 14 天的缓冲期
+        let now = Utc::now();
+        let expire_time_with_buffer = now + Duration::days(14);
+
+        // 2. 向上取整到秒
+        //    先截断到秒,如果原始时间在截断之后,说明有纳秒部分,需要再加一秒
+        let mut expire_time_rounded = expire_time_with_buffer.with_nanosecond(0).unwrap();
+        if expire_time_with_buffer > expire_time_rounded {
+            expire_time_rounded += Duration::seconds(1);
+        }
+        // 3. 获取 Unix 时间戳 (秒)
+        let expire_time_as_seconds = expire_time_rounded.timestamp();
+
         // 需要传给extended的参数整理
         let id = Uuid::new_v4().to_string();
         let market = self.market.as_str();
@@ -162,7 +176,7 @@ impl ExtendedRestClient {
         // qty
         // price
         let time_in_force = "GTT";
-        let expiry_epoch_millis = Utc::now().timestamp_millis() + (60 * 60 * 1000);
+        let expiry_epoch_millis = expire_time_rounded.timestamp_millis();
         let nonce_u32: u32 = rand::random();
         let nonce = nonce_u32.to_string();
         let self_trade_protection_level = "ACCOUNT";
@@ -211,12 +225,18 @@ impl ExtendedRestClient {
         // 其余参数
         let position_id = format!("{}", account.vault_number);
         let base_asset_id_hex = l2_config.get("syntheticId").unwrap().as_str().unwrap().to_string();
-        let base_amount = stark_synthetic_amount.to_string();
+        let base_amount = stark_synthetic_amount.to_i64()
+            .context("stark_synthetic_amount 无法转换为 i64")?
+            .to_string();
         let quote_asset_id_hex = l2_config.get("collateralId").unwrap().as_str().unwrap().to_string();
-        let quote_amount = stark_collateral_amount.to_string();
+        let quote_amount = stark_collateral_amount.to_i64()
+            .context("stark_collateral_amount 无法转换为 i64")?
+            .to_string();
         let fee_asset_id_hex = l2_config.get("collateralId").unwrap().as_str().unwrap().to_string();
-        let fee_amount = stark_fee_part.to_string();
-        let expiration = format!("{}", (expiry_epoch_millis / 1000) as u64);
+        let fee_amount = stark_fee_part.to_u64() // Fee 通常是正数
+            .context("stark_fee_part 无法转换为 u64")?
+            .to_string();
+        let expiration = expire_time_as_seconds.to_string();
         let salt = nonce.clone();
         let user_public_key_hex = account.stark_public_key.clone();
         let domain_name = "Perpetuals".to_string();
@@ -491,6 +511,7 @@ mod tests {
     async fn test_create_order() {
         let _guard = setup_logging().unwrap();
         let mut client = get_client().await;
+        info!("{}", serde_json::to_string_pretty(&client.market_info).unwrap());
         let response_result = client.post_order("LIMIT", "BUY", "0.0001", "100000").await;
 
         match response_result {

+ 4 - 1
src/utils/lib.rs

@@ -4,7 +4,7 @@ use sha2::{Digest, Sha256};
 use starknet::core::crypto::ecdsa_sign;
 use starknet::core::types::Felt;
 use std::str::FromStr;
-
+use tracing::info;
 use crate::utils::starknet_messages::{
     AssetId, OffChainMessage, Order, PositionId, StarknetDomain, Timestamp, TransferArgs,
 };
@@ -139,6 +139,9 @@ pub fn get_order_hash(
         chain_id: domain_chain_id,
         revision,
     };
+    
+    info!("{:?}", order);
+    info!("{:?}", domain);
     order
         .message_hash(&domain, user_key)
         .map_err(|e| format!("Failed to compute message hash: {:?}", e))

+ 5 - 0
src/utils/starknet_messages.rs

@@ -29,6 +29,7 @@ pub trait OffChainMessage: Hashable {
     }
 }
 
+#[derive(Debug)]
 pub struct StarknetDomain {
     pub name: String,
     pub version: String,
@@ -50,9 +51,11 @@ impl Hashable for StarknetDomain {
     }
 }
 
+#[derive(Debug)]
 pub struct AssetId {
     pub value: Felt,
 }
+#[derive(Debug)]
 pub struct PositionId {
     pub value: u32,
 }
@@ -62,10 +65,12 @@ pub struct AssetAmount {
     pub amount: i64,
 }
 
+#[derive(Debug)]
 pub struct Timestamp {
     pub seconds: u64,
 }
 
+#[derive(Debug)]
 pub struct Order {
     pub position_id: PositionId,
     pub base_asset_id: AssetId,