diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11fa5e55..63ea18e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,7 @@ on: - zklink_nexus - v* - devnet + - apex-devnet push: branches: - main @@ -15,6 +16,7 @@ on: - zklink_nexus - v* - devnet + - apex-devnet jobs: fmt: diff --git a/Cargo.lock b/Cargo.lock index 17fa2316..aed8697d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -755,6 +755,12 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" +[[package]] +name = "bytemuck" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15" + [[package]] name = "byteorder" version = "1.5.0" @@ -1208,7 +1214,7 @@ version = "4.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e77a43b28d0668df09411cb0bc9a8c2adc40f9a048afe863e05fd43251e8e39c" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "num_cpus", ] @@ -1224,8 +1230,8 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51aac4c99b2e6775164b412ea33ae8441b2fde2dbf05a20bc0052a63d08c475b" dependencies = [ - "proc-macro2 1.0.76", - "quote 1.0.35", + "proc-macro2", + "quote", "syn 2.0.48", ] @@ -2018,7 +2024,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd250246955bb9548a99733859946a5721289ec152de5fcc6eb03da7d3143dd1" dependencies = [ "hex", - "quote 1.0.35", + "quote", "syn 2.0.48", ] diff --git a/bindings/dart/test/main.dart b/bindings/dart/test/main.dart index 3c9e2059..4f25cbdf 100644 --- a/bindings/dart/test/main.dart +++ b/bindings/dart/test/main.dart @@ -62,6 +62,8 @@ Future main() async { print(txStr); var txJson = jsonDecode(txStr); expect(txJson["signature"]["pubKey"], "0x7b173e25e484eed3461091430f81b2a5bd7ae792f69701dcb073cb903f812510"); - expect(txJson["signature"]["signature"], "a4d48b291495bdb2505dc14c4f04931f854662c9333d7bae13bc953e852ad428b132148c47418b92c216cb555a5a5e8caaba200d204b9ef7f2fefe52e848a003"); + // apex-devnet branch sig: 4541a736a73d829e62195375edd88d7b92636f9f8209dfd267aa3fe27fd0c59104c8bf33fbf70e17a778cd9c55a71a68b4ca7eabdb264a6fc4d60cd891fa1d05 + // main branch sig: a4d48b291495bdb2505dc14c4f04931f854662c9333d7bae13bc953e852ad428b132148c47418b92c216cb555a5a5e8caaba200d204b9ef7f2fefe52e848a003 + expect(txJson["signature"]["signature"], anyOf("4541a736a73d829e62195375edd88d7b92636f9f8209dfd267aa3fe27fd0c59104c8bf33fbf70e17a778cd9c55a71a68b4ca7eabdb264a6fc4d60cd891fa1d05", "a4d48b291495bdb2505dc14c4f04931f854662c9333d7bae13bc953e852ad428b132148c47418b92c216cb555a5a5e8caaba200d204b9ef7f2fefe52e848a003")); }); } \ No newline at end of file diff --git a/bindings/sdk/src/lib.rs b/bindings/sdk/src/lib.rs index d11fa403..8693ab33 100644 --- a/bindings/sdk/src/lib.rs +++ b/bindings/sdk/src/lib.rs @@ -23,15 +23,17 @@ use zklink_sdk_types::basic_types::tx_hash::TxHash; use zklink_sdk_types::basic_types::zklink_address::ZkLinkAddress; use zklink_sdk_types::basic_types::GetBytes; use zklink_sdk_types::basic_types::{ - AccountId, BigUint, BlockNumber, ChainId, EthBlockId, MarginId, Nonce, PairId, PriorityOpId, SlotId, SubAccountId, - TimeStamp, TokenId, + AccountId, BigUint, BlockNumber, ChainId, EthBlockId, MarginId, Nonce, PairId, PriorityOpId, + SlotId, SubAccountId, TimeStamp, TokenId, }; use zklink_sdk_types::error::TypeError; use zklink_sdk_types::prelude::*; use zklink_sdk_types::tx_type::{TxTrait, ZkSignatureTrait}; use zklink_sdk_interface::error::SignError; -use zklink_sdk_interface::sign_change_pubkey::{create_signed_change_pubkey, eth_signature_of_change_pubkey}; +use zklink_sdk_interface::sign_change_pubkey::{ + create_signed_change_pubkey, eth_signature_of_change_pubkey, +}; use zklink_sdk_interface::signer::L1SignerType; use zklink_sdk_interface::signer::{L1Type, Signer}; use zklink_sdk_interface::ChangePubKeyAuthRequest; diff --git a/bindings/sdk/src/type_convert/hex_convert.rs b/bindings/sdk/src/type_convert/hex_convert.rs index 8f5f002f..a12c622e 100644 --- a/bindings/sdk/src/type_convert/hex_convert.rs +++ b/bindings/sdk/src/type_convert/hex_convert.rs @@ -1,4 +1,7 @@ -use crate::{PackedEthSignature, PackedPublicKey, PackedSignature, PubKeyHash, TxHash, UniffiCustomTypeConverter}; +use crate::{ + PackedEthSignature, PackedPublicKey, PackedSignature, PubKeyHash, TxHash, + UniffiCustomTypeConverter, +}; use zklink_sdk_signers::starknet_signer::StarkEip712Signature; macro_rules! ffi_hex_convert { diff --git a/bindings/sdk/src/type_convert/number_convert.rs b/bindings/sdk/src/type_convert/number_convert.rs index 8eedacee..689a2393 100644 --- a/bindings/sdk/src/type_convert/number_convert.rs +++ b/bindings/sdk/src/type_convert/number_convert.rs @@ -1,6 +1,6 @@ use crate::{ - AccountId, BlockNumber, ChainId, EthBlockId, MarginId, Nonce, PairId, PriorityOpId, SlotId, SubAccountId, - TimeStamp, TokenId, TypeError, UniffiCustomTypeConverter, + AccountId, BlockNumber, ChainId, EthBlockId, MarginId, Nonce, PairId, PriorityOpId, SlotId, + SubAccountId, TimeStamp, TokenId, TypeError, UniffiCustomTypeConverter, }; use zklink_sdk_signers::eth_signer::{Address, H256}; macro_rules! ffi_num_convert { diff --git a/bindings/wasm/src/json_rpc_signer.rs b/bindings/wasm/src/json_rpc_signer.rs index 98808aa7..e7f36488 100755 --- a/bindings/wasm/src/json_rpc_signer.rs +++ b/bindings/wasm/src/json_rpc_signer.rs @@ -17,14 +17,15 @@ use zklink_sdk_signers::starknet_signer::starknet_json_rpc_signer::Signer; use zklink_sdk_types::tx_type::change_pubkey::ChangePubKey as TxChangePubKey; use zklink_sdk_types::tx_type::change_pubkey::Create2Data as ChangePubKeyCreate2Data; use zklink_sdk_types::tx_type::contract::{ - AutoDeleveraging as TxAutoDeleveraging, Contract as TxContract, ContractMatching as TxContractMatching, - Funding as TxFunding, Liquidation as TxLiquidation, + AutoDeleveraging as TxAutoDeleveraging, Contract as TxContract, + ContractMatching as TxContractMatching, Funding as TxFunding, Liquidation as TxLiquidation, }; use zklink_sdk_types::tx_type::forced_exit::ForcedExit as TxForcedExit; -use zklink_sdk_types::tx_type::order_matching::{Order as TxOrder, OrderMatching as TxOrderMatching}; +use zklink_sdk_types::tx_type::order_matching::{ + Order as TxOrder, OrderMatching as TxOrderMatching, +}; use zklink_sdk_types::tx_type::transfer::Transfer as TxTransfer; use zklink_sdk_types::tx_type::withdraw::Withdraw as TxWithdraw; -use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx; #[wasm_bindgen] pub struct JsonRpcSigner { @@ -38,8 +39,16 @@ pub fn new_with_provider(provider: Provider) -> Result { } #[wasm_bindgen(js_name=newRpcSignerWithSigner)] -pub fn new_with_signer(signer: Signer, pub_key: String, chain_id: String) -> Result { - let inner = InterfaceJsonRpcSigner::new(JsonRpcProvider::Signer(signer), Some(pub_key), Some(chain_id))?; +pub fn new_with_signer( + signer: Signer, + pub_key: String, + chain_id: String, +) -> Result { + let inner = InterfaceJsonRpcSigner::new( + JsonRpcProvider::Signer(signer), + Some(pub_key), + Some(chain_id), + )?; Ok(JsonRpcSigner { inner }) } @@ -74,15 +83,23 @@ impl JsonRpcSigner { pub fn sign_change_pubkey_with_onchain(&self, tx: ChangePubKey) -> Result { let inner_tx = tx.json_value()?; let change_pubkey: TxChangePubKey = serde_wasm_bindgen::from_value(inner_tx)?; - let signature = self.inner.sign_change_pubkey_with_onchain_auth_data(change_pubkey)?; + let signature = self + .inner + .sign_change_pubkey_with_onchain_auth_data(change_pubkey)?; Ok(serde_wasm_bindgen::to_value(&signature)?) } #[wasm_bindgen(js_name=signChangePubkeyWithEthEcdsaAuth)] - pub async fn sign_change_pubkey_with_eth_ecdsa_auth(&self, tx: ChangePubKey) -> Result { + pub async fn sign_change_pubkey_with_eth_ecdsa_auth( + &self, + tx: ChangePubKey, + ) -> Result { let inner_tx = tx.json_value()?; let change_pubkey: TxChangePubKey = serde_wasm_bindgen::from_value(inner_tx)?; - let signature = self.inner.sign_change_pubkey_with_eth_ecdsa_auth(change_pubkey).await?; + let signature = self + .inner + .sign_change_pubkey_with_eth_ecdsa_auth(change_pubkey) + .await?; Ok(serde_wasm_bindgen::to_value(&signature)?) } @@ -103,7 +120,11 @@ impl JsonRpcSigner { } #[wasm_bindgen(js_name = signTransfer)] - pub async fn sign_transfer(&self, tx: Transfer, token_symbol: &str) -> Result { + pub async fn sign_transfer( + &self, + tx: Transfer, + token_symbol: &str, + ) -> Result { let inner_tx = tx.json_value()?; let transfer: TxTransfer = serde_wasm_bindgen::from_value(inner_tx)?; let signature = self.inner.sign_transfer(transfer, token_symbol).await?; @@ -127,7 +148,11 @@ impl JsonRpcSigner { } #[wasm_bindgen(js_name=signWithdraw)] - pub async fn sign_withdraw(&self, tx: Withdraw, token_symbol: &str) -> Result { + pub async fn sign_withdraw( + &self, + tx: Withdraw, + token_symbol: &str, + ) -> Result { let inner_tx = tx.json_value()?; let withdraw: TxWithdraw = serde_wasm_bindgen::from_value(inner_tx)?; let signature = self.inner.sign_withdraw(withdraw, token_symbol).await?; @@ -181,4 +206,9 @@ impl JsonRpcSigner { let signature = self.inner.sign_liquidation(liquidation)?; Ok(serde_wasm_bindgen::to_value(&signature)?) } + + #[wasm_bindgen(js_name=signMusig)] + pub fn sign_musig(&self, msg: Vec) -> Result { + Ok(self.inner.sign_musig(msg)?.into()) + } } diff --git a/bindings/wasm/src/rpc_client.rs b/bindings/wasm/src/rpc_client.rs index c8b5a469..590f8a43 100644 --- a/bindings/wasm/src/rpc_client.rs +++ b/bindings/wasm/src/rpc_client.rs @@ -23,7 +23,9 @@ use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTxType; macro_rules! rpc_request { ($method:expr,$builder:expr, $server_url:expr, $resp_type: ty) => {{ - let params = $builder.to_rpc_params().map_err(RpcError::InvalidArgument)?; + let params = $builder + .to_rpc_params() + .map_err(RpcError::InvalidArgument)?; let request = Request::new( $method.into(), params.as_ref().map(|p| p.as_ref()), @@ -88,7 +90,12 @@ impl RpcClient { let _ = builder.insert(RpcAccountQuery::from(account_query)); let _ = builder.insert(sub_account_id.map(|id| SubAccountId(id))); let _ = builder.insert(block_number.map(|number| BlockNumber(number))); - rpc_request!("getAccountSnapshot", builder, &self.server_url, AccountSnapshotResp) + rpc_request!( + "getAccountSnapshot", + builder, + &self.server_url, + AccountSnapshotResp + ) } #[wasm_bindgen(js_name=sendTransaction)] @@ -99,7 +106,8 @@ impl RpcClient { l2_signature: Option, ) -> Result { let mut builder = ArrayParams::new(); - let zklink_tx: ZkLinkTx = serde_wasm_bindgen::from_value(tx).map_err(|_e| RpcError::InvalidInputParameter)?; + let zklink_tx: ZkLinkTx = + serde_wasm_bindgen::from_value(tx).map_err(|_e| RpcError::InvalidInputParameter)?; let l1_signature = if let Some(s) = l1_signature { Some(TypesTxLayer1Signature::try_from(s)?) } else { @@ -114,13 +122,23 @@ impl RpcClient { #[wasm_bindgen(js_name=getSupportChains)] pub async fn get_support_chains(&self) -> Result { let builder = ArrayParams::new(); - rpc_request!("getSupportChains", builder, &self.server_url, Vec) + rpc_request!( + "getSupportChains", + builder, + &self.server_url, + Vec + ) } #[wasm_bindgen(js_name=getLatestBlockNumber)] pub async fn block_info(&self) -> Result { let builder = ArrayParams::new(); - rpc_request!("getLatestBlockNumber", builder, &self.server_url, BlockNumberResp) + rpc_request!( + "getLatestBlockNumber", + builder, + &self.server_url, + BlockNumberResp + ) } #[wasm_bindgen(js_name=getBlockByNumber)] @@ -150,14 +168,24 @@ impl RpcClient { let _ = builder.insert(include_tx); let _ = builder.insert(include_update); let _ = builder.insert(limit); - rpc_request!("getPendingBlock", builder, &self.server_url, Vec) + rpc_request!( + "getPendingBlock", + builder, + &self.server_url, + Vec + ) } #[wasm_bindgen(js_name=getBlockOnChainByNumber)] pub async fn block_onchain_detail(&self, block_number: u32) -> Result { let mut builder = ArrayParams::new(); let _ = builder.insert(BlockNumber(block_number)); - rpc_request!("getBlockOnChainByNumber", builder, &self.server_url, BlockOnChainResp) + rpc_request!( + "getBlockOnChainByNumber", + builder, + &self.server_url, + BlockOnChainResp + ) } #[wasm_bindgen(js_name=getAccount)] @@ -168,19 +196,37 @@ impl RpcClient { } #[wasm_bindgen(js_name=getAccountBalances)] - pub async fn account_balances(&self, account_id: u32, sub_account_id: Option) -> Result { + pub async fn account_balances( + &self, + account_id: u32, + sub_account_id: Option, + ) -> Result { let mut builder = ArrayParams::new(); let _ = builder.insert(AccountId(account_id)); let _ = builder.insert(sub_account_id.map(|id| SubAccountId(id))); - rpc_request!("getAccountBalances", builder, &self.server_url, SubAccountBalances) + rpc_request!( + "getAccountBalances", + builder, + &self.server_url, + SubAccountBalances + ) } #[wasm_bindgen(js_name=getAccountOrderSlots)] - pub async fn account_order_slots(&self, account_id: u32, sub_account_id: Option) -> Result { + pub async fn account_order_slots( + &self, + account_id: u32, + sub_account_id: Option, + ) -> Result { let mut builder = ArrayParams::new(); let _ = builder.insert(AccountId(account_id)); let _ = builder.insert(sub_account_id.map(|id| SubAccountId(id))); - rpc_request!("getAccountOrderSlots", builder, &self.server_url, SubAccountOrders) + rpc_request!( + "getAccountOrderSlots", + builder, + &self.server_url, + SubAccountOrders + ) } #[wasm_bindgen(js_name=getTokenReserve)] @@ -208,7 +254,8 @@ impl RpcClient { page_index: u64, page_size: u32, ) -> Result { - let address = ZkLinkAddress::from_hex(&address).map_err(|_e| RpcError::InvalidInputParameter)?; + let address = + ZkLinkAddress::from_hex(&address).map_err(|_e| RpcError::InvalidInputParameter)?; let mut builder = ArrayParams::new(); let _ = builder.insert(tx_type); let _ = builder.insert(address); @@ -223,20 +270,39 @@ impl RpcClient { } #[wasm_bindgen(js_name=getWithdrawTxs)] - pub async fn tx_withdraw(&self, last_tx_timestamp: u64, max_txs: u32) -> Result { + pub async fn tx_withdraw( + &self, + last_tx_timestamp: u64, + max_txs: u32, + ) -> Result { let mut builder = ArrayParams::new(); let _ = builder.insert(last_tx_timestamp); let _ = builder.insert(max_txs); - rpc_request!("getWithdrawTxs", builder, &self.server_url, Vec) + rpc_request!( + "getWithdrawTxs", + builder, + &self.server_url, + Vec + ) } #[wasm_bindgen(js_name=pullForwardTxs)] - pub async fn pull_forward_txs(&self, sub_account_id: u8, offset_id: i64, limit: i64) -> Result { + pub async fn pull_forward_txs( + &self, + sub_account_id: u8, + offset_id: i64, + limit: i64, + ) -> Result { let mut builder = ArrayParams::new(); let _ = builder.insert(SubAccountId(sub_account_id)); let _ = builder.insert(offset_id); let _ = builder.insert(limit); - rpc_request!("pullForwardTxs", builder, &self.server_url, Vec) + rpc_request!( + "pullForwardTxs", + builder, + &self.server_url, + Vec + ) } #[wasm_bindgen(js_name=getWebSocketEvents)] diff --git a/bindings/wasm/src/rpc_type_converter.rs b/bindings/wasm/src/rpc_type_converter.rs index 1007f963..8d6cbfd6 100644 --- a/bindings/wasm/src/rpc_type_converter.rs +++ b/bindings/wasm/src/rpc_type_converter.rs @@ -77,8 +77,12 @@ impl AccountQuery { impl From for RpcAccountQuery { fn from(query: AccountQuery) -> RpcAccountQuery { match query.query_type { - AccountQueryType::AccountId => RpcAccountQuery::Id(AccountId(query.query_param.parse::().unwrap())), - AccountQueryType::Address => RpcAccountQuery::Address(ZkLinkAddress::from_str(&query.query_param).unwrap()), + AccountQueryType::AccountId => { + RpcAccountQuery::Id(AccountId(query.query_param.parse::().unwrap())) + } + AccountQueryType::Address => { + RpcAccountQuery::Address(ZkLinkAddress::from_str(&query.query_param).unwrap()) + } } } } @@ -87,7 +91,10 @@ impl From for RpcAccountQuery { impl TxLayer1Signature { #[wasm_bindgen(constructor)] pub fn new(sign_type: L1SignatureType, signature: String) -> TxLayer1Signature { - TxLayer1Signature { sign_type, signature } + TxLayer1Signature { + sign_type, + signature, + } } } @@ -108,12 +115,15 @@ impl TryFrom for TypesTxLayer1Signature { fn try_from(signature: TxLayer1Signature) -> Result { match signature.sign_type { - L1SignatureType::Eth => Ok(TypesTxLayer1Signature::EthereumSignature(PackedEthSignature::from_hex( - &signature.signature, - )?)), - L1SignatureType::Eip1271 => Ok(TypesTxLayer1Signature::EIP1271Signature(EIP1271Signature( - hex::decode(signature.signature).map_err(|e| JsValue::from_str(&format!("error: {e}")))?, - ))), + L1SignatureType::Eth => Ok(TypesTxLayer1Signature::EthereumSignature( + PackedEthSignature::from_hex(&signature.signature)?, + )), + L1SignatureType::Eip1271 => { + Ok(TypesTxLayer1Signature::EIP1271Signature(EIP1271Signature( + hex::decode(signature.signature) + .map_err(|e| JsValue::from_str(&format!("error: {e}")))?, + ))) + } L1SignatureType::Stark => { let signature = StarkEip712Signature::from_hex(&signature.signature) .map_err(|e| JsValue::from_str(&format!("error: {e}")))?; diff --git a/bindings/wasm/src/signer.rs b/bindings/wasm/src/signer.rs index 88a0dfef..36549514 100644 --- a/bindings/wasm/src/signer.rs +++ b/bindings/wasm/src/signer.rs @@ -15,11 +15,13 @@ use zklink_sdk_interface::signer::Signer as InterfaceSigner; use zklink_sdk_types::tx_type::change_pubkey::ChangePubKey as TxChangePubKey; use zklink_sdk_types::tx_type::change_pubkey::Create2Data as ChangePubKeyCreate2Data; use zklink_sdk_types::tx_type::contract::{ - AutoDeleveraging as TxAutoDeleveraging, Contract as TxContract, ContractMatching as TxContractMatching, - Funding as TxFunding, Liquidation as TxLiquidation, + AutoDeleveraging as TxAutoDeleveraging, Contract as TxContract, + ContractMatching as TxContractMatching, Funding as TxFunding, Liquidation as TxLiquidation, }; use zklink_sdk_types::tx_type::forced_exit::ForcedExit as TxForcedExit; -use zklink_sdk_types::tx_type::order_matching::{Order as TxOrder, OrderMatching as TxOrderMatching}; +use zklink_sdk_types::tx_type::order_matching::{ + Order as TxOrder, OrderMatching as TxOrderMatching, +}; use zklink_sdk_types::tx_type::transfer::Transfer as TxTransfer; use zklink_sdk_types::tx_type::withdraw::Withdraw as TxWithdraw; @@ -69,15 +71,22 @@ impl Signer { pub fn sign_change_pubkey_with_onchain(&self, tx: ChangePubKey) -> Result { let inner_tx = tx.json_value()?; let change_pubkey: TxChangePubKey = serde_wasm_bindgen::from_value(inner_tx)?; - let signature = self.inner.sign_change_pubkey_with_onchain_auth_data(change_pubkey)?; + let signature = self + .inner + .sign_change_pubkey_with_onchain_auth_data(change_pubkey)?; Ok(serde_wasm_bindgen::to_value(&signature)?) } #[wasm_bindgen(js_name=signChangePubkeyWithEthEcdsaAuth)] - pub fn sign_change_pubkey_with_eth_ecdsa_auth(&self, tx: ChangePubKey) -> Result { + pub fn sign_change_pubkey_with_eth_ecdsa_auth( + &self, + tx: ChangePubKey, + ) -> Result { let inner_tx = tx.json_value()?; let change_pubkey: TxChangePubKey = serde_wasm_bindgen::from_value(inner_tx)?; - let signature = self.inner.sign_change_pubkey_with_eth_ecdsa_auth(change_pubkey)?; + let signature = self + .inner + .sign_change_pubkey_with_eth_ecdsa_auth(change_pubkey)?; Ok(serde_wasm_bindgen::to_value(&signature)?) } @@ -107,7 +116,9 @@ impl Signer { ) -> Result { let inner_tx = tx.json_value()?; let transfer: TxTransfer = serde_wasm_bindgen::from_value(inner_tx)?; - let signature = self.inner.sign_transfer(transfer, token_symbol, chain_id, addr)?; + let signature = self + .inner + .sign_transfer(transfer, token_symbol, chain_id, addr)?; Ok(serde_wasm_bindgen::to_value(&signature)?) } @@ -137,7 +148,9 @@ impl Signer { ) -> Result { let inner_tx = tx.json_value()?; let withdraw: TxWithdraw = serde_wasm_bindgen::from_value(inner_tx)?; - let signature = self.inner.sign_withdraw(withdraw, token_symbol, chain_id, addr)?; + let signature = self + .inner + .sign_withdraw(withdraw, token_symbol, chain_id, addr)?; Ok(serde_wasm_bindgen::to_value(&signature)?) } diff --git a/bindings/wasm/src/tx_types/change_pubkey.rs b/bindings/wasm/src/tx_types/change_pubkey.rs index 83ff1a19..fb5685e5 100644 --- a/bindings/wasm/src/tx_types/change_pubkey.rs +++ b/bindings/wasm/src/tx_types/change_pubkey.rs @@ -36,10 +36,14 @@ impl Create2Data { pub fn new(creator_address: &str, salt: &str, code_hash: &str) -> Result { let create2_data = ChangePubKeyCreate2Data { creator_address: ZkLinkAddress::from_hex(creator_address)?, - salt_arg: H256::from_str(&salt).map_err(|e| TypeError::DecodeFromHexErr(e.to_string()))?, - code_hash: H256::from_str(code_hash).map_err(|e| TypeError::DecodeFromHexErr(e.to_string()))?, + salt_arg: H256::from_str(&salt) + .map_err(|e| TypeError::DecodeFromHexErr(e.to_string()))?, + code_hash: H256::from_str(code_hash) + .map_err(|e| TypeError::DecodeFromHexErr(e.to_string()))?, }; - Ok(Create2Data { inner: create2_data }) + Ok(Create2Data { + inner: create2_data, + }) } #[wasm_bindgen] @@ -65,7 +69,9 @@ impl ChangePubKey { verifying_contract: String, ) -> Result { let contract = ZkLinkAddress::from_str(&verifying_contract)?; - let typed_data = self.inner.to_eip712_request_payload(layer_one_chain_id, &contract)?; + let typed_data = self + .inner + .to_eip712_request_payload(layer_one_chain_id, &contract)?; Ok(typed_data.raw_data) } } diff --git a/bindings/wasm/src/tx_types/contract/auto_deleveraging.rs b/bindings/wasm/src/tx_types/contract/auto_deleveraging.rs index 48556f07..589656f2 100644 --- a/bindings/wasm/src/tx_types/contract/auto_deleveraging.rs +++ b/bindings/wasm/src/tx_types/contract/auto_deleveraging.rs @@ -5,7 +5,8 @@ use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::error::TypeError::InvalidBigIntStr; use zklink_sdk_types::tx_builder::AutoDeleveragingBuilder as TxAutoDeleveragingBuilder; use zklink_sdk_types::tx_type::contract::{ - AutoDeleveraging as AutoDeleveragingTx, ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo, + AutoDeleveraging as AutoDeleveragingTx, ContractPrice as InnerContractPrice, + SpotPriceInfo as InnerSpotPriceInfo, }; #[wasm_bindgen] @@ -59,7 +60,8 @@ impl AutoDeleveragingBuilder { adl_account_id: adl_account_id.into(), pair_id: pair_id.into(), adl_size: BigUint::from_str(&adl_size).map_err(|e| InvalidBigIntStr(e.to_string()))?, - adl_price: BigUint::from_str(&adl_price).map_err(|e| InvalidBigIntStr(e.to_string()))?, + adl_price: BigUint::from_str(&adl_price) + .map_err(|e| InvalidBigIntStr(e.to_string()))?, fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?, fee_token: fee_token.into(), }; diff --git a/bindings/wasm/src/tx_types/contract/contract_matching.rs b/bindings/wasm/src/tx_types/contract/contract_matching.rs index e4c9473e..e6e25790 100644 --- a/bindings/wasm/src/tx_types/contract/contract_matching.rs +++ b/bindings/wasm/src/tx_types/contract/contract_matching.rs @@ -7,8 +7,8 @@ use zklink_sdk_types::tx_builder::{ ContractBuilder as TxContractBuilder, ContractMatchingBuilder as TxContractMatchingBuilder, }; use zklink_sdk_types::tx_type::contract::{ - Contract as InnerContract, ContractMatching as ContractMatchingTx, ContractPrice as InnerContractPrice, - SpotPriceInfo as InnerSpotPriceInfo, + Contract as InnerContract, ContractMatching as ContractMatchingTx, + ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo, }; #[wasm_bindgen] diff --git a/bindings/wasm/src/tx_types/contract/funding.rs b/bindings/wasm/src/tx_types/contract/funding.rs index 18d4bfcc..414af80c 100644 --- a/bindings/wasm/src/tx_types/contract/funding.rs +++ b/bindings/wasm/src/tx_types/contract/funding.rs @@ -4,7 +4,9 @@ use wasm_bindgen::JsValue; use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::error::TypeError::InvalidBigIntStr; use zklink_sdk_types::tx_builder::FundingBuilder as TxFundingBuilder; -use zklink_sdk_types::tx_type::contract::{Funding as InnerFunding, FundingInfo as InnerFundingInfo}; +use zklink_sdk_types::tx_type::contract::{ + Funding as InnerFunding, FundingInfo as InnerFundingInfo, +}; #[wasm_bindgen] pub struct FundingInfo { @@ -59,7 +61,10 @@ impl FundingBuilder { fee: String, fee_token: u16, ) -> Result { - let funding_account_ids = funding_account_ids.iter().map(|id| (*id).into()).collect::>(); + let funding_account_ids = funding_account_ids + .iter() + .map(|id| (*id).into()) + .collect::>(); let inner = TxFundingBuilder { account_id: account_id.into(), sub_account_id: sub_account_id.into(), diff --git a/bindings/wasm/src/tx_types/contract/liquidation.rs b/bindings/wasm/src/tx_types/contract/liquidation.rs index 665015bb..52d2060a 100644 --- a/bindings/wasm/src/tx_types/contract/liquidation.rs +++ b/bindings/wasm/src/tx_types/contract/liquidation.rs @@ -5,7 +5,9 @@ use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::error::TypeError::InvalidBigIntStr; use zklink_sdk_types::tx_builder::LiquidationBuilder as TxLiquidationBuilder; use zklink_sdk_types::tx_type::contract::Liquidation as LiquidationTx; -use zklink_sdk_types::tx_type::contract::{ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo}; +use zklink_sdk_types::tx_type::contract::{ + ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo, +}; #[wasm_bindgen] pub struct Liquidation { diff --git a/bindings/wasm/src/tx_types/contract/prices.rs b/bindings/wasm/src/tx_types/contract/prices.rs index 405f18f5..2410d1c7 100644 --- a/bindings/wasm/src/tx_types/contract/prices.rs +++ b/bindings/wasm/src/tx_types/contract/prices.rs @@ -3,7 +3,9 @@ use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::error::TypeError::InvalidBigIntStr; -use zklink_sdk_types::tx_type::contract::{ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo}; +use zklink_sdk_types::tx_type::contract::{ + ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo, +}; #[wasm_bindgen] pub struct ContractPrice { @@ -17,7 +19,8 @@ impl ContractPrice { Ok(ContractPrice { inner: InnerContractPrice { pair_id: pair_id.into(), - market_price: BigUint::from_str(&market_price).map_err(|e| InvalidBigIntStr(e.to_string()))?, + market_price: BigUint::from_str(&market_price) + .map_err(|e| InvalidBigIntStr(e.to_string()))?, }, }) } diff --git a/bindings/wasm/src/tx_types/contract/update_global_var.rs b/bindings/wasm/src/tx_types/contract/update_global_var.rs index 4c0adf22..8c7b648b 100644 --- a/bindings/wasm/src/tx_types/contract/update_global_var.rs +++ b/bindings/wasm/src/tx_types/contract/update_global_var.rs @@ -3,7 +3,8 @@ use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; use zklink_sdk_types::tx_builder::UpdateGlobalVarBuilder as TxUpdateGlobalVarBuilder; use zklink_sdk_types::tx_type::contract::{ - FundingInfo as InnerFundingInfo, Parameter as ContractParameter, UpdateGlobalVar as UpdateGlobalVarTx, + FundingInfo as InnerFundingInfo, Parameter as ContractParameter, + UpdateGlobalVar as UpdateGlobalVarTx, }; use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx; @@ -124,7 +125,12 @@ pub struct ContractInfo { #[wasm_bindgen] impl ContractInfo { #[wasm_bindgen(constructor)] - pub fn new(pair_id: u8, symbol: String, initial_margin_rate: u16, maintenance_margin_rate: u16) -> ContractInfo { + pub fn new( + pair_id: u8, + symbol: String, + initial_margin_rate: u16, + maintenance_margin_rate: u16, + ) -> ContractInfo { ContractInfo { pair_id, symbol, @@ -155,7 +161,8 @@ impl From for ContractParameter { } } ParameterType::MarginInfo => { - let value: MarginInfo = serde_wasm_bindgen::from_value(parameter.parameter_value).unwrap(); + let value: MarginInfo = + serde_wasm_bindgen::from_value(parameter.parameter_value).unwrap(); ContractParameter::MarginInfo { margin_id: value.margin_id.into(), token_id: value.token_id.into(), @@ -163,11 +170,13 @@ impl From for ContractParameter { } } ParameterType::FundingInfos => { - let value: Vec = serde_wasm_bindgen::from_value(parameter.parameter_value).unwrap(); + let value: Vec = + serde_wasm_bindgen::from_value(parameter.parameter_value).unwrap(); ContractParameter::FundingInfos { infos: value } } ParameterType::ContractInfo => { - let value: ContractInfo = serde_wasm_bindgen::from_value(parameter.parameter_value).unwrap(); + let value: ContractInfo = + serde_wasm_bindgen::from_value(parameter.parameter_value).unwrap(); ContractParameter::ContractInfo { pair_id: value.pair_id.into(), symbol: value.symbol, diff --git a/bindings/wasm/src/tx_types/forced_exit.rs b/bindings/wasm/src/tx_types/forced_exit.rs index 2814b631..355bbec5 100644 --- a/bindings/wasm/src/tx_types/forced_exit.rs +++ b/bindings/wasm/src/tx_types/forced_exit.rs @@ -56,7 +56,8 @@ impl ForcedExitBuilder { initiator_nonce: initiator_nonce.into(), target_sub_account_id: target_sub_account_id.into(), withdraw_to_l1, - exit_amount: BigUint::from_str(&exit_amount).map_err(|e| InvalidBigIntStr(e.to_string()))?, + exit_amount: BigUint::from_str(&exit_amount) + .map_err(|e| InvalidBigIntStr(e.to_string()))?, }; Ok(ForcedExitBuilder { inner }) } diff --git a/bindings/wasm/src/tx_types/order_matching.rs b/bindings/wasm/src/tx_types/order_matching.rs index f5f795c7..593cc04b 100644 --- a/bindings/wasm/src/tx_types/order_matching.rs +++ b/bindings/wasm/src/tx_types/order_matching.rs @@ -4,8 +4,12 @@ use wasm_bindgen::JsValue; use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::error::TypeError::InvalidBigIntStr; use zklink_sdk_types::tx_builder::OrderMatchingBuilder as TxOrderMatchingBuilder; -use zklink_sdk_types::tx_type::contract::{ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo}; -use zklink_sdk_types::tx_type::order_matching::{Order as OrderTx, OrderMatching as OrderMatchingTx}; +use zklink_sdk_types::tx_type::contract::{ + ContractPrice as InnerContractPrice, SpotPriceInfo as InnerSpotPriceInfo, +}; +use zklink_sdk_types::tx_type::order_matching::{ + Order as OrderTx, OrderMatching as OrderMatchingTx, +}; #[wasm_bindgen] pub struct Order { @@ -100,7 +104,8 @@ impl OrderMatchingBuilder { taker, fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?, fee_token: fee_token.into(), - expect_base_amount: BigUint::from_str(&expect_base_amount).map_err(|e| InvalidBigIntStr(e.to_string()))?, + expect_base_amount: BigUint::from_str(&expect_base_amount) + .map_err(|e| InvalidBigIntStr(e.to_string()))?, maker, expect_quote_amount: BigUint::from_str(&expect_quote_amount) .map_err(|e| InvalidBigIntStr(e.to_string()))?, diff --git a/bindings/wasm/src/tx_types/withdraw.rs b/bindings/wasm/src/tx_types/withdraw.rs index 158d4ade..0f50c62a 100644 --- a/bindings/wasm/src/tx_types/withdraw.rs +++ b/bindings/wasm/src/tx_types/withdraw.rs @@ -48,7 +48,10 @@ impl WithdrawBuilder { Instant::now().elapsed().as_secs() as u32 }; let call_data = if let Some(call_data) = call_data { - Some(hex::decode(call_data.trim_start_matches("0x")).map_err(|e| DecodeFromHexErr(e.to_string()))?) + Some( + hex::decode(call_data.trim_start_matches("0x")) + .map_err(|e| DecodeFromHexErr(e.to_string()))?, + ) } else { None }; diff --git a/bindings/wasm/src/utils.rs b/bindings/wasm/src/utils.rs index c3688aaa..39a0c395 100644 --- a/bindings/wasm/src/utils.rs +++ b/bindings/wasm/src/utils.rs @@ -1,13 +1,16 @@ use std::str::FromStr; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; -use zklink_sdk_types::basic_types::pack::{closest_packable_fee_amount, closest_packable_token_amount}; +use zklink_sdk_types::basic_types::pack::{ + closest_packable_fee_amount, closest_packable_token_amount, +}; use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::error::TypeError; #[wasm_bindgen(js_name=closestPackableTransactionAmount)] pub fn closest_packable_transaction_amount(amount: &str) -> Result { - let amount = BigUint::from_str(amount).map_err(|e| TypeError::InvalidBigIntStr(e.to_string()))?; + let amount = + BigUint::from_str(amount).map_err(|e| TypeError::InvalidBigIntStr(e.to_string()))?; let packable_amount = closest_packable_token_amount(&amount); Ok(packable_amount.to_string()) } diff --git a/bindings/wasm/src/wallet.rs b/bindings/wasm/src/wallet.rs index 69fea464..34ac46bd 100644 --- a/bindings/wasm/src/wallet.rs +++ b/bindings/wasm/src/wallet.rs @@ -46,19 +46,26 @@ impl EthTxOption { gas_price: Option, ) -> Result { let value = if let Some(v) = value { - Some(BigUint::from_str(&v).map_err(|error| JsValue::from_str(&format!("error: {error}")))?) + Some( + BigUint::from_str(&v) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?, + ) } else { None }; let gas_price = if let Some(g) = gas_price { - Some(BigUint::from_str(&g).map_err(|error| JsValue::from_str(&format!("error: {error}")))?) + Some( + BigUint::from_str(&g) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?, + ) } else { None }; let inner = InnerEthTxOption { is_support_eip1559, - to: ZkLinkAddress::from_str(&to).map_err(|error| JsValue::from_str(&format!("error: {error}")))?, + to: ZkLinkAddress::from_str(&to) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?, nonce: nonce.map(|n| n as u64), value, gas: gas.map(|g| g as u64), @@ -92,7 +99,11 @@ impl Wallet { } #[wasm_bindgen(js_name=getNonce)] - pub async fn get_nonce(&self, block_number: BlockNumber, block: Option) -> Result { + pub async fn get_nonce( + &self, + block_number: BlockNumber, + block: Option, + ) -> Result { let block_number = if matches!(block_number, BlockNumber::Number) { format!("{}", block.unwrap_or_default()) } else { @@ -104,7 +115,8 @@ impl Wallet { #[wasm_bindgen(js_name=getDepositFee)] pub async fn get_deposit_fee(&self, eth_params: EthTxOption) -> Result { - let eth_params: InnerEthTxOption = serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); + let eth_params: InnerEthTxOption = + serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); let fee = self.inner.get_fee(eth_params).await?; Ok(fee.to_string()) } @@ -115,7 +127,8 @@ impl Wallet { tx_hash: String, timeout: Option, ) -> Result { - let tx_hash = H256::from_str(&tx_hash).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let tx_hash = H256::from_str(&tx_hash) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; let status = self.inner.wait_for_transaction(tx_hash, timeout).await?; Ok(status) } @@ -127,11 +140,16 @@ impl Wallet { amount: String, eth_params: EthTxOption, ) -> Result { - let contract = - ZkLinkAddress::from_str(&contract).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; - let amount = BigUint::from_str(&amount).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; - let eth_params: InnerEthTxOption = serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); - let tx_hash = self.inner.approve_erc20(contract, amount, eth_params).await?; + let contract = ZkLinkAddress::from_str(&contract) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let amount = BigUint::from_str(&amount) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let eth_params: InnerEthTxOption = + serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); + let tx_hash = self + .inner + .approve_erc20(contract, amount, eth_params) + .await?; Ok(hex::encode(tx_hash.as_bytes())) } @@ -146,19 +164,35 @@ impl Wallet { eth_params: EthTxOption, is_gateway: bool, ) -> Result { - let deposit_to = - ZkLinkAddress::from_str(&deposit_to).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; - let token_addr = - ZkLinkAddress::from_str(&token_addr).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; - let amount = BigUint::from_str(&amount).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; - let eth_params: InnerEthTxOption = serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); + let deposit_to = ZkLinkAddress::from_str(&deposit_to) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let token_addr = ZkLinkAddress::from_str(&token_addr) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let amount = BigUint::from_str(&amount) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let eth_params: InnerEthTxOption = + serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); let tx_hash = if !is_gateway { self.inner - .deposit_erc20_to_layer1(sub_account_id, deposit_to, token_addr, amount, mapping, eth_params) + .deposit_erc20_to_layer1( + sub_account_id, + deposit_to, + token_addr, + amount, + mapping, + eth_params, + ) .await? } else { self.inner - .deposit_erc20_to_gateway(sub_account_id, deposit_to, token_addr, amount, mapping, eth_params) + .deposit_erc20_to_gateway( + sub_account_id, + deposit_to, + token_addr, + amount, + mapping, + eth_params, + ) .await? }; Ok(hex::encode(tx_hash.as_bytes())) @@ -172,9 +206,10 @@ impl Wallet { eth_params: EthTxOption, is_gateway: bool, ) -> Result { - let deposit_to = - ZkLinkAddress::from_str(&deposit_to).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; - let eth_params: InnerEthTxOption = serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); + let deposit_to = ZkLinkAddress::from_str(&deposit_to) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let eth_params: InnerEthTxOption = + serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); let tx_hash = if !is_gateway { self.inner .deposit_eth_to_layer1(sub_account_id, deposit_to, eth_params) @@ -194,9 +229,10 @@ impl Wallet { new_pubkey_hash: String, eth_params: EthTxOption, ) -> Result { - let eth_params: InnerEthTxOption = serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); - let new_pubkey_hash = - PubKeyHash::from_hex(&new_pubkey_hash).map_err(|error| JsValue::from_str(&format!("error: {error}")))?; + let eth_params: InnerEthTxOption = + serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); + let new_pubkey_hash = PubKeyHash::from_hex(&new_pubkey_hash) + .map_err(|error| JsValue::from_str(&format!("error: {error}")))?; let tx_hash = self .inner .set_auth_pubkey_hash(nonce as u64, new_pubkey_hash, eth_params) @@ -213,7 +249,8 @@ impl Wallet { mapping: bool, eth_params: EthTxOption, ) -> Result { - let eth_params: InnerEthTxOption = serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); + let eth_params: InnerEthTxOption = + serde_wasm_bindgen::from_value(eth_params.json_value().unwrap()).unwrap(); let tx_hash = self .inner .full_exit(account_id, sub_account_id, token_id, mapping, eth_params) diff --git a/bindings/wasm/tests/test_rpc.rs b/bindings/wasm/tests/test_rpc.rs index d6af65b6..96d5516a 100644 --- a/bindings/wasm/tests/test_rpc.rs +++ b/bindings/wasm/tests/test_rpc.rs @@ -14,7 +14,9 @@ use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx as TypesZkLinkTx; use zklink_sdk_types::tx_type::ZkSignatureTrait; use zklink_sdk_wasm::rpc_client::RpcClient; use zklink_sdk_wasm::rpc_type_converter::{AccountQuery, AccountQueryType}; -use zklink_sdk_wasm::utils::{closest_packable_transaction_amount, closest_packable_transaction_fee}; +use zklink_sdk_wasm::utils::{ + closest_packable_transaction_amount, closest_packable_transaction_fee, +}; wasm_bindgen_test_configure!(run_in_worker); #[wasm_bindgen_test] @@ -93,9 +95,14 @@ async fn test_send_change_pubkey() { }; let change_pubkey = ChangePubKey::new(builder); let message = change_pubkey - .to_eip712_request_payload(l1_client_id, &ZkLinkAddress::from_str(&main_contract).unwrap()) + .to_eip712_request_payload( + l1_client_id, + &ZkLinkAddress::from_str(&main_contract).unwrap(), + ) + .unwrap(); + let signature = eth_signer + .sign_message(message.raw_data.as_bytes()) .unwrap(); - let signature = eth_signer.sign_message(message.raw_data.as_bytes()).unwrap(); let builder_with_sig = ChangePubKeyBuilder { chain_id: ChainId(1), account_id: AccountId(10), diff --git a/interface/src/json_rpc_signer.rs b/interface/src/json_rpc_signer.rs index 94e40d21..df90f19d 100755 --- a/interface/src/json_rpc_signer.rs +++ b/interface/src/json_rpc_signer.rs @@ -6,7 +6,9 @@ use crate::sign_forced_exit::sign_forced_exit; use crate::sign_order_matching::sign_order_matching; use crate::sign_transfer::{sign_eth_transfer, sign_starknet_transfer}; use crate::sign_withdraw::{sign_eth_withdraw, sign_starknet_withdraw}; -use zklink_sdk_signers::eth_signer::json_rpc_signer::{JsonRpcSigner as EthJsonRpcSigner, Provider}; +use zklink_sdk_signers::eth_signer::json_rpc_signer::{ + JsonRpcSigner as EthJsonRpcSigner, Provider, +}; use zklink_sdk_signers::starknet_signer::starknet_json_rpc_signer::{ Signer as StarknetAccountSigner, StarknetJsonRpcSigner, }; @@ -19,10 +21,12 @@ use zklink_sdk_signers::starknet_signer::error::StarkSignerError; use zklink_sdk_signers::starknet_signer::StarkEip712Signature; use zklink_sdk_signers::zklink_signer::ZkLinkSigner; use zklink_sdk_types::basic_types::GetBytes; -use zklink_sdk_types::prelude::PackedEthSignature; +use zklink_sdk_types::prelude::{PackedEthSignature, ZkLinkSignature}; use zklink_sdk_types::signatures::TxSignature; use zklink_sdk_types::tx_type::change_pubkey::{ChangePubKey, ChangePubKeyAuthData, Create2Data}; -use zklink_sdk_types::tx_type::contract::{AutoDeleveraging, Contract, ContractMatching, Funding, Liquidation}; +use zklink_sdk_types::tx_type::contract::{ + AutoDeleveraging, Contract, ContractMatching, Funding, Liquidation, +}; use zklink_sdk_types::tx_type::forced_exit::ForcedExit; use zklink_sdk_types::tx_type::order_matching::{Order, OrderMatching}; use zklink_sdk_types::tx_type::transfer::Transfer; @@ -51,12 +55,12 @@ impl JsonRpcSigner { chain_id: Option, ) -> Result { let eth_json_rpc_signer = match provider { - JsonRpcProvider::Provider(provider) => Layer1JsonRpcSigner::EthSigner(EthJsonRpcSigner::new(provider)), - JsonRpcProvider::Signer(signer) => Layer1JsonRpcSigner::StarknetSigner(StarknetJsonRpcSigner::new( - signer, - pub_key.unwrap(), - chain_id.unwrap(), - )), + JsonRpcProvider::Provider(provider) => { + Layer1JsonRpcSigner::EthSigner(EthJsonRpcSigner::new(provider)) + } + JsonRpcProvider::Signer(signer) => Layer1JsonRpcSigner::StarknetSigner( + StarknetJsonRpcSigner::new(signer, pub_key.unwrap(), chain_id.unwrap()), + ), }; let default_zklink_signer = ZkLinkSigner::new()?; Ok(Self { @@ -82,7 +86,9 @@ impl JsonRpcSigner { } } else { match &self.layer1_signer { - Layer1JsonRpcSigner::EthSigner(signer) => ZkLinkSigner::new_from_eth_rpc_signer(signer).await?, + Layer1JsonRpcSigner::EthSigner(signer) => { + ZkLinkSigner::new_from_eth_rpc_signer(signer).await? + } Layer1JsonRpcSigner::StarknetSigner(signer) => { ZkLinkSigner::new_from_starknet_rpc_signer(signer).await? } @@ -114,7 +120,11 @@ impl JsonRpcSigner { self.signature_seed.clone() } - pub async fn sign_transfer(&self, tx: Transfer, token_symbol: &str) -> Result { + pub async fn sign_transfer( + &self, + tx: Transfer, + token_symbol: &str, + ) -> Result { match &self.layer1_signer { Layer1JsonRpcSigner::EthSigner(signer) => { sign_eth_transfer(signer, &self.zklink_signer, tx, token_symbol).await @@ -126,7 +136,10 @@ impl JsonRpcSigner { } #[inline] - pub fn sign_change_pubkey_with_onchain_auth_data(&self, tx: ChangePubKey) -> Result { + pub fn sign_change_pubkey_with_onchain_auth_data( + &self, + tx: ChangePubKey, + ) -> Result { do_sign_change_pubkey_with_onchain_auth_data(tx, &self.zklink_signer) } @@ -140,7 +153,10 @@ impl JsonRpcSigner { } #[inline] - pub async fn sign_change_pubkey_with_eth_ecdsa_auth(&self, mut tx: ChangePubKey) -> Result { + pub async fn sign_change_pubkey_with_eth_ecdsa_auth( + &self, + mut tx: ChangePubKey, + ) -> Result { tx.sign(&self.zklink_signer)?; let should_valid = tx.is_signature_valid(); assert!(should_valid); @@ -148,10 +164,14 @@ impl JsonRpcSigner { // create auth data let eth_sign_msg = ChangePubKey::get_eth_sign_msg(&tx.new_pk_hash, tx.nonce, tx.account_id); let eth_signature = match &self.layer1_signer { - Layer1JsonRpcSigner::EthSigner(signer) => signer.sign_message(eth_sign_msg.as_bytes()).await?, + Layer1JsonRpcSigner::EthSigner(signer) => { + signer.sign_message(eth_sign_msg.as_bytes()).await? + } Layer1JsonRpcSigner::StarknetSigner(_) => { //starknet only support change_pubkey_onchain - return Err(StarkSignerError::SignError("Not support for starknet".to_string()).into()); + return Err( + StarkSignerError::SignError("Not support for starknet".to_string()).into(), + ); } }; @@ -163,13 +183,18 @@ impl JsonRpcSigner { }) } - pub async fn sign_withdraw(&self, tx: Withdraw, l2_source_token_symbol: &str) -> Result { + pub async fn sign_withdraw( + &self, + tx: Withdraw, + l2_source_token_symbol: &str, + ) -> Result { match &self.layer1_signer { Layer1JsonRpcSigner::EthSigner(signer) => { sign_eth_withdraw(signer, &self.zklink_signer, tx, l2_source_token_symbol).await } Layer1JsonRpcSigner::StarknetSigner(signer) => { - sign_starknet_withdraw(signer, &self.zklink_signer, tx, l2_source_token_symbol).await + sign_starknet_withdraw(signer, &self.zklink_signer, tx, l2_source_token_symbol) + .await } } } @@ -218,4 +243,9 @@ impl JsonRpcSigner { contract.signature = self.zklink_signer.sign_musig(&contract.get_bytes())?; Ok(contract) } + + #[inline] + pub fn sign_musig(&self, msg: Vec) -> Result { + Ok(self.zklink_signer.sign_musig(&msg)?) + } } diff --git a/interface/src/sign_change_pubkey.rs b/interface/src/sign_change_pubkey.rs index fda063b4..f3f2af21 100644 --- a/interface/src/sign_change_pubkey.rs +++ b/interface/src/sign_change_pubkey.rs @@ -113,15 +113,21 @@ mod test { #[test] fn test_check_create2() { - let creator_address = ZkLinkAddress::from_hex("0x6E253C951A40fAf4032faFbEc19262Cd1531A5F5").unwrap(); - let salt_arg = H256::from_str("0x0000000000000000000000000000000000000000000000000000000000000000").unwrap(); - let code_hash = H256::from_str("0x4f063cd4b2e3a885f61fefb0988cc12487182c4f09ff5de374103f5812f33fe7").unwrap(); + let creator_address = + ZkLinkAddress::from_hex("0x6E253C951A40fAf4032faFbEc19262Cd1531A5F5").unwrap(); + let salt_arg = + H256::from_str("0x0000000000000000000000000000000000000000000000000000000000000000") + .unwrap(); + let code_hash = + H256::from_str("0x4f063cd4b2e3a885f61fefb0988cc12487182c4f09ff5de374103f5812f33fe7") + .unwrap(); let create2_data = Create2Data { creator_address, code_hash, salt_arg, }; - let from_account = ZkLinkAddress::from_hex("0x4504d5BE8634e3896d42784A5aB89fc41C3d4511").unwrap(); + let from_account = + ZkLinkAddress::from_hex("0x4504d5BE8634e3896d42784A5aB89fc41C3d4511").unwrap(); let eth_private_key = "43be0b8bdeccb5a13741c8fd076bf2619bfc9f6dcc43ad6cf965ab489e156ced"; let zk_signer = ZkLinkSigner::new_from_hex_eth_signer(eth_private_key).unwrap(); diff --git a/interface/src/sign_forced_exit.rs b/interface/src/sign_forced_exit.rs index afed2b0e..188c98e7 100644 --- a/interface/src/sign_forced_exit.rs +++ b/interface/src/sign_forced_exit.rs @@ -3,7 +3,10 @@ use zklink_sdk_signers::zklink_signer::pk_signer::ZkLinkSigner; use zklink_sdk_types::prelude::{GetBytes, TxSignature}; use zklink_sdk_types::tx_type::forced_exit::ForcedExit; -pub fn sign_forced_exit(zklink_signer: &ZkLinkSigner, mut tx: ForcedExit) -> Result { +pub fn sign_forced_exit( + zklink_signer: &ZkLinkSigner, + mut tx: ForcedExit, +) -> Result { tx.signature = zklink_signer.sign_musig(&tx.get_bytes())?; Ok(TxSignature { tx: tx.into(), diff --git a/interface/src/sign_funding.rs b/interface/src/sign_funding.rs index 7f1e0fcb..20170544 100644 --- a/interface/src/sign_funding.rs +++ b/interface/src/sign_funding.rs @@ -2,7 +2,10 @@ use zklink_sdk_signers::zklink_signer::pk_signer::ZkLinkSigner; use zklink_sdk_signers::zklink_signer::ZkSignerError; use zklink_sdk_types::prelude::{Funding, GetBytes, TxSignature}; -pub fn sign_funding(zklink_signer: &ZkLinkSigner, mut tx: Funding) -> Result { +pub fn sign_funding( + zklink_signer: &ZkLinkSigner, + mut tx: Funding, +) -> Result { tx.signature = zklink_signer.sign_musig(&tx.get_bytes())?; Ok(TxSignature { tx: tx.into(), diff --git a/interface/src/sign_liquidation.rs b/interface/src/sign_liquidation.rs index 7cbb56b3..b51a085f 100644 --- a/interface/src/sign_liquidation.rs +++ b/interface/src/sign_liquidation.rs @@ -2,7 +2,10 @@ use zklink_sdk_signers::zklink_signer::pk_signer::ZkLinkSigner; use zklink_sdk_signers::zklink_signer::ZkSignerError; use zklink_sdk_types::prelude::{GetBytes, Liquidation, TxSignature}; -pub fn sign_liquidation(zklink_signer: &ZkLinkSigner, mut tx: Liquidation) -> Result { +pub fn sign_liquidation( + zklink_signer: &ZkLinkSigner, + mut tx: Liquidation, +) -> Result { tx.signature = zklink_signer.sign_musig(&tx.get_bytes())?; Ok(TxSignature { tx: tx.into(), diff --git a/interface/src/sign_order_matching.rs b/interface/src/sign_order_matching.rs index 202018f4..7905af7c 100644 --- a/interface/src/sign_order_matching.rs +++ b/interface/src/sign_order_matching.rs @@ -4,7 +4,10 @@ use zklink_sdk_types::basic_types::GetBytes; use zklink_sdk_types::prelude::TxSignature; use zklink_sdk_types::tx_type::order_matching::OrderMatching; -pub fn sign_order_matching(zklink_signer: &ZkLinkSigner, mut tx: OrderMatching) -> Result { +pub fn sign_order_matching( + zklink_signer: &ZkLinkSigner, + mut tx: OrderMatching, +) -> Result { tx.signature = zklink_signer.sign_musig(&tx.get_bytes())?; Ok(TxSignature { tx: tx.into(), diff --git a/interface/src/sign_transfer.rs b/interface/src/sign_transfer.rs index ce7a892c..0a3331dc 100644 --- a/interface/src/sign_transfer.rs +++ b/interface/src/sign_transfer.rs @@ -79,7 +79,10 @@ pub fn sign_starknet_transfer( ) -> Result { tx.signature = zklink_signer.sign_musig(&tx.get_bytes())?; let message = tx.get_starknet_sign_msg(token_symbol); - let typed_data = TypedData::new(TypedDataMessage::Transaction { message }, chain_id.to_string()); + let typed_data = TypedData::new( + TypedDataMessage::Transaction { message }, + chain_id.to_string(), + ); let starknet_signature = signer.sign_message(&typed_data, addr)?; Ok(TxSignature { @@ -103,7 +106,8 @@ mod tests { account_id: AccountId(1), from_sub_account_id: SubAccountId(1), to_sub_account_id: SubAccountId(1), - to_address: ZkLinkAddress::from_str("0x0000000000000000000000000000000000000000").unwrap(), + to_address: ZkLinkAddress::from_str("0x0000000000000000000000000000000000000000") + .unwrap(), token: TokenId(1), amount: BigUint::from_str("1000000000000000000").unwrap(), fee: BigUint::from_str("10000000000").unwrap(), @@ -113,7 +117,9 @@ mod tests { let tx = builder.build(); let signature = sign_eth_transfer(ð_signer, &zk_signer, tx, "USD").unwrap(); - let eth_sign = signature.layer1_signature.expect("transfer must has eth signature"); + let eth_sign = signature + .layer1_signature + .expect("transfer must has eth signature"); if let TxLayer1Signature::EthereumSignature(eth_sign) = eth_sign { assert_eq!(eth_sign.as_hex(), "0x08c9cd25416c871a153e9d51385c28413311e8ed055a195e4f5e8c229244e1a05bab15a9e6eb1cff9a5d237d878c41553215341742779745574a631d89e09a831b"); } diff --git a/interface/src/sign_withdraw.rs b/interface/src/sign_withdraw.rs index 7683bcc4..777376d2 100644 --- a/interface/src/sign_withdraw.rs +++ b/interface/src/sign_withdraw.rs @@ -25,7 +25,10 @@ pub fn sign_starknet_withdraw( ) -> Result { tx.sign(zklink_singer)?; let message = tx.get_starknet_sign_msg(l2_source_token_symbol); - let typed_data = TypedData::new(TypedDataMessage::Transaction { message }, chain_id.to_string()); + let typed_data = TypedData::new( + TypedDataMessage::Transaction { message }, + chain_id.to_string(), + ); let signature = signer.sign_message(&typed_data, addr)?; Ok(TxSignature { @@ -100,7 +103,8 @@ mod tests { account_id: AccountId(1), to_chain_id: ChainId(3), sub_account_id: SubAccountId(1), - to_address: ZkLinkAddress::from_str("0x3d809e414ba4893709c85f242ba3617481bc4126").unwrap(), + to_address: ZkLinkAddress::from_str("0x3d809e414ba4893709c85f242ba3617481bc4126") + .unwrap(), l2_source_token: TokenId(1), l1_target_token: TokenId(17), amount: BigUint::from_str("99995900000000000000").unwrap(), diff --git a/interface/src/signer.rs b/interface/src/signer.rs index 41f76cd5..309b62c8 100644 --- a/interface/src/signer.rs +++ b/interface/src/signer.rs @@ -1,17 +1,16 @@ use crate::error::SignError; use crate::sign_auto_deleveraging::sign_auto_deleveraging; -use crate::sign_forced_exit::sign_forced_exit; -use crate::sign_liquidation::sign_liquidation; -use crate::sign_transfer::{sign_eth_transfer, sign_starknet_transfer}; -use crate::sign_withdraw::{sign_eth_withdraw, sign_starknet_withdraw}; -use zklink_sdk_types::prelude::{PubKeyHash, TxSignature, ZkLinkSignature}; use crate::sign_change_pubkey::{ do_sign_change_pubkey_with_create2data_auth, do_sign_change_pubkey_with_eth_ecdsa_auth, do_sign_change_pubkey_with_onchain_auth_data, }; use crate::sign_contract_matching::sign_contract_matching; +use crate::sign_forced_exit::sign_forced_exit; use crate::sign_funding::sign_funding; +use crate::sign_liquidation::sign_liquidation; use crate::sign_order_matching::sign_order_matching; +use crate::sign_transfer::{sign_eth_transfer, sign_starknet_transfer}; +use crate::sign_withdraw::{sign_eth_withdraw, sign_starknet_withdraw}; use cfg_if::cfg_if; #[cfg(feature = "ffi")] use std::sync::Arc; @@ -23,6 +22,7 @@ use zklink_sdk_signers::zklink_signer::pk_signer::ZkLinkSigner; use zklink_sdk_signers::zklink_signer::public_key::PackedPublicKey; #[cfg(not(feature = "ffi"))] use zklink_sdk_types::prelude::{Contract, GetBytes, Order}; +use zklink_sdk_types::prelude::{PubKeyHash, TxSignature, ZkLinkSignature}; use zklink_sdk_types::tx_type::change_pubkey::Create2Data; cfg_if! { @@ -65,15 +65,18 @@ impl Signer { pub fn new(private_key: &str, l1_signer_type: L1SignerType) -> Result { let (zklink_signer, layer1_signer) = match l1_signer_type { L1SignerType::Eth { .. } => { - let eth_signer = EthSigner::try_from(private_key).map_err(|_| EthSignerError::InvalidEthSigner)?; + let eth_signer = EthSigner::try_from(private_key) + .map_err(|_| EthSignerError::InvalidEthSigner)?; ( ZkLinkSigner::new_from_hex_eth_signer(private_key)?, Layer1Sginer::EthSigner(eth_signer), ) } - L1SignerType::Starknet { chain_id, address, .. } => { - let stark_signer = - StarkSigner::new_from_hex_str(private_key).map_err(|_| StarkSignerError::InvalidStarknetSigner)?; + L1SignerType::Starknet { + chain_id, address, .. + } => { + let stark_signer = StarkSigner::new_from_hex_str(private_key) + .map_err(|_| StarkSignerError::InvalidStarknetSigner)?; ( ZkLinkSigner::new_from_hex_stark_signer(private_key, &address, &chain_id)?, Layer1Sginer::StarknetSigner(stark_signer), @@ -108,7 +111,10 @@ impl Signer { } #[inline] - pub fn sign_change_pubkey_with_onchain_auth_data(&self, tx: ChangePubKey) -> Result { + pub fn sign_change_pubkey_with_onchain_auth_data( + &self, + tx: ChangePubKey, + ) -> Result { #[cfg(feature = "ffi")] let tx = (*tx).clone(); do_sign_change_pubkey_with_onchain_auth_data(tx, &self.zklink_signer) @@ -116,7 +122,10 @@ impl Signer { #[cfg(not(feature = "web"))] #[inline] - pub fn sign_change_pubkey_with_eth_ecdsa_auth(&self, tx: ChangePubKey) -> Result { + pub fn sign_change_pubkey_with_eth_ecdsa_auth( + &self, + tx: ChangePubKey, + ) -> Result { #[cfg(feature = "ffi")] let tx = (*tx).clone(); if let Layer1Sginer::EthSigner(signer) = &self.layer1_signer { @@ -137,15 +146,24 @@ impl Signer { #[cfg(feature = "ffi")] let tx = (*tx).clone(); match &self.layer1_signer { - Layer1Sginer::EthSigner(signer) => sign_eth_transfer(signer, &self.zklink_signer, tx, token_symbol), + Layer1Sginer::EthSigner(signer) => { + sign_eth_transfer(signer, &self.zklink_signer, tx, token_symbol) + } Layer1Sginer::StarknetSigner(signer) => { - let chain_id = starknet_chain_id.ok_or(SignError::StarkSigningError(StarkSignerError::SignError( - "Invalid starknet_chain_id".to_string(), - )))?; - let addr = starknet_addr.ok_or(SignError::StarkSigningError(StarkSignerError::SignError( - "Invalid starknet_addr".to_string(), - )))?; - sign_starknet_transfer(signer, &self.zklink_signer, tx, token_symbol, &chain_id, &addr) + let chain_id = starknet_chain_id.ok_or(SignError::StarkSigningError( + StarkSignerError::SignError("Invalid starknet_chain_id".to_string()), + ))?; + let addr = starknet_addr.ok_or(SignError::StarkSigningError( + StarkSignerError::SignError("Invalid starknet_addr".to_string()), + ))?; + sign_starknet_transfer( + signer, + &self.zklink_signer, + tx, + token_symbol, + &chain_id, + &addr, + ) } } } @@ -165,12 +183,12 @@ impl Signer { sign_eth_withdraw(signer, &self.zklink_signer, tx, l2_source_token_symbol) } Layer1Sginer::StarknetSigner(signer) => { - let chain_id = starknet_chain_id.ok_or(SignError::StarkSigningError(StarkSignerError::SignError( - "Invalid starknet_chain_id".to_string(), - )))?; - let addr = starknet_addr.ok_or(SignError::StarkSigningError(StarkSignerError::SignError( - "Invalid starknet_addr".to_string(), - )))?; + let chain_id = starknet_chain_id.ok_or(SignError::StarkSigningError( + StarkSignerError::SignError("Invalid starknet_chain_id".to_string()), + ))?; + let addr = starknet_addr.ok_or(SignError::StarkSigningError( + StarkSignerError::SignError("Invalid starknet_addr".to_string()), + ))?; sign_starknet_withdraw( signer, &self.zklink_signer, diff --git a/provider/src/response.rs b/provider/src/response.rs index a490b0df..25d9aa55 100644 --- a/provider/src/response.rs +++ b/provider/src/response.rs @@ -8,8 +8,8 @@ use chrono::serde::{ts_microseconds, ts_microseconds_option}; use zklink_sdk_signers::eth_signer::H256; use zklink_sdk_signers::zklink_signer::pubkey_hash::PubKeyHash; use zklink_sdk_types::prelude::{ - AccountId, BigIntSerdeWrapper, BigUintSerdeWrapper, BlockNumber, ChainId, MarginId, Nonce, PairId, SlotId, - SubAccountId, TokenId, TxHash, ZkLinkAddress, U256, + AccountId, BigIntSerdeWrapper, BigUintSerdeWrapper, BlockNumber, ChainId, MarginId, Nonce, + PairId, SlotId, SubAccountId, TokenId, TxHash, ZkLinkAddress, U256, }; use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx; diff --git a/provider/src/rpc.rs b/provider/src/rpc.rs index 9b8b1387..621b1382 100644 --- a/provider/src/rpc.rs +++ b/provider/src/rpc.rs @@ -7,7 +7,9 @@ use crate::web_socket::ws_message::message::response::TxTopicEvent; use crate::web_socket::ws_message::topic::Topic; use jsonrpsee::core::RpcResult; use zklink_sdk_types::basic_types::tx_hash::TxHash; -use zklink_sdk_types::basic_types::{AccountId, BlockNumber, ChainId, SubAccountId, TokenId, ZkLinkAddress}; +use zklink_sdk_types::basic_types::{ + AccountId, BlockNumber, ChainId, SubAccountId, TokenId, ZkLinkAddress, +}; use zklink_sdk_types::prelude::BigUintSerdeWrapper; use zklink_sdk_types::signatures::TxLayer1Signature; use zklink_sdk_types::tx_type::zklink_tx::{ZkLinkTx, ZkLinkTxType}; @@ -71,7 +73,11 @@ pub trait ZkLinkRpc { ) -> RpcResult; #[method(name = "getTokenReserve")] - async fn token_remain(&self, token_id: TokenId, mapping: bool) -> RpcResult>; + async fn token_remain( + &self, + token_id: TokenId, + mapping: bool, + ) -> RpcResult>; #[method(name = "getAccountSnapshot")] async fn account_snapshot( @@ -94,10 +100,18 @@ pub trait ZkLinkRpc { ) -> RpcResult>; #[method(name = "getWithdrawTxs")] - async fn tx_withdraw(&self, last_tx_timestamp_micro: u64, max_txs: u32) -> RpcResult>; + async fn tx_withdraw( + &self, + last_tx_timestamp_micro: u64, + max_txs: u32, + ) -> RpcResult>; #[method(name = "getWebSocketEvents")] - async fn get_websocket_events(&self, topic: Topic, offset: ClientOffset) -> RpcResult>; + async fn get_websocket_events( + &self, + topic: Topic, + offset: ClientOffset, + ) -> RpcResult>; #[method(name = "getChangePubkeyChainId")] async fn get_change_pubkey_chain_id(&self) -> RpcResult; @@ -106,5 +120,9 @@ pub trait ZkLinkRpc { async fn get_eth_property(&self) -> RpcResult; #[method(name = "sendTransaction")] - async fn tx_submit(&self, tx: ZkLinkTx, l1_signature: Option) -> RpcResult; + async fn tx_submit( + &self, + tx: ZkLinkTx, + l1_signature: Option, + ) -> RpcResult; } diff --git a/provider/src/web_socket/ws_message/message/response.rs b/provider/src/web_socket/ws_message/message/response.rs index 64c4ae99..0f72c2cf 100644 --- a/provider/src/web_socket/ws_message/message/response.rs +++ b/provider/src/web_socket/ws_message/message/response.rs @@ -1,6 +1,8 @@ use crate::response::TxResp; use crate::web_socket::proto::event::Event; -use crate::web_socket::ws_message::message::response::ServerEvent::{PriorityEvent, TxExecuteResult}; +use crate::web_socket::ws_message::message::response::ServerEvent::{ + PriorityEvent, TxExecuteResult, +}; use crate::web_socket::ws_message::topic::{Topic, TopicType}; use serde::{Deserialize, Serialize}; use serde_json::Value; diff --git a/provider/tests/test_rpc.rs b/provider/tests/test_rpc.rs index 8ebcbe47..4c49f093 100644 --- a/provider/tests/test_rpc.rs +++ b/provider/tests/test_rpc.rs @@ -8,7 +8,9 @@ mod test { use zklink_sdk_signers::zklink_signer::{PubKeyHash, ZkLinkSigner}; use zklink_sdk_types::basic_types::BigUint; use zklink_sdk_types::basic_types::GetBytes; - use zklink_sdk_types::basic_types::{AccountId, ChainId, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress}; + use zklink_sdk_types::basic_types::{ + AccountId, ChainId, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress, + }; use zklink_sdk_types::tx_builder::{ChangePubKeyBuilder, OrderMatchingBuilder}; use zklink_sdk_types::tx_type::order_matching::Order; use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx; @@ -37,9 +39,14 @@ mod test { }; let change_pubkey = builder.build(); let message = change_pubkey - .to_eip712_request_payload(l1_client_id, &ZkLinkAddress::from_str(main_contract).unwrap()) + .to_eip712_request_payload( + l1_client_id, + &ZkLinkAddress::from_str(main_contract).unwrap(), + ) + .unwrap(); + let signature = eth_signer + .sign_message(message.raw_data.as_bytes()) .unwrap(); - let signature = eth_signer.sign_message(message.raw_data.as_bytes()).unwrap(); let builder_with_sig = ChangePubKeyBuilder { chain_id: ChainId(1), account_id: AccountId(10), @@ -55,7 +62,9 @@ mod test { tx.sign(&zklink_signer).unwrap(); //use jsonrpsee - let client = HttpClientBuilder::default().build("https://dev-gw-v1.zk.link").unwrap(); + let client = HttpClientBuilder::default() + .build("https://dev-gw-v1.zk.link") + .unwrap(); let ret = client .tx_submit(ZkLinkTx::ChangePubKey(Box::new(tx.clone())), None) .await; @@ -117,9 +126,14 @@ mod test { order_matching.sign(&zklink_signer).unwrap(); //use jsonrpsee - let client = HttpClientBuilder::default().build("https://aws-gw-v2.zk.link").unwrap(); + let client = HttpClientBuilder::default() + .build("https://aws-gw-v2.zk.link") + .unwrap(); let ret = client - .tx_submit(ZkLinkTx::OrderMatching(Box::new(order_matching.clone())), None) + .tx_submit( + ZkLinkTx::OrderMatching(Box::new(order_matching.clone())), + None, + ) .await; println!("{:?}", ret) } diff --git a/signers/src/eth_signer/eip712/eip712.rs b/signers/src/eth_signer/eip712/eip712.rs index 47a328b3..bd5a4b12 100644 --- a/signers/src/eth_signer/eip712/eip712.rs +++ b/signers/src/eth_signer/eip712/eip712.rs @@ -36,8 +36,16 @@ impl EIP712Domain { }) } - pub fn new_zklink_domain(layer_one_chain_id: u32, eth_contract_addr: String) -> Result { - EIP712Domain::new("ZkLink".into(), "1".into(), layer_one_chain_id, eth_contract_addr) + pub fn new_zklink_domain( + layer_one_chain_id: u32, + eth_contract_addr: String, + ) -> Result { + EIP712Domain::new( + "ZkLink".into(), + "1".into(), + layer_one_chain_id, + eth_contract_addr, + ) } } @@ -67,17 +75,20 @@ where pub fn new(domain: EIP712Domain, value: M) -> Result, EthSignerError> { // Get primary type. - let encode_type = eip712_encode_type(&value).map_err(|e| EthSignerError::Eip712Failed(e.to_string()))?; + let encode_type = + eip712_encode_type(&value).map_err(|e| EthSignerError::Eip712Failed(e.to_string()))?; let pos = encode_type.find('(').unwrap(); let primary_type = encode_type[..pos].to_string(); - let mut type_definitions = - eip712_type_definitions(&domain).map_err(|e| EthSignerError::Eip712Failed(e.to_string()))?; + let mut type_definitions = eip712_type_definitions(&domain) + .map_err(|e| EthSignerError::Eip712Failed(e.to_string()))?; - type_definitions - .extend(eip712_type_definitions(&value).map_err(|e| EthSignerError::Eip712Failed(e.to_string()))?); + type_definitions.extend( + eip712_type_definitions(&value) + .map_err(|e| EthSignerError::Eip712Failed(e.to_string()))?, + ); Ok(TypedData { types: type_definitions, diff --git a/signers/src/eth_signer/json_rpc_signer.rs b/signers/src/eth_signer/json_rpc_signer.rs index 08e933b1..04bc0b9d 100755 --- a/signers/src/eth_signer/json_rpc_signer.rs +++ b/signers/src/eth_signer/json_rpc_signer.rs @@ -42,39 +42,44 @@ impl JsonRpcSigner { pub async fn sign_message(&self, message: &[u8]) -> Result { let provider_address = self.provider.selectedAddress(); let mut params = Vec::new(); - let msg_str = std::str::from_utf8(message).map_err(|e| EthSignerError::CustomError(e.to_string()))?; + let msg_str = + std::str::from_utf8(message).map_err(|e| EthSignerError::CustomError(e.to_string()))?; params.push(serde_json::to_value(msg_str).unwrap()); params.push(serde_json::to_value(provider_address).unwrap()); let req_params = RequestArguments { method: "personal_sign".to_string(), params, }; - let params = - serde_wasm_bindgen::to_value(&req_params).map_err(|e| EthSignerError::CustomError(e.to_string()))?; - let signature = self - .provider - .request(params) - .await - .map_err(|e| EthSignerError::RpcSignError(serde_wasm_bindgen::from_value::(e).unwrap()))?; + let params = serde_wasm_bindgen::to_value(&req_params) + .map_err(|e| EthSignerError::CustomError(e.to_string()))?; + let signature = self.provider.request(params).await.map_err(|e| { + EthSignerError::RpcSignError(serde_wasm_bindgen::from_value::(e).unwrap()) + })?; let signature = serde_wasm_bindgen::from_value::(signature) .map_err(|e| EthSignerError::SigningFailed(e.to_string()))?; PackedEthSignature::from_hex(&signature) } - pub async fn sign_message_eip712(&self, message: &[u8]) -> Result { + pub async fn sign_message_eip712( + &self, + message: &[u8], + ) -> Result { let provider_address = self.provider.selectedAddress(); let mut params = Vec::new(); - let msg_str = std::str::from_utf8(message).map_err(|e| EthSignerError::CustomError(e.to_string()))?; + let msg_str = + std::str::from_utf8(message).map_err(|e| EthSignerError::CustomError(e.to_string()))?; params.push(serde_json::to_value(provider_address).unwrap()); params.push(serde_json::to_value(msg_str).unwrap()); let req_params = RequestArguments { method: "eth_signTypedData_v4".to_string(), params, }; - let params = - serde_wasm_bindgen::to_value(&req_params).map_err(|e| EthSignerError::CustomError(e.to_string()))?; + let params = serde_wasm_bindgen::to_value(&req_params) + .map_err(|e| EthSignerError::CustomError(e.to_string()))?; let signature = self.provider.request(params).await.map_err(|e| { - EthSignerError::SigningFailed(serde_wasm_bindgen::from_value::(e).unwrap_or_default()) + EthSignerError::SigningFailed( + serde_wasm_bindgen::from_value::(e).unwrap_or_default(), + ) })?; let signature = serde_wasm_bindgen::from_value::(signature) .map_err(|e| EthSignerError::SigningFailed(e.to_string()))?; diff --git a/signers/src/eth_signer/packed_eth_signature.rs b/signers/src/eth_signer/packed_eth_signature.rs index 7884b021..10c756e5 100644 --- a/signers/src/eth_signer/packed_eth_signature.rs +++ b/signers/src/eth_signer/packed_eth_signature.rs @@ -45,7 +45,8 @@ impl PackedEthSignature { bytes_array.copy_from_slice(bytes); Ok(PackedEthSignature( - Signature::try_from(bytes_array.as_slice()).map_err(|_err| EthSignerError::InvalidEthSigner)?, + Signature::try_from(bytes_array.as_slice()) + .map_err(|_err| EthSignerError::InvalidEthSigner)?, )) } diff --git a/signers/src/eth_signer/pk_signer.rs b/signers/src/eth_signer/pk_signer.rs index aab6530c..807f344a 100644 --- a/signers/src/eth_signer/pk_signer.rs +++ b/signers/src/eth_signer/pk_signer.rs @@ -38,7 +38,10 @@ impl EthSigner { } /// Signs and returns the RLP-encoded transaction. - pub fn sign_transaction(&self, tx: &TypedTransaction) -> Result { + pub fn sign_transaction( + &self, + tx: &TypedTransaction, + ) -> Result { let key = SigningKey::from_slice(self.private_key.as_bytes()).unwrap(); let signed = LocalWallet::from(key) .with_chain_id(tx.chain_id().unwrap_or_default().as_u64()) @@ -169,7 +172,9 @@ mod test { let typed_data = TypedData::new(domain, message).unwrap(); - let signature = pk_signer.sign_hash(typed_data.sign_hash().unwrap().as_ref()).unwrap(); + let signature = pk_signer + .sign_hash(typed_data.sign_hash().unwrap().as_ref()) + .unwrap(); assert_eq!(signature.as_hex(), "0xbf24877c59766e95717686e71a0402ba12f5db4a8aa93ac6c30b5742925ebfc26c91d6b6bb949a2b0578c397e296830dde9cc3531adbb259c4b4b06441b1a9c51b"); } diff --git a/signers/src/lib.rs b/signers/src/lib.rs index 46ca821c..297b3280 100644 --- a/signers/src/lib.rs +++ b/signers/src/lib.rs @@ -18,6 +18,10 @@ pub struct RpcErr { impl std::fmt::Display for RpcErr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "error code: {},error message: {}", self.code, self.message) + write!( + f, + "error code: {},error message: {}", + self.code, self.message + ) } } diff --git a/signers/src/starknet_signer/ecdsa_signature.rs b/signers/src/starknet_signer/ecdsa_signature.rs index 62039383..9dd3b4e7 100644 --- a/signers/src/starknet_signer/ecdsa_signature.rs +++ b/signers/src/starknet_signer/ecdsa_signature.rs @@ -38,8 +38,10 @@ impl StarkEcdsaSignature { } pub fn from_rs_str(r: &str, s: &str) -> Result { - let r = FieldElement::from_str(r).map_err(|e| StarkSignerError::InvalidSignature(e.to_string()))?; - let s = FieldElement::from_str(s).map_err(|e| StarkSignerError::InvalidSignature(e.to_string()))?; + let r = FieldElement::from_str(r) + .map_err(|e| StarkSignerError::InvalidSignature(e.to_string()))?; + let s = FieldElement::from_str(s) + .map_err(|e| StarkSignerError::InvalidSignature(e.to_string()))?; Ok(Self { s, r }) } @@ -47,12 +49,16 @@ impl StarkEcdsaSignature { let mut s = [0_u8; 32]; let mut r = [0_u8; 32]; if bytes.len() != 64 { - return Err(StarkSignerError::invalid_signature("bytes should be 64 length")); + return Err(StarkSignerError::invalid_signature( + "bytes should be 64 length", + )); } r.clone_from_slice(&bytes[0..32]); s.clone_from_slice(&bytes[32..]); - let s = FieldElement::from_bytes_be(&s).map_err(|e| StarkSignerError::invalid_signature(e.to_string()))?; - let r = FieldElement::from_bytes_be(&r).map_err(|e| StarkSignerError::invalid_signature(e.to_string()))?; + let s = FieldElement::from_bytes_be(&s) + .map_err(|e| StarkSignerError::invalid_signature(e.to_string()))?; + let r = FieldElement::from_bytes_be(&r) + .map_err(|e| StarkSignerError::invalid_signature(e.to_string()))?; Ok(Self { s, r }) } } @@ -103,7 +109,8 @@ impl StarkEip712Signature { impl StarkEip712Signature { pub fn verify(&self, msg: &TypedData, addr: &str) -> Result { - let addr = FieldElement::from_hex_be(addr).map_err(|e| StarkSignerError::SignError(e.to_string()))?; + let addr = FieldElement::from_hex_be(addr) + .map_err(|e| StarkSignerError::SignError(e.to_string()))?; let hash = msg.get_message_hash(addr)?; let verifying_key = VerifyingKey::from_scalar(self.pub_key); let is_ok = verifying_key diff --git a/signers/src/starknet_signer/pk_signer.rs b/signers/src/starknet_signer/pk_signer.rs index 3a2b32b1..d3ee04e9 100644 --- a/signers/src/starknet_signer/pk_signer.rs +++ b/signers/src/starknet_signer/pk_signer.rs @@ -25,7 +25,8 @@ impl StarkSigner { } pub fn new_from_hex_str(hex_str: &str) -> Result { - let private_key = FieldElement::from_hex_be(hex_str).map_err(|e| Error::InvalidPrivKey(e.to_string()))?; + let private_key = + FieldElement::from_hex_be(hex_str).map_err(|e| Error::InvalidPrivKey(e.to_string()))?; let signing_key = SigningKey::from_secret_scalar(private_key); Ok(Self(signing_key)) } @@ -35,7 +36,10 @@ impl StarkSigner { pub fn sign_message(&self, msg: &TypedData, addr: &str) -> Result { let addr = FieldElement::from_hex_be(addr).map_err(|e| Error::SignError(e.to_string()))?; let hash = msg.get_message_hash(addr)?; - let signature = self.0.sign(&hash).map_err(|e| Error::sign_error(e.to_string()))?; + let signature = self + .0 + .sign(&hash) + .map_err(|e| Error::sign_error(e.to_string()))?; let s = StarkEip712Signature { pub_key: self.public_key(), signature: StarkEcdsaSignature { @@ -83,7 +87,10 @@ mod tests { }; let message = transfer.clone(); - let typed_data = TypedData::new(TypedDataMessage::Transaction { message }, "SN_GOERLI".to_string()); + let typed_data = TypedData::new( + TypedDataMessage::Transaction { message }, + "SN_GOERLI".to_string(), + ); let signature = StarkEip712Signature::from_hex(sig_str).unwrap(); let is_ok = signature.verify(&typed_data, addr).unwrap(); assert!(is_ok); diff --git a/signers/src/starknet_signer/starknet_json_rpc_signer.rs b/signers/src/starknet_signer/starknet_json_rpc_signer.rs index 8581c9cb..e8d68334 100644 --- a/signers/src/starknet_signer/starknet_json_rpc_signer.rs +++ b/signers/src/starknet_signer/starknet_json_rpc_signer.rs @@ -41,10 +41,13 @@ impl StarknetJsonRpcSigner { self.signer.address() } - pub async fn sign_message(&self, message: TypedDataMessage) -> Result { + pub async fn sign_message( + &self, + message: TypedDataMessage, + ) -> Result { let typed_data = TypedData::new(message, self.chain_id.clone()); - let typed_data = - serde_wasm_bindgen::to_value(&typed_data).map_err(|e| StarkSignerError::SignError(e.to_string()))?; + let typed_data = serde_wasm_bindgen::to_value(&typed_data) + .map_err(|e| StarkSignerError::SignError(e.to_string()))?; let signature = self.signer.signMessage(&typed_data).await.map_err(|e| { let err_str = format!("{:?}", e); let e = err_str.trim_start_matches("JsValue(").trim_end_matches(')'); @@ -58,7 +61,8 @@ impl StarknetJsonRpcSigner { let signature = StarkEcdsaSignature::from_rs_str(&signature[0], &signature[1]) .map_err(|e| StarkSignerError::InvalidSignature(e.to_string()))?; - let pub_key = FieldElement::from_str(&self.pub_key).map_err(|e| StarkSignerError::SignError(e.to_string()))?; + let pub_key = FieldElement::from_str(&self.pub_key) + .map_err(|e| StarkSignerError::SignError(e.to_string()))?; Ok(StarkEip712Signature { pub_key, signature }) } } diff --git a/signers/src/starknet_signer/typed_data/mod.rs b/signers/src/starknet_signer/typed_data/mod.rs index 931a30f5..22035995 100644 --- a/signers/src/starknet_signer/typed_data/mod.rs +++ b/signers/src/starknet_signer/typed_data/mod.rs @@ -145,13 +145,18 @@ impl TypedData { ret } - pub fn get_struct_hash(&self, struct_type: &str, data: &M) -> Result { + pub fn get_struct_hash( + &self, + struct_type: &str, + data: &M, + ) -> Result { let mut types_array = vec![]; let mut data_array = vec![]; types_array.push("felt".to_string()); let type_hash = starknet_keccak(self.encode_type(struct_type).as_bytes()); data_array.push(type_hash); - let data_value = serde_json::to_value(data).map_err(|e| StarkSignerError::SignError(e.to_string()))?; + let data_value = + serde_json::to_value(data).map_err(|e| StarkSignerError::SignError(e.to_string()))?; let data_map = data_value.as_object().unwrap(); //type must be exist let td = self.get_type_define(struct_type); @@ -163,7 +168,8 @@ impl TypedData { types_array.push(t.r#type.clone()); let v_str = data_map.get(&t.name).unwrap().as_str().unwrap(); let v = Self::string_to_hex(v_str); - let v = FieldElement::from_hex_be(&v).map_err(|e| StarkSignerError::SignError(e.to_string()))?; + let v = FieldElement::from_hex_be(&v) + .map_err(|e| StarkSignerError::SignError(e.to_string()))?; data_array.push(v); } @@ -178,7 +184,8 @@ impl TypedData { .get_struct_hash("Message", &self.message) .map_err(|e| StarkSignerError::SignError(e.to_string()))?; //StarkNet Message - let stark_net_message = FieldElement::from_str(&Self::string_to_hex("StarkNet Message")).unwrap(); + let stark_net_message = + FieldElement::from_str(&Self::string_to_hex("StarkNet Message")).unwrap(); Ok(vec![stark_net_message, domain, addr, message]) } @@ -217,7 +224,9 @@ mod tests { version: "1".to_string(), chain_id: starknet_chain_id, }; - let domain_hash = typed_data.get_struct_hash("StarkNetDomain", &domain).unwrap(); + let domain_hash = typed_data + .get_struct_hash("StarkNetDomain", &domain) + .unwrap(); let message_hash = typed_data.get_struct_hash("Message", &message).unwrap(); assert_eq!( hex::encode(domain_hash.to_bytes_be()), diff --git a/signers/src/zklink_signer/pk_signer.rs b/signers/src/zklink_signer/pk_signer.rs index 405e8d5a..28da1c47 100755 --- a/signers/src/zklink_signer/pk_signer.rs +++ b/signers/src/zklink_signer/pk_signer.rs @@ -77,7 +77,9 @@ impl ZkLinkSigner { loop { let raw_priv_key = sha256_bytes(effective_seed.as_slice()); let mut fs_repr = FsRepr::default(); - fs_repr.read_be(&raw_priv_key[..]).expect("failed to read raw_priv_key"); + fs_repr + .read_be(&raw_priv_key[..]) + .expect("failed to read raw_priv_key"); match Fs::from_repr(fs_repr) { Ok(fs) => { return Ok(Self::from_fs(fs)); @@ -96,7 +98,11 @@ impl ZkLinkSigner { Self::new_from_seed(&seed) } - pub fn new_from_hex_stark_signer(hex_private_key: &str, addr: &str, chain_id: &str) -> Result { + pub fn new_from_hex_stark_signer( + hex_private_key: &str, + addr: &str, + chain_id: &str, + ) -> Result { let stark_signer = StarkSigner::new_from_hex_str(hex_private_key)?; Self::new_from_starknet_signer(&stark_signer, addr, chain_id) } @@ -108,19 +114,30 @@ impl ZkLinkSigner { } /// create zkLink signer from starknet signer - pub fn new_from_starknet_signer(starknet_signer: &StarkSigner, addr: &str, chain_id: &str) -> Result { + pub fn new_from_starknet_signer( + starknet_signer: &StarkSigner, + addr: &str, + chain_id: &str, + ) -> Result { let message = Message { data: Self::STARKNET_SIGN_MESSAGE.to_string(), }; - let typed_data = TypedData::new(TypedDataMessage::CreateL2Key { message }, chain_id.to_string()); + let typed_data = TypedData::new( + TypedDataMessage::CreateL2Key { message }, + chain_id.to_string(), + ); let signature = starknet_signer.sign_message(&typed_data, addr)?; let seed = signature.signature.to_bytes_be(); Self::new_from_seed(&seed) } #[cfg(feature = "web")] - pub async fn new_from_eth_rpc_signer(eth_signer: &JsonRpcSigner) -> Result<(Self, Vec), Error> { - let signature = eth_signer.sign_message(Self::SIGN_MESSAGE.as_bytes()).await?; + pub async fn new_from_eth_rpc_signer( + eth_signer: &JsonRpcSigner, + ) -> Result<(Self, Vec), Error> { + let signature = eth_signer + .sign_message(Self::SIGN_MESSAGE.as_bytes()) + .await?; let seed = signature.serialize_packed(); Ok((Self::new_from_seed(&seed)?, seed.to_vec())) } @@ -144,7 +161,9 @@ impl ZkLinkSigner { fs_repr .read_be(bytes) .map_err(|_| Error::custom_error("couldn't read private key repr"))?; - let private_key = FLPrivateKey::(Fs::from_repr(fs_repr).expect("couldn't read private key from repr")); + let private_key = FLPrivateKey::( + Fs::from_repr(fs_repr).expect("couldn't read private key from repr"), + ); Ok(private_key.into()) } @@ -159,8 +178,13 @@ impl ZkLinkSigner { RESCUE_PARAMS.with(|rescue_params| { let hashed_msg = utils::rescue_hash_tx_msg(msg); let seed = Seed::deterministic_seed(self.as_ref(), &hashed_msg); - self.as_ref() - .musig_rescue_sign(hashed_msg.as_slice(), &seed, p_g, rescue_params, jubjub_params) + self.as_ref().musig_rescue_sign( + hashed_msg.as_slice(), + &seed, + p_g, + rescue_params, + jubjub_params, + ) }) }); let signature = ZkLinkSignature { @@ -176,7 +200,13 @@ impl ZkLinkSigner { pub fn public_key(&self) -> PackedPublicKey { let pubkey: PackedPublicKey = JUBJUB_PARAMS - .with(|params| PublicKey::from_private(self.as_ref(), FixedGenerators::SpendingKeyGenerator, params)) + .with(|params| { + PublicKey::from_private( + self.as_ref(), + FixedGenerators::SpendingKeyGenerator, + params, + ) + }) .into(); pubkey } @@ -196,7 +226,10 @@ mod test { "0x7b173e25e484eed3461091430f81b2a5bd7ae792f69701dcb073cb903f812510" ); let pub_key_hash = zk_signer.public_key().public_key_hash(); - assert_eq!(pub_key_hash.as_hex(), "0xd8d5fb6a6caef06aa3dc2abdcdc240987e5330fe"); + assert_eq!( + pub_key_hash.as_hex(), + "0xd8d5fb6a6caef06aa3dc2abdcdc240987e5330fe" + ); let zk_signer2 = zk_signer.clone(); let pub_key_hash2 = zk_signer2.public_key().public_key_hash(); assert_eq!(pub_key_hash.as_hex(), pub_key_hash2.as_hex()); diff --git a/signers/src/zklink_signer/public_key.rs b/signers/src/zklink_signer/public_key.rs index b65ee326..8148fc4c 100644 --- a/signers/src/zklink_signer/public_key.rs +++ b/signers/src/zklink_signer/public_key.rs @@ -1,7 +1,9 @@ use super::error::ZkSignerError as Error; use super::{EddsaPubkey, Engine, JUBJUB_PARAMS}; use crate::zklink_signer::pubkey_hash::PubKeyHash; -use crate::zklink_signer::utils::{append_le_fixed_width, pack_bits_into_bytes, rescue_hash_elements}; +use crate::zklink_signer::utils::{ + append_le_fixed_width, pack_bits_into_bytes, rescue_hash_elements, +}; use crate::zklink_signer::{NEW_PUBKEY_HASH_WIDTH, PACKED_POINT_SIZE}; use franklin_crypto::jubjub::edwards; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -64,7 +66,8 @@ impl PackedPublicKey { pub fn from_hex(s: &str) -> Result { let s = s.strip_prefix("0x").unwrap_or(s); - let raw = hex::decode(s).map_err(|_| Error::InvalidPubkey("can't convert to public key".into()))?; + let raw = hex::decode(s) + .map_err(|_| Error::InvalidPubkey("can't convert to public key".into()))?; Self::from_bytes(&raw) } diff --git a/signers/src/zklink_signer/signature.rs b/signers/src/zklink_signer/signature.rs index 08a56d1c..5a628714 100644 --- a/signers/src/zklink_signer/signature.rs +++ b/signers/src/zklink_signer/signature.rs @@ -94,7 +94,8 @@ impl PackedSignature { pub fn from_hex(s: &str) -> Result { let s = s.strip_prefix("0x").unwrap_or(s); - let raw = hex::decode(s).map_err(|_e| Error::InvalidSignature("can't convert string to bytes".into()))?; + let raw = hex::decode(s) + .map_err(|_e| Error::InvalidSignature("can't convert string to bytes".into()))?; Self::from_bytes(&raw) } } @@ -136,7 +137,8 @@ impl ZkLinkSignature { /// Create a ZkLinkSignature from hex string which starts with 0x or not pub fn from_hex(s: &str) -> Result { let s = s.strip_prefix("0x").unwrap_or(s); - let raw = hex::decode(s).map_err(|_| Error::InvalidSignature("invalid signature string".into()))?; + let raw = hex::decode(s) + .map_err(|_| Error::InvalidSignature("invalid signature string".into()))?; Self::from_bytes(&raw) } diff --git a/signers/src/zklink_signer/utils.rs b/signers/src/zklink_signer/utils.rs index e6a73c11..7227ef8b 100644 --- a/signers/src/zklink_signer/utils.rs +++ b/signers/src/zklink_signer/utils.rs @@ -119,8 +119,8 @@ mod tests { assert_eq!( hash, vec![ - 249, 154, 208, 123, 96, 89, 132, 235, 231, 63, 56, 200, 153, 131, 27, 183, 128, 71, 26, 245, 208, 120, - 49, 246, 233, 72, 230, 84, 66, 150, 170, 27 + 249, 154, 208, 123, 96, 89, 132, 235, 231, 63, 56, 200, 153, 131, 27, 183, 128, 71, + 26, 245, 208, 120, 49, 246, 233, 72, 230, 84, 66, 150, 170, 27 ] ); } @@ -132,8 +132,8 @@ mod tests { assert_eq!( hash, vec![ - 165, 52, 198, 24, 171, 190, 215, 122, 29, 12, 31, 190, 98, 145, 72, 245, 89, 202, 199, 73, 239, 213, - 234, 218, 74, 182, 95, 119, 141, 75, 253 + 165, 52, 198, 24, 171, 190, 215, 122, 29, 12, 31, 190, 98, 145, 72, 245, 89, 202, + 199, 73, 239, 213, 234, 218, 74, 182, 95, 119, 141, 75, 253 ] ); } diff --git a/signers/tests/eip712_test.rs b/signers/tests/eip712_test.rs index 4712ff5b..908ad6ef 100644 --- a/signers/tests/eip712_test.rs +++ b/signers/tests/eip712_test.rs @@ -54,16 +54,21 @@ fn test_mail() { eip712_encode_type(&mail).expect("generate e712 types") ); - let expect_request: TypedData = serde_json::from_str(include_str!("./eip712.json")).unwrap(); + let expect_request: TypedData = + serde_json::from_str(include_str!("./eip712.json")).unwrap(); - assert_eq!(TypedData::::new(domain_1, mail).unwrap(), expect_request); + assert_eq!( + TypedData::::new(domain_1, mail).unwrap(), + expect_request + ); assert_eq!( hex::encode(expect_request.sign_hash().unwrap()), "be609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2" ); - let expect_request: TypedData = serde_json::from_str(include_str!("./eip712.json")).unwrap(); + let expect_request: TypedData = + serde_json::from_str(include_str!("./eip712.json")).unwrap(); assert_eq!( hex::encode(expect_request.sign_hash().unwrap()), diff --git a/types/src/basic_types/float_convert.rs b/types/src/basic_types/float_convert.rs index d4cb8898..0f5b1468 100644 --- a/types/src/basic_types/float_convert.rs +++ b/types/src/basic_types/float_convert.rs @@ -21,7 +21,8 @@ impl FloatConversions { pub fn pack_up(number: &BigUint, exponent_len: usize, mantissa_len: usize) -> Vec { let uint = number.to_u128().expect("Only u128 allowed"); - let mut vec = Self::to_float_up(uint, exponent_len, mantissa_len, 10).expect("packing error"); + let mut vec = + Self::to_float_up(uint, exponent_len, mantissa_len, 10).expect("packing error"); vec.reverse(); BitConvert::into_bytes_ordered(vec) } diff --git a/types/src/basic_types/pack.rs b/types/src/basic_types/pack.rs index e8baa2a6..0ef1b13d 100644 --- a/types/src/basic_types/pack.rs +++ b/types/src/basic_types/pack.rs @@ -1,6 +1,7 @@ use crate::basic_types::float_convert::FloatConversions; use crate::basic_types::params::{ - AMOUNT_EXPONENT_BIT_WIDTH, AMOUNT_MANTISSA_BIT_WIDTH, FEE_EXPONENT_BIT_WIDTH, FEE_MANTISSA_BIT_WIDTH, + AMOUNT_EXPONENT_BIT_WIDTH, AMOUNT_MANTISSA_BIT_WIDTH, FEE_EXPONENT_BIT_WIDTH, + FEE_MANTISSA_BIT_WIDTH, }; use num::{BigUint, FromPrimitive}; @@ -64,12 +65,14 @@ pub fn is_fee_amount_packable(amount: &BigUint) -> bool { /// Attempts to unpack the token amount. pub fn unpack_token_amount(data: &[u8]) -> Option { - FloatConversions::unpack(data, AMOUNT_EXPONENT_BIT_WIDTH, AMOUNT_MANTISSA_BIT_WIDTH).and_then(BigUint::from_u128) + FloatConversions::unpack(data, AMOUNT_EXPONENT_BIT_WIDTH, AMOUNT_MANTISSA_BIT_WIDTH) + .and_then(BigUint::from_u128) } /// Attempts to unpack the fee amount. pub fn unpack_fee_amount(data: &[u8]) -> Option { - FloatConversions::unpack(data, FEE_EXPONENT_BIT_WIDTH, FEE_MANTISSA_BIT_WIDTH).and_then(BigUint::from_u128) + FloatConversions::unpack(data, FEE_EXPONENT_BIT_WIDTH, FEE_MANTISSA_BIT_WIDTH) + .and_then(BigUint::from_u128) } /// Returns the closest possible packable token amount. @@ -128,8 +131,12 @@ mod test { let max_mantissa_fee = BigUint::from((1u128 << FEE_MANTISSA_BIT_WIDTH) - 1); assert!(is_token_amount_packable(&max_mantissa_token)); assert!(is_fee_amount_packable(&max_mantissa_fee)); - assert!(!is_token_amount_packable(&(max_mantissa_token + BigUint::from(1u32)))); - assert!(!is_fee_amount_packable(&(max_mantissa_fee + BigUint::from(1u32)))); + assert!(!is_token_amount_packable( + &(max_mantissa_token + BigUint::from(1u32)) + )); + assert!(!is_fee_amount_packable( + &(max_mantissa_fee + BigUint::from(1u32)) + )); } #[test] diff --git a/types/src/basic_types/params.rs b/types/src/basic_types/params.rs index b9058017..e94cb5bf 100644 --- a/types/src/basic_types/params.rs +++ b/types/src/basic_types/params.rs @@ -4,7 +4,8 @@ use crate::basic_types::{AccountId, ChainId, Nonce, SlotId, SubAccountId, TokenI pub const TOKEN_MAX_PRECISION: u8 = 18; /// Maximum number of chains allowed => The width of every token chain partition.(global asset tree) pub const MAX_CHAIN_ID: ChainId = ChainId(u8::pow(2, CHAIN_SUB_TREE_DEPTH as u32) - 1); -pub const MAX_SUB_ACCOUNT_ID: SubAccountId = SubAccountId(u8::pow(2, SUB_ACCOUNT_TREE_DEPTH as u32) - 1); +pub const MAX_SUB_ACCOUNT_ID: SubAccountId = + SubAccountId(u8::pow(2, SUB_ACCOUNT_TREE_DEPTH as u32) - 1); /// Depth of sub-account tree allowed (be used for multiple different partition dex). pub const SUB_ACCOUNT_TREE_DEPTH: usize = 5; /// Depth of the orders subtree for each account. diff --git a/types/src/basic_types/tx_hash.rs b/types/src/basic_types/tx_hash.rs index 0c038b5e..3ffe5703 100644 --- a/types/src/basic_types/tx_hash.rs +++ b/types/src/basic_types/tx_hash.rs @@ -65,7 +65,8 @@ impl FromStr for TxHash { return Err(Error::NotStartWithZerox); } let remove_prefix_start = zerox_prefix.len(); - let bytes = hex::decode(&s[remove_prefix_start..]).map_err(|e| Error::DecodeFromHexErr(e.to_string()))?; + let bytes = hex::decode(&s[remove_prefix_start..]) + .map_err(|e| Error::DecodeFromHexErr(e.to_string()))?; if bytes.len() != 32 { return Err(Error::SizeMismatch); } diff --git a/types/src/basic_types/zklink_address.rs b/types/src/basic_types/zklink_address.rs index 3bdbbf74..33c9c5e0 100644 --- a/types/src/basic_types/zklink_address.rs +++ b/types/src/basic_types/zklink_address.rs @@ -113,7 +113,8 @@ impl FromStr for ZkLinkAddress { if !s.starts_with("0x") { return Err(Error::NotStartWithZerox); } - let bytes = hex::decode(s.trim_start_matches("0x")).map_err(|e| Error::DecodeFromHexErr(e.to_string()))?; + let bytes = hex::decode(s.trim_start_matches("0x")) + .map_err(|e| Error::DecodeFromHexErr(e.to_string()))?; if !(bytes.len() == 32 || bytes.len() == 20) { return Err(Error::SizeMismatch); } @@ -225,14 +226,18 @@ mod tests { #[test] fn test_address_convert() { // zklink address and starknet address convert - let starknet_address = - FieldElement::from_str("0x3c9a304c229732090db86a0f1db015c08aa99e31bd68352855a910e477063f8").unwrap(); + let starknet_address = FieldElement::from_str( + "0x3c9a304c229732090db86a0f1db015c08aa99e31bd68352855a910e477063f8", + ) + .unwrap(); let zklink_address: ZkLinkAddress = starknet_address.into(); let address: FieldElement = zklink_address.into(); assert_eq!(address, starknet_address); - let zklink_address = - ZkLinkAddress::from_str("0x03c9a304c229732090db86a0f1db015c08aa99e31bd68352855a910e477063f8").unwrap(); + let zklink_address = ZkLinkAddress::from_str( + "0x03c9a304c229732090db86a0f1db015c08aa99e31bd68352855a910e477063f8", + ) + .unwrap(); let address: FieldElement = zklink_address.into(); assert_eq!(address, starknet_address); @@ -242,7 +247,8 @@ mod tests { let address: Address = zklink_address.into(); assert_eq!(address, eth_address); - let zklink_address = ZkLinkAddress::from_str("0x3D809E414BA4893709C85F242BA3617481BC4126").unwrap(); + let zklink_address = + ZkLinkAddress::from_str("0x3D809E414BA4893709C85F242BA3617481BC4126").unwrap(); let address: Address = zklink_address.into(); assert_eq!(address, eth_address); } diff --git a/types/src/lib.rs b/types/src/lib.rs index 45f8714a..550d1642 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -15,8 +15,8 @@ pub mod prelude { pad::pad_front, tx_hash::TxHash, zklink_address::ZkLinkAddress, - AccountId, BlockNumber, ChainId, EthBlockId, GetBytes, MarginId, Nonce, PairId, PriorityOpId, SlotId, - SubAccountId, TimeStamp, TokenId, + AccountId, BlockNumber, ChainId, EthBlockId, GetBytes, MarginId, Nonce, PairId, + PriorityOpId, SlotId, SubAccountId, TimeStamp, TokenId, }; pub use super::error::TypeError; pub use super::signatures::{TxLayer1Signature, TxSignature}; diff --git a/types/src/tx_builder.rs b/types/src/tx_builder.rs index ede1292f..d23c858f 100644 --- a/types/src/tx_builder.rs +++ b/types/src/tx_builder.rs @@ -1,8 +1,10 @@ -use crate::basic_types::{AccountId, ChainId, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress}; +use crate::basic_types::{ + AccountId, ChainId, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress, +}; use crate::prelude::{ - AutoDeleveraging, ChangePubKey, ChangePubKeyAuthData, Contract, ContractMatching, Deposit, ForcedExit, FullExit, - Funding, Liquidation, OraclePrices, Order, OrderMatching, PairId, Parameter, SlotId, Transfer, UpdateGlobalVar, - Withdraw, + AutoDeleveraging, ChangePubKey, ChangePubKeyAuthData, Contract, ContractMatching, Deposit, + ForcedExit, FullExit, Funding, Liquidation, OraclePrices, Order, OrderMatching, PairId, + Parameter, SlotId, Transfer, UpdateGlobalVar, Withdraw, }; use crate::tx_type::contract::prices::{ContractPrice, SpotPriceInfo}; use crate::tx_type::exit_info::ExitInfo; diff --git a/types/src/tx_type/change_pubkey.rs b/types/src/tx_type/change_pubkey.rs index b0ca5b13..8e2ebd09 100644 --- a/types/src/tx_type/change_pubkey.rs +++ b/types/src/tx_type/change_pubkey.rs @@ -1,5 +1,7 @@ use crate::basic_types::pack::pack_fee_amount; -use crate::basic_types::{AccountId, ChainId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress}; +use crate::basic_types::{ + AccountId, ChainId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress, +}; use crate::params::{SIGNED_CHANGE_PUBKEY_BIT_WIDTH, TX_TYPE_BIT_WIDTH}; #[cfg(feature = "ffi")] use crate::prelude::ChangePubKeyBuilder; @@ -208,7 +210,11 @@ impl ChangePubKey { /// AccountId: 2 /// #[inline] - pub fn get_eth_sign_msg(pubkey_hash: &PubKeyHash, nonce: Nonce, account_id: AccountId) -> String { + pub fn get_eth_sign_msg( + pubkey_hash: &PubKeyHash, + nonce: Nonce, + account_id: AccountId, + ) -> String { format!( "ChangePubKey\nPubKeyHash: {}\nNonce: {}\nAccountId: {}", pubkey_hash.as_hex(), @@ -247,13 +253,17 @@ impl ChangePubKey { layer_one_chain_id: u32, verifying_contract: &ZkLinkAddress, ) -> Result { - let domain = EIP712Domain::new_zklink_domain(layer_one_chain_id, verifying_contract.to_string())?; + let domain = + EIP712Domain::new_zklink_domain(layer_one_chain_id, verifying_contract.to_string())?; let typed_data = TypedData::::new(domain, self.into())?; let raw_data = serde_json::to_string(&typed_data) .map_err(|e| EthSignerError::CustomError(format!("serialization error: {e:?}")))?; let data_hash = typed_data.sign_hash()?; let data_hash = H256::from_slice(&data_hash.0); - Ok(EthTypedData { raw_data, data_hash }) + Ok(EthTypedData { + raw_data, + data_hash, + }) } } @@ -308,15 +318,16 @@ mod test { let change_pubkey = builder.build(); let bytes = change_pubkey.get_bytes(); let expected_bytes = [ - 6, 1, 0, 0, 0, 1, 1, 216, 213, 251, 106, 108, 174, 240, 106, 163, 220, 42, 189, 205, 194, 64, 152, 126, 83, - 48, 254, 0, 18, 12, 128, 0, 0, 0, 1, 100, 240, 85, 232, + 6, 1, 0, 0, 0, 1, 1, 216, 213, 251, 106, 108, 174, 240, 106, 163, 220, 42, 189, 205, + 194, 64, 152, 126, 83, 48, 254, 0, 18, 12, 128, 0, 0, 0, 1, 100, 240, 85, 232, ]; assert_eq!(bytes, expected_bytes); } #[test] fn test_change_pubkey_eth_sign_msg() { - let pubkey_hash = PubKeyHash::from_hex("0xdbd9c8235e4fc9d5b9b7bb201f1133e8a28c0edd").unwrap(); + let pubkey_hash = + PubKeyHash::from_hex("0xdbd9c8235e4fc9d5b9b7bb201f1133e8a28c0edd").unwrap(); let nonce = Nonce(0); let account_id = 2.into(); let key: H256 = [5; 32].into(); diff --git a/types/src/tx_type/contract/auto_deleveraging.rs b/types/src/tx_type/contract/auto_deleveraging.rs index 6cacafb6..bd44ca13 100644 --- a/types/src/tx_type/contract/auto_deleveraging.rs +++ b/types/src/tx_type/contract/auto_deleveraging.rs @@ -69,7 +69,10 @@ impl GetBytes for AutoDeleveraging { out.extend(self.adl_account_id.to_be_bytes()); out.push(*self.pair_id as u8); out.extend(pack_token_amount(&self.adl_size)); - out.extend(pad_front(&self.adl_price.to_bytes_be(), PRICE_BIT_WIDTH / 8)); + out.extend(pad_front( + &self.adl_price.to_bytes_be(), + PRICE_BIT_WIDTH / 8, + )); out.extend((*self.fee_token as u16).to_be_bytes()); out.extend(pack_fee_amount(&self.fee)); assert_eq!(out.len(), bytes_len); diff --git a/types/src/tx_type/contract/contract_matching.rs b/types/src/tx_type/contract/contract_matching.rs index 8e8b7dcb..b6516c57 100644 --- a/types/src/tx_type/contract/contract_matching.rs +++ b/types/src/tx_type/contract/contract_matching.rs @@ -1,7 +1,9 @@ use crate::basic_types::pack::{pack_fee_amount, pack_token_amount}; use crate::basic_types::pad::pad_front; use crate::basic_types::{AccountId, GetBytes, Nonce, PairId, SlotId, SubAccountId, TokenId}; -use crate::params::{CONTRACT_BYTES, ORDERS_BYTES, PRICE_BIT_WIDTH, SIGNED_CONTRACT_MATCHING_BIT_WIDTH}; +use crate::params::{ + CONTRACT_BYTES, ORDERS_BYTES, PRICE_BIT_WIDTH, SIGNED_CONTRACT_MATCHING_BIT_WIDTH, +}; use crate::prelude::{validator::*, OraclePrices}; #[cfg(feature = "ffi")] use crate::tx_builder::{ContractBuilder, ContractMatchingBuilder}; @@ -169,14 +171,20 @@ impl Contract { } #[cfg(feature = "ffi")] - pub fn create_signed_contract(&self, zklink_signer: Arc) -> Result, ZkSignerError> { + pub fn create_signed_contract( + &self, + zklink_signer: Arc, + ) -> Result, ZkSignerError> { let mut contract = self.clone(); contract.signature = zklink_signer.sign_musig(&contract.get_bytes())?; Ok(Arc::new(contract)) } #[cfg(not(feature = "ffi"))] - pub fn create_signed_contract(&self, zklink_signer: &ZkLinkSigner) -> Result { + pub fn create_signed_contract( + &self, + zklink_signer: &ZkLinkSigner, + ) -> Result { let mut contract = self.clone(); contract.signature = zklink_signer.sign_musig(&contract.get_bytes())?; Ok(contract) diff --git a/types/src/tx_type/contract/funding.rs b/types/src/tx_type/contract/funding.rs index 1f9abd43..8be1cc3a 100644 --- a/types/src/tx_type/contract/funding.rs +++ b/types/src/tx_type/contract/funding.rs @@ -1,7 +1,8 @@ use crate::basic_types::pack::pack_fee_amount; use crate::basic_types::{AccountId, GetBytes, Nonce, PairId, SubAccountId, TokenId}; use crate::params::{ - FUNDING_RATE_BYTES, PAIR_BIT_WIDTH, PRICE_BIT_WIDTH, SIGNED_BATCH_FUNDING_BIT_WIDTH, SIGNED_FUNDING_BIT_WIDTH, + FUNDING_RATE_BYTES, PAIR_BIT_WIDTH, PRICE_BIT_WIDTH, SIGNED_BATCH_FUNDING_BIT_WIDTH, + SIGNED_FUNDING_BIT_WIDTH, }; use crate::prelude::pad_front; use crate::prelude::validator::*; diff --git a/types/src/tx_type/contract/prices.rs b/types/src/tx_type/contract/prices.rs index 9b391dce..937099df 100644 --- a/types/src/tx_type/contract/prices.rs +++ b/types/src/tx_type/contract/prices.rs @@ -1,7 +1,8 @@ use crate::basic_types::pad::pad_front; use crate::basic_types::{GetBytes, PairId, TokenId}; use crate::params::{ - CONTRACT_PRICE_BYTES, MARGIN_PRICE_BYTES, MARGIN_TOKENS_NUMBER, PRICE_BIT_WIDTH, USED_POSITION_NUMBER, + CONTRACT_PRICE_BYTES, MARGIN_PRICE_BYTES, MARGIN_TOKENS_NUMBER, PRICE_BIT_WIDTH, + USED_POSITION_NUMBER, }; use crate::prelude::validator::*; use num::BigUint; @@ -25,7 +26,10 @@ impl GetBytes for ContractPrice { let bytes_len = self.bytes_len(); let mut contracts_encode = Vec::with_capacity(bytes_len); contracts_encode.extend((*self.pair_id as u8).to_be_bytes()); - contracts_encode.extend(pad_front(&self.market_price.to_bytes_be(), PRICE_BIT_WIDTH / 8)); + contracts_encode.extend(pad_front( + &self.market_price.to_bytes_be(), + PRICE_BIT_WIDTH / 8, + )); assert_eq!(contracts_encode.len(), bytes_len); contracts_encode } @@ -84,7 +88,9 @@ impl Default for OraclePrices { ..Default::default() }) .collect(), - margin_prices: (0..MARGIN_TOKENS_NUMBER).map(|_| SpotPriceInfo::default()).collect(), + margin_prices: (0..MARGIN_TOKENS_NUMBER) + .map(|_| SpotPriceInfo::default()) + .collect(), } } } diff --git a/types/src/tx_type/contract/update_global_var.rs b/types/src/tx_type/contract/update_global_var.rs index 29e84ee1..45c6822e 100644 --- a/types/src/tx_type/contract/update_global_var.rs +++ b/types/src/tx_type/contract/update_global_var.rs @@ -108,9 +108,8 @@ impl GetBytes for Parameter { fn get_bytes(&self) -> Vec { let mut bytes = vec![self.parameter_type()]; bytes.extend(match self { - Parameter::FeeAccount { account_id } | Parameter::InsuranceFundAccount { account_id } => { - account_id.get_bytes() - } + Parameter::FeeAccount { account_id } + | Parameter::InsuranceFundAccount { account_id } => account_id.get_bytes(), Parameter::MarginInfo { margin_id, token_id, @@ -129,7 +128,8 @@ impl GetBytes for Parameter { } => { let mut bytes = vec![(**pair_id as u8)]; let mut symbol_bytes = [0u8; PAIR_SYMBOL_BYTES]; - symbol_bytes[PAIR_SYMBOL_BYTES - symbol.as_bytes().len()..].copy_from_slice(symbol.as_bytes()); + symbol_bytes[PAIR_SYMBOL_BYTES - symbol.as_bytes().len()..] + .copy_from_slice(symbol.as_bytes()); bytes.extend(symbol_bytes); bytes.extend(initial_margin_rate.to_be_bytes()); bytes.extend(maintenance_margin_rate.to_be_bytes()); @@ -177,8 +177,12 @@ mod test { }, ], }, - Parameter::FeeAccount { account_id: 10.into() }, - Parameter::InsuranceFundAccount { account_id: 9.into() }, + Parameter::FeeAccount { + account_id: 10.into(), + }, + Parameter::InsuranceFundAccount { + account_id: 9.into(), + }, Parameter::MarginInfo { margin_id: 1.into(), token_id: 9.into(), @@ -193,15 +197,17 @@ mod test { ]; let excepted_bytes = [ vec![ - 12, 1, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 13, 224, 182, 179, 167, 100, 0, 0, 127, 255, 1, 0, 0, 0, 0, 0, 0, - 0, 0, 3, 141, 126, 164, 198, 128, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 212, 165, 16, 0, 128, - 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 154, 202, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 12, 1, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 13, 224, 182, 179, 167, 100, 0, 0, 127, 255, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 141, 126, 164, 198, 128, 0, 0, 0, 2, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 232, 212, 165, 16, 0, 128, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 59, 154, 202, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ], vec![12, 1, 1, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0], vec![12, 1, 1, 1, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0], vec![12, 1, 1, 2, 1, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0], vec![ - 12, 1, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 66, 84, 67, 85, 83, 68, 67, 0, 6, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, + 12, 1, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 66, 84, 67, 85, 83, 68, 67, 0, 6, 0, 8, 0, + 0, 0, 0, 0, 0, 0, 0, ], ]; for (param, excepted_bytes) in params.into_iter().zip(excepted_bytes) { diff --git a/types/src/tx_type/deposit.rs b/types/src/tx_type/deposit.rs index 3b8cb10f..de1aa958 100644 --- a/types/src/tx_type/deposit.rs +++ b/types/src/tx_type/deposit.rs @@ -73,8 +73,11 @@ mod test { #[test] fn test_deposit_get_bytes() { - let address = ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); - let l2_hash = H256::from_str("0xe35f3a39d542f6d276c2f203e8fd64fcb8bf5db062b71ccacf45d5ecd9d456f3").unwrap(); + let address = + ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); + let l2_hash = + H256::from_str("0xe35f3a39d542f6d276c2f203e8fd64fcb8bf5db062b71ccacf45d5ecd9d456f3") + .unwrap(); let builder = DepositBuilder { from_address: address.clone(), to_address: address.clone(), @@ -90,8 +93,9 @@ mod test { let deposit = builder.build(); let bytes = deposit.get_bytes(); let excepted_bytes = [ - 0, 0, 0, 0, 0, 0, 125, 1, 227, 95, 58, 57, 213, 66, 246, 210, 118, 194, 242, 3, 232, 253, 100, 252, 184, - 191, 93, 176, 98, 183, 28, 202, 207, 69, 213, 236, 217, 212, 86, 243, + 0, 0, 0, 0, 0, 0, 125, 1, 227, 95, 58, 57, 213, 66, 246, 210, 118, 194, 242, 3, 232, + 253, 100, 252, 184, 191, 93, 176, 98, 183, 28, 202, 207, 69, 213, 236, 217, 212, 86, + 243, ]; assert_eq!(bytes, excepted_bytes); } diff --git a/types/src/tx_type/forced_exit.rs b/types/src/tx_type/forced_exit.rs index 1201418e..a791f97c 100644 --- a/types/src/tx_type/forced_exit.rs +++ b/types/src/tx_type/forced_exit.rs @@ -2,7 +2,9 @@ use num::{BigUint, ToPrimitive}; use validator::Validate; use zklink_sdk_utils::serde::BigUintSerdeAsRadix10Str; -use crate::basic_types::{AccountId, ChainId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress}; +use crate::basic_types::{ + AccountId, ChainId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress, +}; use crate::params::{SIGNED_FORCED_EXIT_BIT_WIDTH, TX_TYPE_BIT_WIDTH}; #[cfg(feature = "ffi")] use crate::prelude::ForcedExitBuilder; @@ -115,7 +117,8 @@ mod test { #[test] fn test_get_bytes() { - let address = ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); + let address = + ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); let ts = 1693472232u32; let builder = ForcedExitBuilder { to_chain_id: ChainId(1), @@ -133,9 +136,9 @@ mod test { let forced_exit = builder.build(); let bytes = forced_exit.get_bytes(); let excepted_bytes = [ - 7, 1, 0, 0, 0, 10, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 175, 243, 173, 26, 4, 37, 215, 146, 67, 45, - 158, 205, 28, 62, 38, 239, 44, 66, 233, 1, 0, 18, 0, 18, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 39, 16, 0, 100, 240, 85, 232, + 7, 1, 0, 0, 0, 10, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 175, 243, 173, 26, 4, + 37, 215, 146, 67, 45, 158, 205, 28, 62, 38, 239, 44, 66, 233, 1, 0, 18, 0, 18, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 16, 0, 100, 240, 85, 232, ]; assert_eq!(bytes, excepted_bytes); diff --git a/types/src/tx_type/full_exit.rs b/types/src/tx_type/full_exit.rs index cea551c2..5f0ab96f 100644 --- a/types/src/tx_type/full_exit.rs +++ b/types/src/tx_type/full_exit.rs @@ -64,8 +64,11 @@ mod test { #[test] fn test_full_exit_get_bytes() { - let address = ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); - let l2_hash = H256::from_str("0xe35f3a39d542f6d276c2f203e8fd64fcb8bf5db062b71ccacf45d5ecd9d456f3").unwrap(); + let address = + ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); + let l2_hash = + H256::from_str("0xe35f3a39d542f6d276c2f203e8fd64fcb8bf5db062b71ccacf45d5ecd9d456f3") + .unwrap(); let default_oracle_price = OraclePrices::default(); let builder = FullExitBuilder { to_chain_id: ChainId(1), @@ -82,8 +85,9 @@ mod test { let full_exit = builder.build(); let bytes = full_exit.get_bytes(); let excepted_bytes = [ - 0, 0, 0, 0, 0, 0, 0, 100, 227, 95, 58, 57, 213, 66, 246, 210, 118, 194, 242, 3, 232, 253, 100, 252, 184, - 191, 93, 176, 98, 183, 28, 202, 207, 69, 213, 236, 217, 212, 86, 243, + 0, 0, 0, 0, 0, 0, 0, 100, 227, 95, 58, 57, 213, 66, 246, 210, 118, 194, 242, 3, 232, + 253, 100, 252, 184, 191, 93, 176, 98, 183, 28, 202, 207, 69, 213, 236, 217, 212, 86, + 243, ]; assert_eq!(bytes, excepted_bytes); } diff --git a/types/src/tx_type/order_matching.rs b/types/src/tx_type/order_matching.rs index 4b84db4d..da91dc33 100644 --- a/types/src/tx_type/order_matching.rs +++ b/types/src/tx_type/order_matching.rs @@ -1,6 +1,8 @@ use crate::basic_types::pack::{pack_fee_amount, pack_token_amount}; use crate::basic_types::pad::pad_front; -use crate::basic_types::params::{ORDERS_BYTES, PRICE_BIT_WIDTH, SIGNED_ORDER_MATCHING_BIT_WIDTH, TX_TYPE_BIT_WIDTH}; +use crate::basic_types::params::{ + ORDERS_BYTES, PRICE_BIT_WIDTH, SIGNED_ORDER_MATCHING_BIT_WIDTH, TX_TYPE_BIT_WIDTH, +}; use crate::basic_types::{AccountId, GetBytes, Nonce, SlotId, SubAccountId, TokenId}; use crate::params::{SIGNED_ORDER_BIT_WIDTH, TOKEN_MAX_PRECISION}; use crate::prelude::OraclePrices; @@ -92,7 +94,10 @@ impl Order { } #[cfg(feature = "ffi")] - pub fn create_signed_order(&self, zklink_signer: Arc) -> Result, ZkSignerError> { + pub fn create_signed_order( + &self, + zklink_signer: Arc, + ) -> Result, ZkSignerError> { let mut order = self.clone(); order.signature = zklink_signer.sign_musig(&order.get_bytes())?; Ok(Arc::new(order)) @@ -243,7 +248,10 @@ impl OrderMatching { } #[cfg(feature = "ffi")] - pub fn eth_signature(&self, eth_signer: Arc) -> Result { + pub fn eth_signature( + &self, + eth_signer: Arc, + ) -> Result { let msg = self.get_eth_sign_msg(); let eth_signature = eth_signer.sign_message(msg.as_bytes())?; let tx_eth_signature = TxLayer1Signature::EthereumSignature(eth_signature); @@ -251,7 +259,10 @@ impl OrderMatching { } #[cfg(not(feature = "ffi"))] - pub fn eth_signature(&self, eth_signer: &EthSigner) -> Result { + pub fn eth_signature( + &self, + eth_signer: &EthSigner, + ) -> Result { let msg = self.get_eth_sign_msg(); let eth_signature = eth_signer.sign_message(msg.as_bytes())?; let tx_eth_signature = TxLayer1Signature::EthereumSignature(eth_signature); diff --git a/types/src/tx_type/transfer.rs b/types/src/tx_type/transfer.rs index 19d64dde..c286559c 100644 --- a/types/src/tx_type/transfer.rs +++ b/types/src/tx_type/transfer.rs @@ -1,7 +1,11 @@ use crate::basic_types::pack::{pack_fee_amount, pack_token_amount}; -use crate::basic_types::{AccountId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress}; +use crate::basic_types::{ + AccountId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress, +}; use crate::tx_type::validator::*; -use crate::tx_type::{ethereum_sign_message_part, starknet_sign_message_part, TxTrait, ZkSignatureTrait}; +use crate::tx_type::{ + ethereum_sign_message_part, starknet_sign_message_part, TxTrait, ZkSignatureTrait, +}; use crate::params::{SIGNED_TRANSFER_BIT_WIDTH, TOKEN_MAX_PRECISION, TX_TYPE_BIT_WIDTH}; #[cfg(feature = "ffi")] @@ -134,7 +138,10 @@ impl Transfer { addr: &str, ) -> Result { let message = self.get_starknet_sign_msg(token_symbol); - let typed_data = TypedData::new(TypedDataMessage::Transaction { message }, chain_id.to_string()); + let typed_data = TypedData::new( + TypedDataMessage::Transaction { message }, + chain_id.to_string(), + ); let signature = starknet_signer.sign_message(&typed_data, addr)?; let tx_eth_signature = TxLayer1Signature::StarkSignature(signature); Ok(tx_eth_signature) @@ -149,7 +156,10 @@ impl Transfer { addr: &str, ) -> Result { let message = self.get_starknet_sign_msg(token_symbol); - let typed_data = TypedData::new(TypedDataMessage::Transaction { message }, chain_id.to_string()); + let typed_data = TypedData::new( + TypedDataMessage::Transaction { message }, + chain_id.to_string(), + ); let signature = starknet_signer.sign_message(&typed_data, addr)?; let tx_eth_signature = TxLayer1Signature::StarkSignature(signature); Ok(tx_eth_signature) @@ -201,7 +211,8 @@ mod test { #[test] fn test_get_bytes() { - let address = ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); + let address = + ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); let ts = 1693472232u32; let builder = TransferBuilder { account_id: AccountId(10), @@ -217,8 +228,9 @@ mod test { let transfer = builder.build(); let bytes = transfer.get_bytes(); let excepted_bytes = [ - 4, 0, 0, 0, 10, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 175, 243, 173, 26, 4, 37, 215, 146, 67, 45, - 158, 205, 28, 62, 38, 239, 44, 66, 233, 1, 0, 18, 0, 0, 4, 226, 0, 0, 96, 0, 0, 0, 1, 100, 240, 85, 232, + 4, 0, 0, 0, 10, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 175, 243, 173, 26, 4, 37, + 215, 146, 67, 45, 158, 205, 28, 62, 38, 239, 44, 66, 233, 1, 0, 18, 0, 0, 4, 226, 0, 0, + 96, 0, 0, 0, 1, 100, 240, 85, 232, ]; assert_eq!(bytes, excepted_bytes); } @@ -230,7 +242,8 @@ mod test { let eth_signature = "0x1f11707e54773e059bc38aa73526fe2b51af9b89a77df731af7bcc429750d0317727a857efda5d79232eb5f9a66ed60a79aad2195d4de1375f5021c0db041b221b"; let signature = "0x7b173e25e484eed3461091430f81b2a5bd7ae792f69701dcb073cb903f8125107ecbe23c307d18007ee43090940a4a43bd02bdcda206ad695f745c2f0a64f4ac4c4c8beb9ed9cbdd0e523e75ffc7dedd0281da4946bb37fa26a04283bd480a04"; let public_key_str = "0x7b173e25e484eed3461091430f81b2a5bd7ae792f69701dcb073cb903f812510"; - let address = ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); + let address = + ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); let builder = TransferBuilder { account_id: AccountId(1), to_address: address, @@ -265,7 +278,10 @@ mod test { let private_key = StarkSigner::new_from_hex_str(private_key_str).unwrap(); let message = tx.get_starknet_sign_msg("USDC"); let addr = "0x04A69b67bcaBfA7D3CCb96e1d25C2e6fC93589fE24A6fD04566B8700ff97a71a"; - let typed_data = TypedData::new(TypedDataMessage::Transaction { message }, "SN_GOERLI".to_string()); + let typed_data = TypedData::new( + TypedDataMessage::Transaction { message }, + "SN_GOERLI".to_string(), + ); let signature = private_key.sign_message(&typed_data, addr).unwrap(); let is_ok = signature.verify(&typed_data, addr).unwrap(); assert!(is_ok); diff --git a/types/src/tx_type/validator.rs b/types/src/tx_type/validator.rs index b150dcaf..846a87f4 100644 --- a/types/src/tx_type/validator.rs +++ b/types/src/tx_type/validator.rs @@ -1,14 +1,15 @@ #![allow(unused_doc_comments)] use crate::basic_types::pack::{is_fee_amount_packable, is_token_amount_packable}; use crate::basic_types::params::{ - GLOBAL_ASSET_ACCOUNT_ID, MARGIN_TOKENS_NUMBER, MAX_ACCOUNT_ID, MAX_CHAIN_ID, MAX_NONCE, MAX_ORDER_NONCE, MAX_PRICE, - MAX_SLOT_ID, MAX_SUB_ACCOUNT_ID, MAX_TOKEN_ID, MIN_PRICE, USDX_TOKEN_ID_LOWER_BOUND, USDX_TOKEN_ID_UPPER_BOUND, - USED_POSITION_NUMBER, USED_POSITION_PAIR_ID_RANGE, + GLOBAL_ASSET_ACCOUNT_ID, MARGIN_TOKENS_NUMBER, MAX_ACCOUNT_ID, MAX_CHAIN_ID, MAX_NONCE, + MAX_ORDER_NONCE, MAX_PRICE, MAX_SLOT_ID, MAX_SUB_ACCOUNT_ID, MAX_TOKEN_ID, MIN_PRICE, + USDX_TOKEN_ID_LOWER_BOUND, USDX_TOKEN_ID_UPPER_BOUND, USED_POSITION_NUMBER, + USED_POSITION_PAIR_ID_RANGE, }; use crate::params::{PAIR_SYMBOL_BYTES, WITHDRAW_FEE_RATIO_DENOMINATOR}; use crate::prelude::{ - AccountId, ChainId, ContractPrice, Nonce, PairId, Parameter, SlotId, SpotPriceInfo, SubAccountId, TokenId, - ZkLinkAddress, + AccountId, ChainId, ContractPrice, Nonce, PairId, Parameter, SlotId, SpotPriceInfo, + SubAccountId, TokenId, ZkLinkAddress, }; use num::{BigUint, Zero}; pub use validator::{Validate, ValidationError}; @@ -102,7 +103,9 @@ pub fn zklink_address_validator(zklink_address: &ZkLinkAddress) -> Result<(), Va return Err(ValidationError::new("zklink address is 0")); } if zklink_address.is_global_account_address() { - return Err(ValidationError::new("zklink address is global asset account address")); + return Err(ValidationError::new( + "zklink address is global asset account address", + )); } Ok(()) } @@ -160,16 +163,22 @@ pub fn margin_rate_validator(margin_ratio: u8) -> Result<(), ValidationError> { /// Check contracts prices infos /// /// - contracts_prices must be ordered by pair_id from smallest to largest -pub fn contract_prices_validator(contracts_prices: &[ContractPrice]) -> Result<(), ValidationError> { +pub fn contract_prices_validator( + contracts_prices: &[ContractPrice], +) -> Result<(), ValidationError> { if contracts_prices.len() != USED_POSITION_NUMBER { return Err(ValidationError::new("contract prices number mismatch")); } for (info, pair_id) in contracts_prices.iter().zip(0..USED_POSITION_NUMBER) { if let Err(e) = info.validate() { - return Err(ValidationError::new(e.into_errors().into_keys().last().unwrap())); + return Err(ValidationError::new( + e.into_errors().into_keys().last().unwrap(), + )); } if *info.pair_id != pair_id as u16 { - return Err(ValidationError::new("contracts prices array are wrong order")); + return Err(ValidationError::new( + "contracts prices array are wrong order", + )); } } Ok(()) @@ -184,7 +193,9 @@ pub fn margin_prices_validator(margin_prices: &[SpotPriceInfo]) -> Result<(), Va } for info in margin_prices.iter() { if let Err(e) = info.validate() { - return Err(ValidationError::new(e.into_errors().into_keys().last().unwrap())); + return Err(ValidationError::new( + e.into_errors().into_keys().last().unwrap(), + )); } } Ok(()) @@ -236,7 +247,9 @@ pub fn nonce_validator(nonce: &Nonce) -> Result<(), ValidationError> { /// - nonce should < MAX_ORDER_NONCE pub fn order_nonce_validator(nonce: &Nonce) -> Result<(), ValidationError> { if *nonce >= MAX_ORDER_NONCE { - return Err(ValidationError::new("The order nonce has reached its maximum.")); + return Err(ValidationError::new( + "The order nonce has reached its maximum.", + )); } Ok(()) } @@ -246,7 +259,9 @@ pub fn order_nonce_validator(nonce: &Nonce) -> Result<(), ValidationError> { /// - funding rate should not eq i16::MIN(for the convenience of the circuit) pub fn funding_rate_validator(rate: i16) -> Result<(), ValidationError> { if rate == i16::MIN { - return Err(ValidationError::new("The funding rate disables i16 minimum value")); + return Err(ValidationError::new( + "The funding rate disables i16 minimum value", + )); } Ok(()) } @@ -261,7 +276,9 @@ pub fn parameter_validator(param: &Parameter) -> Result<(), ValidationError> { } for funding_info in infos { if let Err(e) = funding_info.validate() { - return Err(ValidationError::new(e.into_errors().into_keys().last().unwrap())); + return Err(ValidationError::new( + e.into_errors().into_keys().last().unwrap(), + )); } } } @@ -290,10 +307,14 @@ pub fn parameter_validator(param: &Parameter) -> Result<(), ValidationError> { return Err(ValidationError::new("pair symbol are not ascii chars")); } if symbol.len() > PAIR_SYMBOL_BYTES { - return Err(ValidationError::new("pair symbol chars length out of range")); + return Err(ValidationError::new( + "pair symbol chars length out of range", + )); } if *initial_margin_rate >= 1000 || *maintenance_margin_rate >= 1000 { - return Err(ValidationError::new("initial or maintenance margin rate out of range")); + return Err(ValidationError::new( + "initial or maintenance margin rate out of range", + )); } } } diff --git a/types/src/tx_type/withdraw.rs b/types/src/tx_type/withdraw.rs index c0222342..226cb2fa 100644 --- a/types/src/tx_type/withdraw.rs +++ b/types/src/tx_type/withdraw.rs @@ -10,12 +10,16 @@ use zklink_sdk_signers::zklink_signer::signature::ZkLinkSignature; use zklink_sdk_utils::serde::BigUintSerdeAsRadix10Str; use crate::basic_types::pack::pack_fee_amount; -use crate::basic_types::{AccountId, ChainId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress}; +use crate::basic_types::{ + AccountId, ChainId, GetBytes, Nonce, SubAccountId, TimeStamp, TokenId, ZkLinkAddress, +}; use crate::params::{ORDERS_BYTES, TOKEN_MAX_PRECISION, WITHDRAW_FEE_RATIO_DENOMINATOR}; #[cfg(feature = "ffi")] use crate::prelude::WithdrawBuilder; use crate::tx_type::validator::*; -use crate::tx_type::{ethereum_sign_message_part, starknet_sign_message_part, TxTrait, ZkSignatureTrait}; +use crate::tx_type::{ + ethereum_sign_message_part, starknet_sign_message_part, TxTrait, ZkSignatureTrait, +}; use zklink_sdk_signers::starknet_signer::typed_data::message::TxMessage; use zklink_sdk_signers::zklink_signer::utils::rescue_hash_orders; @@ -197,7 +201,8 @@ mod test { #[test] fn test_get_bytes() { - let address = ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); + let address = + ZkLinkAddress::from_str("0xAFAFf3aD1a0425D792432D9eCD1c3e26Ef2C42E9").unwrap(); let ts = 1693472232u32; let builder = WithdrawBuilder { account_id: AccountId(10), @@ -217,9 +222,9 @@ mod test { let withdraw = builder.build(); let bytes = withdraw.get_bytes(); let excepted_bytes = [ - 35, 38, 100, 21, 162, 218, 169, 88, 46, 176, 84, 204, 61, 64, 69, 248, 70, 224, 44, 240, 208, 221, 29, 8, - 236, 225, 227, 255, 131, 200, 226, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, + 35, 38, 100, 21, 162, 218, 169, 88, 46, 176, 84, 204, 61, 64, 69, 248, 70, 224, 44, + 240, 208, 221, 29, 8, 236, 225, 227, 255, 131, 200, 226, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; assert_eq!(bytes, excepted_bytes); diff --git a/utils/src/serde.rs b/utils/src/serde.rs index 669d7b14..7f8f9be0 100644 --- a/utils/src/serde.rs +++ b/utils/src/serde.rs @@ -65,7 +65,9 @@ impl OptionBytesToHexSerde

{ S: Serializer, { // First, serialize to hexadecimal string. - let hex_value = value.as_ref().map(|val| format!("{}{}", P::prefix(), hex::encode(val))); + let hex_value = value + .as_ref() + .map(|val| format!("{}{}", P::prefix(), hex::encode(val))); // Then, serialize it using `Serialize` trait implementation for `String`. Option::serialize(&hex_value, serializer) @@ -113,7 +115,8 @@ impl BigUintSerdeAsRadix10Str { { use serde::de::Error; let s = String::deserialize(deserializer)?; - let num = BigUint::from_str(&s).map_err(|_| Error::custom("Invalid string type of big unit"))?; + let num = + BigUint::from_str(&s).map_err(|_| Error::custom("Invalid string type of big unit"))?; Ok(num) } } @@ -137,7 +140,8 @@ impl BigIntSerdeAsRadix10Str { { use serde::de::Error; let s = String::deserialize(deserializer)?; - let num = BigInt::from_str(&s).map_err(|_| Error::custom("Invalid string type of big int"))?; + let num = + BigInt::from_str(&s).map_err(|_| Error::custom("Invalid string type of big int"))?; Ok(num) } } diff --git a/wallet/src/eth.rs b/wallet/src/eth.rs index 82a61687..7c26786d 100644 --- a/wallet/src/eth.rs +++ b/wallet/src/eth.rs @@ -84,7 +84,11 @@ pub fn new_typed_tx(from: Address, tx_params: EthTxParam, chain_id: u64) -> Type tx } -pub fn encode_tx(contract: Contract, method: &str, params: Vec) -> Result, WalletError> { +pub fn encode_tx( + contract: Contract, + method: &str, + params: Vec, +) -> Result, WalletError> { let function = contract.function(method)?; let tx_data = function.encode_input(¶ms)?; Ok(tx_data) diff --git a/wallet/src/wallet.rs b/wallet/src/wallet.rs index 987db6e7..1eac618f 100644 --- a/wallet/src/wallet.rs +++ b/wallet/src/wallet.rs @@ -43,7 +43,10 @@ impl Wallet { pub fn get_l1_contract(&self, is_gateway: bool) -> Contract { let contract_name = if is_gateway { "l1_gateway" } else { "zklink" }; - self.contracts.get(&contract_name.to_string()).unwrap().clone() + self.contracts + .get(&contract_name.to_string()) + .unwrap() + .clone() } pub async fn get_balance(&self) -> Result { @@ -52,7 +55,8 @@ impl Wallet { } pub async fn get_nonce(&self, block_number: String) -> Result { - let block_number = BlockNumber::from_str(&block_number).map_err(|_e| WalletError::InvalidInputParameter)?; + let block_number = BlockNumber::from_str(&block_number) + .map_err(|_e| WalletError::InvalidInputParameter)?; let from = self.signer.get_address(); Ok(self .provider @@ -93,7 +97,9 @@ impl Wallet { args: T, ) -> Result, WalletError> { let contract = self.get_l1_contract(is_gateway); - let function = contract.function(method).map_err(WalletError::EthAbiError)?; + let function = contract + .function(method) + .map_err(WalletError::EthAbiError)?; let encoded_data = encode_function_data(function, args).map_err(WalletError::AbiError)?; let params = EthTxParam { data: Some(encoded_data.to_vec()), @@ -102,7 +108,9 @@ impl Wallet { let chain_id = self.provider.get_chainid().await?; let typed_tx = new_call_typed_tx(params, chain_id.as_u64()); let data: Vec = (*(self.provider).call(&typed_tx, None).await?).to_vec(); - let tokens = function.decode_output(&data).map_err(WalletError::EthAbiError)?; + let tokens = function + .decode_output(&data) + .map_err(WalletError::EthAbiError)?; Ok(tokens) } @@ -267,7 +275,8 @@ impl Wallet { eth_params: EthTxOption, ) -> Result { let zklink_addr = Address::from_slice(zklink_addr.as_bytes()); - self.inner_approve_erc20(zklink_addr, amount, eth_params.into()).await + self.inner_approve_erc20(zklink_addr, amount, eth_params.into()) + .await } pub async fn deposit_eth_to_layer1( @@ -356,8 +365,14 @@ impl Wallet { mapping: bool, eth_params: EthTxOption, ) -> Result { - self.inner_full_exit(account_id, sub_account_id, token_id, mapping, eth_params.into()) - .await + self.inner_full_exit( + account_id, + sub_account_id, + token_id, + mapping, + eth_params.into(), + ) + .await } pub async fn inner_get_fee(&self, eth_params: EthTxParam) -> Result {