Skip to content

Commit

Permalink
Replace the unwrap used in wasm to convert string to biguint (fix #99) (
Browse files Browse the repository at this point in the history
#100)

* Replace the unwrap used in wasm to convert string to biguint (fix #99)

* replace unwrap used in sdk

* fix review suggests
  • Loading branch information
nick-zkp authored Nov 30, 2023
1 parent 272e4b4 commit 5388453
Show file tree
Hide file tree
Showing 14 changed files with 104 additions and 68 deletions.
14 changes: 10 additions & 4 deletions bindings/wasm/src/rpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use jsonrpsee::core::params::ArrayParams;
use jsonrpsee::core::traits::ToRpcParams;
use jsonrpsee::types::request::Request;
use jsonrpsee::types::Id;
use std::convert::TryFrom;
use std::str::FromStr;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
Expand Down Expand Up @@ -61,13 +62,13 @@ pub struct RpcClient {
#[wasm_bindgen]
impl RpcClient {
#[wasm_bindgen(constructor)]
pub fn new(network: &str, custom_url: Option<String>) -> RpcClient {
pub fn new(network: &str, custom_url: Option<String>) -> Result<RpcClient, JsValue> {
let server_url = if let Ok(network) = Network::from_str(network) {
network.url().to_owned()
} else {
custom_url.unwrap()
custom_url.ok_or(RpcError::InvalidNetwork)?
};
RpcClient { server_url }
Ok(RpcClient { server_url })
}

#[wasm_bindgen(js_name=getSupportTokens)]
Expand Down Expand Up @@ -105,8 +106,13 @@ impl RpcClient {
let mut builder = ArrayParams::new();
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 {
None
};
let _ = builder.insert(zklink_tx);
let _ = builder.insert(l1_signature.map(|t| TypesTxLayer1Signature::from(t)));
let _ = builder.insert(l1_signature);
let _ = builder.insert(l2_signature.map(|s| ZkLinkSignature::from(s)));
rpc_request!("sendTransaction", builder, &self.server_url, TxHash)
}
Expand Down
46 changes: 27 additions & 19 deletions bindings/wasm/src/rpc_type_converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,18 +110,26 @@ impl TxLayer1Signature {
}
}

impl From<TxLayer1Signature> for TypesTxLayer1Signature {
fn from(signature: TxLayer1Signature) -> TypesTxLayer1Signature {
impl TryFrom<TxLayer1Signature> for TypesTxLayer1Signature {
type Error = JsValue;

fn try_from(signature: TxLayer1Signature) -> Result<TypesTxLayer1Signature, Self::Error> {
match signature.sign_type {
L1SignatureType::Eth => TypesTxLayer1Signature::EthereumSignature(
PackedEthSignature::from_hex(&signature.signature).unwrap(),
),
L1SignatureType::Eip1271 => TypesTxLayer1Signature::EIP1271Signature(EIP1271Signature(
hex::decode(signature.signature).unwrap(),
)),
L1SignatureType::Stark => TypesTxLayer1Signature::StarkSignature(StarkECDSASignature(
hex::decode(signature.signature).unwrap(),
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 => {
Ok(TypesTxLayer1Signature::StarkSignature(StarkECDSASignature(
hex::decode(signature.signature)
.map_err(|e| JsValue::from_str(&format!("error: {e}")))?,
)))
}
}
}
}
Expand Down Expand Up @@ -158,20 +166,20 @@ impl ZkLinkTx {
}
}

impl From<ZkLinkTx> for TypesZkLinkTx {
fn from(tx: ZkLinkTx) -> TypesZkLinkTx {
impl TryFrom<ZkLinkTx> for TypesZkLinkTx {
type Error = JsValue;

fn try_from(tx: ZkLinkTx) -> Result<TypesZkLinkTx, Self::Error> {
match tx.tx_type {
ChangePubKey::TX_TYPE => {
let change_pubkey: ChangePubKey = serde_wasm_bindgen::from_value(tx.tx).unwrap();
TypesZkLinkTx::ChangePubKey(Box::new(change_pubkey))
let change_pubkey: ChangePubKey = serde_wasm_bindgen::from_value(tx.tx)?;
Ok(TypesZkLinkTx::ChangePubKey(Box::new(change_pubkey)))
}
Transfer::TX_TYPE => {
let transfer: Transfer = serde_wasm_bindgen::from_value(tx.tx).unwrap();
TypesZkLinkTx::Transfer(Box::new(transfer))
}
_ => {
panic!("Not support tx type!")
let transfer: Transfer = serde_wasm_bindgen::from_value(tx.tx)?;
Ok(TypesZkLinkTx::Transfer(Box::new(transfer)))
}
_ => Err(JsValue::from_str(&format!("error: Invalid tx type"))),
}
}
}
3 changes: 2 additions & 1 deletion bindings/wasm/src/tx_types/change_pubkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use zklink_sdk_signers::eth_signer::packed_eth_signature::PackedEthSignature;
use zklink_sdk_signers::zklink_signer::pubkey_hash::PubKeyHash;
use zklink_sdk_types::basic_types::{BigUint, ZkLinkAddress};
use zklink_sdk_types::error::TypeError;
use zklink_sdk_types::error::TypeError::InvalidBigIntStr;
use zklink_sdk_types::prelude::H256;
use zklink_sdk_types::tx_builder::ChangePubKeyBuilder as TxChangePubKeyBuilder;
use zklink_sdk_types::tx_type::change_pubkey::{
Expand Down Expand Up @@ -109,7 +110,7 @@ impl ChangePubKeyBuilder {
sub_account_id: sub_account_id.into(),
new_pubkey_hash: PubKeyHash::from_hex(&new_pubkey_hash)?,
fee_token: fee_token.into(),
fee: BigUint::from_str(&fee).unwrap(),
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
nonce: nonce.into(),
eth_signature,
timestamp: ts.into(),
Expand Down
8 changes: 5 additions & 3 deletions bindings/wasm/src/tx_types/contract/auto_deleveraging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
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_builder::AutoDeleveragingBuilder as TxAutoDeleveragingBuilder;
use zklink_sdk_types::tx_type::contract::{
AutoDeleveraging as AutoDeleveragingTx, ContractPrice as InnerContractPrice,
Expand Down Expand Up @@ -58,9 +59,10 @@ impl AutoDeleveragingBuilder {
margin_prices,
adl_account_id: adl_account_id.into(),
pair_id: pair_id.into(),
adl_size: BigUint::from_str(&adl_size).unwrap(),
adl_price: BigUint::from_str(&adl_price).unwrap(),
fee: BigUint::from_str(&fee).unwrap(),
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()))?,
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
fee_token: fee_token.into(),
};
Ok(AutoDeleveragingBuilder { inner })
Expand Down
7 changes: 4 additions & 3 deletions bindings/wasm/src/tx_types/contract/contract_matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
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_builder::{
ContractBuilder as TxContractBuilder, ContractMatchingBuilder as TxContractMatchingBuilder,
};
Expand Down Expand Up @@ -48,7 +49,7 @@ impl ContractMatchingBuilder {
sub_account_id: sub_account_id.into(),
taker,
maker,
fee: BigUint::from_str(&fee).unwrap(),
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
fee_token: fee_token.into(),
};
Ok(ContractMatchingBuilder { inner })
Expand Down Expand Up @@ -107,8 +108,8 @@ impl ContractBuilder {
slot_id: slot_id.into(),
nonce: nonce.into(),
pair_id: pair_id.into(),
size: BigUint::from_str(&size).unwrap(),
price: BigUint::from_str(&price).unwrap(),
size: BigUint::from_str(&size).map_err(|e| InvalidBigIntStr(e.to_string()))?,
price: BigUint::from_str(&price).map_err(|e| InvalidBigIntStr(e.to_string()))?,
direction,
maker_fee_rate,
taker_fee_rate,
Expand Down
11 changes: 6 additions & 5 deletions bindings/wasm/src/tx_types/contract/funding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
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_builder::FundingBuilder as TxFundingBuilder;
use zklink_sdk_types::tx_type::contract::{
Funding as InnerFunding, FundingInfo as InnerFundingInfo,
Expand All @@ -15,14 +16,14 @@ pub struct FundingInfo {
#[wasm_bindgen]
impl FundingInfo {
#[wasm_bindgen(constructor)]
pub fn new(pair_id: u16, funding_rate: i16, price: String) -> FundingInfo {
FundingInfo {
pub fn new(pair_id: u16, funding_rate: i16, price: String) -> Result<FundingInfo, JsValue> {
Ok(FundingInfo {
inner: InnerFundingInfo {
pair_id: pair_id.into(),
price: BigUint::from_str(&price).unwrap(),
price: BigUint::from_str(&price).map_err(|e| InvalidBigIntStr(e.to_string()))?,
funding_rate,
},
}
})
}

#[wasm_bindgen(js_name=jsonValue)]
Expand Down Expand Up @@ -68,7 +69,7 @@ impl FundingBuilder {
account_id: account_id.into(),
sub_account_id: sub_account_id.into(),
sub_account_nonce: sub_account_nonce.into(),
fee: BigUint::from_str(&fee).unwrap(),
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
fee_token: fee_token.into(),
funding_account_ids,
};
Expand Down
3 changes: 2 additions & 1 deletion bindings/wasm/src/tx_types/contract/liquidation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
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_builder::LiquidationBuilder as TxLiquidationBuilder;
use zklink_sdk_types::tx_type::contract::Liquidation as LiquidationTx;
use zklink_sdk_types::tx_type::contract::{
Expand Down Expand Up @@ -53,7 +54,7 @@ impl LiquidationBuilder {
contract_prices,
margin_prices,
liquidation_account_id: liquidation_account_id.into(),
fee: BigUint::from_str(&fee).unwrap(),
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
fee_token: fee_token.into(),
};
Ok(LiquidationBuilder { inner })
Expand Down
18 changes: 10 additions & 8 deletions bindings/wasm/src/tx_types/contract/prices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
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,
};
Expand All @@ -14,13 +15,14 @@ pub struct ContractPrice {
#[wasm_bindgen]
impl ContractPrice {
#[wasm_bindgen(constructor)]
pub fn new(pair_id: u16, market_price: String) -> ContractPrice {
ContractPrice {
pub fn new(pair_id: u16, market_price: String) -> Result<ContractPrice, JsValue> {
Ok(ContractPrice {
inner: InnerContractPrice {
pair_id: pair_id.into(),
market_price: BigUint::from_str(&market_price).unwrap(),
market_price: BigUint::from_str(&market_price)
.map_err(|e| InvalidBigIntStr(e.to_string()))?,
},
}
})
}

#[wasm_bindgen(js_name=jsonValue)]
Expand All @@ -36,13 +38,13 @@ pub struct SpotPriceInfo {
#[wasm_bindgen]
impl SpotPriceInfo {
#[wasm_bindgen(constructor)]
pub fn new(token_id: u32, price: String) -> SpotPriceInfo {
SpotPriceInfo {
pub fn new(token_id: u32, price: String) -> Result<SpotPriceInfo, JsValue> {
Ok(SpotPriceInfo {
inner: InnerSpotPriceInfo {
token_id: token_id.into(),
price: BigUint::from_str(&price).unwrap(),
price: BigUint::from_str(&price).map_err(|e| InvalidBigIntStr(e.to_string()))?,
},
}
})
}

#[wasm_bindgen(js_name=jsonValue)]
Expand Down
4 changes: 3 additions & 1 deletion bindings/wasm/src/tx_types/forced_exit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use zklink_sdk_types::basic_types::{BigUint, ZkLinkAddress};
use zklink_sdk_types::error::TypeError::InvalidBigIntStr;
use zklink_sdk_types::tx_builder::ForcedExitBuilder as TxForcedExitBuilder;
use zklink_sdk_types::tx_type::forced_exit::ForcedExit as ForcedExitTx;

Expand Down Expand Up @@ -54,7 +55,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).unwrap(),
exit_amount: BigUint::from_str(&exit_amount)
.map_err(|e| InvalidBigIntStr(e.to_string()))?,
};
Ok(ForcedExitBuilder { inner })
}
Expand Down
21 changes: 13 additions & 8 deletions bindings/wasm/src/tx_types/order_matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ use std::str::FromStr;
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_builder::OrderMatchingBuilder as TxOrderMatchingBuilder;
use zklink_sdk_types::tx_type::order_matching::{
Order as OrderTx, OrderMatching as OrderMatchingTx,
};

#[wasm_bindgen]
pub struct Order {
inner: OrderTx,
Expand All @@ -31,23 +33,24 @@ impl Order {
maker_fee_rate: u8,
taker_fee_rate: u8,
has_subsidy: bool,
) -> Order {
Order {
) -> Result<Order, JsValue> {
let order = Order {
inner: OrderTx {
account_id: account_id.into(),
sub_account_id: sub_account_id.into(),
slot_id: slot_id.into(),
nonce: nonce.into(),
base_token_id: base_token_id.into(),
quote_token_id: quote_token_id.into(),
amount: BigUint::from_str(&amount).unwrap(),
price: BigUint::from_str(&price).unwrap(),
amount: BigUint::from_str(&amount).map_err(|e| InvalidBigIntStr(e.to_string()))?,
price: BigUint::from_str(&price).map_err(|e| InvalidBigIntStr(e.to_string()))?,
is_sell: is_sell as u8,
fee_rates: [maker_fee_rate, taker_fee_rate],
has_subsidy: has_subsidy as u8,
signature: Default::default(),
},
}
};
Ok(order)
}

pub fn json_value(&self) -> Result<JsValue, JsValue> {
Expand Down Expand Up @@ -86,11 +89,13 @@ impl OrderMatchingBuilder {
account_id: account_id.into(),
sub_account_id: sub_account_id.into(),
taker,
fee: BigUint::from_str(&fee).unwrap(),
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).unwrap(),
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).unwrap(),
expect_quote_amount: BigUint::from_str(&expect_quote_amount)
.map_err(|e| InvalidBigIntStr(e.to_string()))?,
};
Ok(OrderMatchingBuilder { inner })
}
Expand Down
5 changes: 3 additions & 2 deletions bindings/wasm/src/tx_types/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use zklink_sdk_types::basic_types::{BigUint, ZkLinkAddress};
use zklink_sdk_types::error::TypeError::InvalidBigIntStr;
use zklink_sdk_types::tx_builder::TransferBuilder as TxTransferBuilder;
use zklink_sdk_types::tx_type::transfer::Transfer as TransferTx;

Expand Down Expand Up @@ -47,10 +48,10 @@ impl TransferBuilder {
from_sub_account_id: from_sub_account_id.into(),
to_sub_account_id: to_sub_account_id.into(),
token: token.into(),
fee: BigUint::from_str(&fee).unwrap(),
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
nonce: nonce.into(),
timestamp: ts.into(),
amount: BigUint::from_str(&amount).unwrap(),
amount: BigUint::from_str(&amount).map_err(|e| InvalidBigIntStr(e.to_string()))?,
};
Ok(TransferBuilder { inner })
}
Expand Down
5 changes: 3 additions & 2 deletions bindings/wasm/src/tx_types/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::str::FromStr;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use zklink_sdk_types::basic_types::{BigUint, ZkLinkAddress};
use zklink_sdk_types::error::TypeError::InvalidBigIntStr;
use zklink_sdk_types::tx_builder::WithdrawBuilder as TxWithdrawBuilder;
use zklink_sdk_types::tx_type::withdraw::Withdraw as WithdrawTx;

Expand Down Expand Up @@ -50,11 +51,11 @@ impl WithdrawBuilder {
to_chain_id: to_chain_id.into(),
to_address: ZkLinkAddress::from_hex(&to_address)?,
l2_source_token: l2_source_token.into(),
fee: BigUint::from_str(&fee).unwrap(),
fee: BigUint::from_str(&fee).map_err(|e| InvalidBigIntStr(e.to_string()))?,
nonce: nonce.into(),
withdraw_fee_ratio,
timestamp: ts.into(),
amount: BigUint::from_str(&amount).unwrap(),
amount: BigUint::from_str(&amount).map_err(|e| InvalidBigIntStr(e.to_string()))?,
l1_target_token: l1_target_token.into(),
withdraw_to_l1,
};
Expand Down
Loading

0 comments on commit 5388453

Please sign in to comment.