Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add perp js examples #103

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,6 @@ GO_FILES = 1_change_pubkey 2_withdraw 3_transfer 4_forced_exit 5_order_matching
RUN_GO_EXAMPLES = $(patsubst %, run_example_go_%, $(GO_FILES))
run_example_go: ${RUN_GO_EXAMPLES}

JS_FILES = 1_change_pubkey 2_auto_deleveraging 3_update_global_var 4_contract_matching
JS_FILES = 1_change_pubkey 2_auto_deleveraging 3_update_global_var 4_contract_matching 5_liquidation 6_funding
RUN_JS_EXAMPLES = $(patsubst %, run_example_js_%, $(JS_FILES))
run_example_js: ${RUN_JS_EXAMPLES}
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
Loading
Loading