Skip to content

Commit

Permalink
fix review suggests and add all txs example
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-zkp committed Oct 12, 2023
1 parent d1e1b71 commit 8682f5b
Show file tree
Hide file tree
Showing 23 changed files with 514 additions and 170 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ wasm:
wasm-pack build --release --target=web --out-name=zklink-sdk-web --out-dir=web-dist && \
wasm-pack build --release --target=nodejs --out-name=zklink-sdk-node --out-dir=node-dist
#wasm-pack build --release --target=bundler --out-name=zklink-bundler-node --out-dir=dist
test_wasm:
cd ${ROOT_DIR}/bindings/wasm && \
wasm-pack test --firefox --headless -- --test test_rpc


run_example_go_%: ${ROOT_DIR}/examples/Golang/%.go
Expand Down
1 change: 1 addition & 0 deletions bindings/wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ serde-wasm-bindgen = "0.5"
getrandom = { version = "0.2.10", features = ["js"] }
web-sys = "0.3"
hex = "0.4.3"
serde = "1.0.137"
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "rustls-tls"] }

[target.'cfg(target_arch = "wasm32")'.dependencies]
Expand Down
2 changes: 0 additions & 2 deletions bindings/wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ pub mod rpc_client;
pub mod rpc_type_converter;
pub mod signer;
pub mod tx_types;
// pub mod wallet;
// pub mod error;

extern crate getrandom;
18 changes: 16 additions & 2 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 serde::Deserialize;
use std::collections::HashMap;
use std::str::FromStr;
use wasm_bindgen::prelude::wasm_bindgen;
Expand All @@ -24,6 +25,13 @@ use zklink_sdk_types::signatures::TxLayer1Signature as TypesTxLayer1Signature;
use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx;
use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTxType;

#[derive(Deserialize, Clone)]
pub struct ErrMsg {
#[allow(dead_code)]
code: i32,
message: String,
}

macro_rules! rpc_request {
($method:expr,$builder:expr, $server_url:expr, $resp_type: ty) => {{
let params = $builder
Expand All @@ -47,10 +55,16 @@ macro_rules! rpc_request {
let resp = serde_json::from_value::<$resp_type>(result.clone());
match resp {
Ok(resp) => Ok(serde_wasm_bindgen::to_value(&resp)?),
Err(_e) => Err(RpcError::ParseJsonError.into()),
Err(e) => Err(RpcError::ParseJsonError(e.to_string()).into()),
}
} else if let Some(&ref error) = res.get("error") {
let err_msg = serde_json::from_value::<ErrMsg>(error.clone());
match err_msg {
Ok(msg) => Err(RpcError::GetErrorResult(msg.message).into()),
Err(_) => Err(RpcError::GetErrorResult("Other error response".to_string()).into()),
}
} else {
Err(RpcError::ParseJsonError.into())
Err(RpcError::GetErrorResult("Other error response".to_string()).into())
}
}};
}
Expand Down
40 changes: 40 additions & 0 deletions bindings/wasm/src/signer.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
use crate::tx_types::change_pubkey::{ChangePubKey, Create2Data};
use crate::tx_types::forced_exit::ForcedExit;
use crate::tx_types::order_matching::{Order, OrderMatching};
use crate::tx_types::transfer::Transfer;
use crate::tx_types::withdraw::Withdraw;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use zklink_sdk_interface::signer::Signer as InterfaceSigner;
use zklink_sdk_types::basic_types::ZkLinkAddress;
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::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::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]
Expand Down Expand Up @@ -67,6 +75,38 @@ impl Signer {
Ok(serde_wasm_bindgen::to_value(&signature)?)
}

#[wasm_bindgen(js_name=createSignedOrder)]
pub fn create_signed_order(&self, order: Order) -> Result<JsValue, JsValue> {
let inner_order = order.get_inner_order()?;
let mut order: TxOrder = serde_wasm_bindgen::from_value(inner_order)?;
let signed_order = self.inner.sign_order(&mut order)?;
Ok(serde_wasm_bindgen::to_value(&signed_order)?)
}

#[wasm_bindgen(js_name=signOrderMatching)]
pub fn sign_order_matching(&self, tx: OrderMatching) -> Result<JsValue, JsValue> {
let inner_tx = tx.get_inner_tx()?;
let order_matching: TxOrderMatching = serde_wasm_bindgen::from_value(inner_tx)?;
let signature = self.inner.sign_order_matching(order_matching)?;
Ok(serde_wasm_bindgen::to_value(&signature)?)
}

#[wasm_bindgen(js_name=signWithdraw)]
pub fn sign_withdraw(&self, tx: Withdraw, token_symbol: &str) -> Result<JsValue, JsValue> {
let inner_tx = tx.get_inner_tx()?;
let withdraw: TxWithdraw = serde_wasm_bindgen::from_value(inner_tx)?;
let signature = self.inner.sign_withdraw(withdraw, token_symbol)?;
Ok(serde_wasm_bindgen::to_value(&signature)?)
}

#[wasm_bindgen(js_name=signForcedExit)]
pub fn sign_forced_exit(&self, tx: ForcedExit) -> Result<JsValue, JsValue> {
let inner_tx = tx.get_inner_tx()?;
let forced_exit: TxForcedExit = serde_wasm_bindgen::from_value(inner_tx)?;
let signature = self.inner.sign_forced_exit(forced_exit)?;
Ok(serde_wasm_bindgen::to_value(&signature)?)
}

#[wasm_bindgen(js_name=submitterSignature)]
pub fn submitter_signature(&self, tx: JsValue) -> Result<String, JsValue> {
let zklink_tx: ZkLinkTx = serde_wasm_bindgen::from_value(tx)?;
Expand Down
66 changes: 66 additions & 0 deletions bindings/wasm/src/tx_types/forced_exit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
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::tx_builder::ForcedExitBuilder as TxForcedExitBuilder;
use zklink_sdk_types::tx_type::forced_exit::ForcedExit as ForcedExitTx;

#[wasm_bindgen]
pub struct ForcedExit {
inner: ForcedExitTx,
}

#[wasm_bindgen]
impl ForcedExit {
pub fn get_inner_tx(&self) -> Result<JsValue, JsValue> {
Ok(serde_wasm_bindgen::to_value(&self.inner)?)
}
}

#[wasm_bindgen]
pub struct ForcedExitBuilder {
inner: TxForcedExitBuilder,
}

#[wasm_bindgen]
impl ForcedExitBuilder {
#[wasm_bindgen(constructor)]
pub fn new(
to_chain_id: u8,
initiator_account_id: u32,
initiator_sub_account_id: u8,
target_sub_account_id: u8,
target: String,
l2_source_token: u32,
l1_target_token: u32,
exit_amount: String,
initiator_nonce: u32,
ts: u32,
) -> Result<ForcedExitBuilder, JsValue> {
let inner = TxForcedExitBuilder {
to_chain_id: to_chain_id.into(),
initiator_account_id: initiator_account_id.into(),
initiator_sub_account_id: initiator_sub_account_id.into(),
target: ZkLinkAddress::from_hex(&target)?,
l2_source_token: l2_source_token.into(),
timestamp: ts.into(),
l1_target_token: l1_target_token.into(),
initiator_nonce: initiator_nonce.into(),
target_sub_account_id: target_sub_account_id.into(),
exit_amount: BigUint::from_str(&exit_amount).unwrap(),
};
Ok(ForcedExitBuilder { inner })
}

#[wasm_bindgen]
pub fn build(self) -> ForcedExit {
ForcedExit {
inner: ForcedExitTx::new(self.inner),
}
}
}

#[wasm_bindgen(js_name=newForcedExit)]
pub fn new_forced_exit(builder: ForcedExitBuilder) -> ForcedExit {
builder.build()
}
3 changes: 3 additions & 0 deletions bindings/wasm/src/tx_types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
pub mod change_pubkey;
pub mod forced_exit;
pub mod order_matching;
pub mod transfer;
pub mod withdraw;
108 changes: 108 additions & 0 deletions bindings/wasm/src/tx_types/order_matching.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
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::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,
}

#[wasm_bindgen]
pub struct OrderMatching {
inner: OrderMatchingTx,
}
#[wasm_bindgen]
impl Order {
#[wasm_bindgen(constructor)]
pub fn new(
account_id: u32,
sub_account_id: u8,
slot_id: u32,
nonce: u32,
base_token_id: u32,
quote_token_id: u32,
amount: String,
price: String,
is_sell: bool,
fee_ratio1: u8,
fee_ratio2: u8,
) -> 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(),
is_sell: is_sell as u8,
fee_ratio1,
fee_ratio2,
signature: Default::default(),
},
}
}

pub fn get_inner_order(&self) -> Result<JsValue, JsValue> {
Ok(serde_wasm_bindgen::to_value(&self.inner)?)
}
}

#[wasm_bindgen]
impl OrderMatching {
pub fn get_inner_tx(&self) -> Result<JsValue, JsValue> {
Ok(serde_wasm_bindgen::to_value(&self.inner)?)
}
}

#[wasm_bindgen]
pub struct OrderMatchingBuilder {
inner: TxOrderMatchingBuilder,
}

#[wasm_bindgen]
impl OrderMatchingBuilder {
#[wasm_bindgen(constructor)]
pub fn new(
account_id: u32,
sub_account_id: u8,
taker: JsValue,
maker: JsValue,
fee: String,
fee_token: u32,
expect_base_amount: String,
expect_quote_amount: String,
) -> Result<OrderMatchingBuilder, JsValue> {
let maker: OrderTx = serde_wasm_bindgen::from_value(maker)?;
let taker: OrderTx = serde_wasm_bindgen::from_value(taker)?;
let inner = TxOrderMatchingBuilder {
account_id: account_id.into(),
sub_account_id: sub_account_id.into(),
taker,
fee: BigUint::from_str(&fee).unwrap(),
fee_token: fee_token.into(),
expect_base_amount: BigUint::from_str(&expect_base_amount).unwrap(),
maker,
expect_quote_amount: BigUint::from_str(&expect_quote_amount).unwrap(),
};
Ok(OrderMatchingBuilder { inner })
}

#[wasm_bindgen]
pub fn build(self) -> OrderMatching {
OrderMatching {
inner: OrderMatchingTx::new(self.inner),
}
}
}

#[wasm_bindgen(js_name=newOrderMatching)]
pub fn new_order_matching(builder: OrderMatchingBuilder) -> OrderMatching {
builder.build()
}
70 changes: 70 additions & 0 deletions bindings/wasm/src/tx_types/withdraw.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
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::tx_builder::WithdrawBuilder as TxWithdrawBuilder;
use zklink_sdk_types::tx_type::withdraw::Withdraw as WithdrawTx;

#[wasm_bindgen]
pub struct Withdraw {
inner: WithdrawTx,
}

#[wasm_bindgen]
impl Withdraw {
pub fn get_inner_tx(&self) -> Result<JsValue, JsValue> {
Ok(serde_wasm_bindgen::to_value(&self.inner)?)
}
}

#[wasm_bindgen]
pub struct WithdrawBuilder {
inner: TxWithdrawBuilder,
}

#[wasm_bindgen]
impl WithdrawBuilder {
#[wasm_bindgen(constructor)]
pub fn new(
account_id: u32,
sub_account_id: u8,
to_chain_id: u8,
to_address: String,
l2_source_token: u32,
fee: String,
fast_withdraw: bool,
withdraw_fee_ratio: u16,
l1_target_token: u32,
amount: String,
nonce: u32,
ts: u32,
) -> Result<WithdrawBuilder, JsValue> {
let inner = TxWithdrawBuilder {
account_id: account_id.into(),
sub_account_id: sub_account_id.into(),
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(),
nonce: nonce.into(),
fast_withdraw,
withdraw_fee_ratio,
timestamp: ts.into(),
amount: BigUint::from_str(&amount).unwrap(),
l1_target_token: l1_target_token.into(),
};
Ok(WithdrawBuilder { inner })
}

#[wasm_bindgen]
pub fn build(self) -> Withdraw {
Withdraw {
inner: WithdrawTx::new(self.inner),
}
}
}

#[wasm_bindgen(js_name=newWithdraw)]
pub fn new_withdraw(builder: WithdrawBuilder) -> Withdraw {
builder.build()
}
Loading

0 comments on commit 8682f5b

Please sign in to comment.