From faffc6c7b0950112315a7f64159d72ce776a9d17 Mon Sep 17 00:00:00 2001 From: nickwest Date: Tue, 10 Oct 2023 21:54:15 -0700 Subject: [PATCH] Make the calling processes of wasm and golang consistent --- bindings/wasm/Cargo.toml | 1 + bindings/wasm/src/crypto.rs | 77 ---------- bindings/wasm/src/lib.rs | 2 +- bindings/wasm/src/rpc_client.rs | 33 ++--- bindings/wasm/src/rpc_type_converter.rs | 2 +- bindings/wasm/src/signer.rs | 76 ++++++++++ bindings/wasm/src/tx_types/change_pubkey.rs | 131 ++++++++++-------- bindings/wasm/src/tx_types/transfer.rs | 74 +++++----- .../tests/{test_provider.rs => test_rpc.rs} | 0 .../Javascript/js-example/1_change_pubkey.js | 58 ++------ examples/Javascript/js-example/2_transfer.js | 25 ++-- examples/Javascript/js-example/index.html | 5 +- interface/Cargo.toml | 1 + interface/src/error.rs | 9 ++ provider/Cargo.toml | 1 - provider/src/error.rs | 3 +- signers/src/eth_signer/pk_signer.rs | 2 - types/Cargo.toml | 2 +- types/src/error.rs | 9 ++ 19 files changed, 250 insertions(+), 261 deletions(-) delete mode 100644 bindings/wasm/src/crypto.rs create mode 100644 bindings/wasm/src/signer.rs rename bindings/wasm/tests/{test_provider.rs => test_rpc.rs} (100%) diff --git a/bindings/wasm/Cargo.toml b/bindings/wasm/Cargo.toml index 664c1351..80e781a1 100644 --- a/bindings/wasm/Cargo.toml +++ b/bindings/wasm/Cargo.toml @@ -11,6 +11,7 @@ crate-type = ["cdylib","rlib"] zklink_sdk_signers = { path = "../../signers" } zklink_sdk_types = { path = "../../types" } zklink_sdk_provider = { path = "../../provider" } +zklink_sdk_interface = { path = "../../interface" } serde_json = "1.0" wasm-bindgen = { version = "0.2.87",features = ["serde-serialize"] } serde-wasm-bindgen = "0.5" diff --git a/bindings/wasm/src/crypto.rs b/bindings/wasm/src/crypto.rs deleted file mode 100644 index 3aab81be..00000000 --- a/bindings/wasm/src/crypto.rs +++ /dev/null @@ -1,77 +0,0 @@ -use wasm_bindgen::prelude::*; -use zklink_sdk_signers::eth_signer::pk_signer::EthSigner; -use zklink_sdk_signers::zklink_signer::pk_signer::ZkLinkSigner as Signer; -use zklink_sdk_signers::zklink_signer::signature::ZkLinkSignature as Signature; - -#[wasm_bindgen] -pub struct EthPrivateKeySigner { - inner: EthSigner, -} - -#[wasm_bindgen] -impl EthPrivateKeySigner { - #[wasm_bindgen(js_name=newFromHexPrivateKey)] - pub fn new_from_hex_pk(private_key: &str) -> Result { - let signer = EthSigner::try_from(private_key)?; - Ok(Self { inner: signer }) - } - - #[wasm_bindgen(js_name=getAddress)] - pub fn get_address(&self) -> String { - let address = self.inner.get_address(); - format!("{:?}", address) - } - #[wasm_bindgen(js_name=signMessage)] - pub fn sign_message(&self, msg: &[u8]) -> Result { - let signature = self.inner.sign_message(msg)?; - Ok(signature.as_hex()) - } -} - -#[wasm_bindgen] -pub struct ZklinkSigner { - inner: Signer, -} - -#[wasm_bindgen] -impl ZklinkSigner { - #[wasm_bindgen(js_name=newRand)] - pub fn new_rand() -> Result { - let zklink_signer = Signer::new()?; - Ok(ZklinkSigner { - inner: zklink_signer, - }) - } - - #[wasm_bindgen(js_name=newFromEthSigner)] - pub fn new_from_hex_eth_signer(eth_hex_private_key: &str) -> Result { - let zklink_signer = Signer::new_from_hex_eth_signer(eth_hex_private_key)?; - Ok(ZklinkSigner { - inner: zklink_signer, - }) - } - - #[wasm_bindgen] - pub fn sign(&self, msg: &[u8]) -> Result { - let signature = self.inner.sign_musig(msg)?; - Ok(signature.as_hex()) - } -} - -#[wasm_bindgen] -pub struct ZklinkSignature { - inner: Signature, -} - -#[wasm_bindgen] -impl ZklinkSignature { - #[wasm_bindgen(js_name=newFromHexStr)] - pub fn new_from_hex_str(signature_str: &str) -> Result { - let signature = Signature::from_hex(signature_str)?; - Ok(ZklinkSignature { inner: signature }) - } - #[wasm_bindgen] - pub fn verify(&self, msg: &[u8]) -> bool { - self.inner.verify_musig(msg) - } -} diff --git a/bindings/wasm/src/lib.rs b/bindings/wasm/src/lib.rs index 047377a2..5bb43983 100644 --- a/bindings/wasm/src/lib.rs +++ b/bindings/wasm/src/lib.rs @@ -1,7 +1,7 @@ #![cfg(target_arch = "wasm32")] -pub mod crypto; pub mod rpc_client; pub mod rpc_type_converter; +pub mod signer; pub mod tx_types; // pub mod wallet; // pub mod error; diff --git a/bindings/wasm/src/rpc_client.rs b/bindings/wasm/src/rpc_client.rs index 0b99e3f7..99ad24d6 100644 --- a/bindings/wasm/src/rpc_client.rs +++ b/bindings/wasm/src/rpc_client.rs @@ -1,24 +1,28 @@ use crate::rpc_type_converter::{AccountQueryParam, SignedTransaction, TxL1Signature}; +use getrandom::getrandom; +use jsonrpsee::core::params::ArrayParams; +use jsonrpsee::core::traits::ToRpcParams; +use jsonrpsee::types::request::Request; +use jsonrpsee::types::Id; use std::collections::HashMap; use std::str::FromStr; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; use zklink_sdk_provider::error::RpcError; use zklink_sdk_provider::network::Network; -use zklink_sdk_provider::response::{AccountInfoResp, AccountSnapshotResp, BlockNumberResp, BlockOnChainResp, BlockResp, ChainResp, FastWithdrawTxResp, ForwardTxResp, Page, SubAccountBalances, SubAccountOrders, TokenResp, TxHashOrDetailResp, TxResp, ZkLinkTxHistory, AccountQuery}; +use zklink_sdk_provider::response::{ + AccountInfoResp, AccountQuery, AccountSnapshotResp, BlockNumberResp, BlockOnChainResp, + BlockResp, ChainResp, FastWithdrawTxResp, ForwardTxResp, Page, SubAccountBalances, + SubAccountOrders, TokenResp, TxHashOrDetailResp, TxResp, ZkLinkTxHistory, +}; use zklink_sdk_signers::zklink_signer::ZkLinkSignature; use zklink_sdk_types::basic_types::bigunit_wrapper::BigUintSerdeWrapper; use zklink_sdk_types::basic_types::tx_hash::TxHash; use zklink_sdk_types::basic_types::{AccountId, BlockNumber, ChainId, SubAccountId, TokenId}; use zklink_sdk_types::prelude::ZkLinkAddress; -use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTxType; -use getrandom::getrandom; -use jsonrpsee::core::params::ArrayParams; -use jsonrpsee::core::traits::ToRpcParams; -use jsonrpsee::types::request::Request; -use jsonrpsee::types::Id; use zklink_sdk_types::signatures::TxLayer1Signature; use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx; +use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTxType; macro_rules! rpc_request { ($method:expr,$builder:expr, $server_url:expr, $resp_type: ty) => {{ @@ -42,12 +46,8 @@ macro_rules! rpc_request { if let Some(&ref result) = res.get("result") { 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()) - } + Ok(resp) => Ok(serde_wasm_bindgen::to_value(&resp)?), + Err(_e) => Err(RpcError::ParseJsonError.into()), } } else { Err(RpcError::ParseJsonError.into()) @@ -96,7 +96,7 @@ impl RpcClient { ) -> Result { let mut builder = ArrayParams::new(); let _ = builder.insert(AccountQuery::from(account_query)); - let _ = builder.insert(sub_account_id.map(|id| SubAccountId(id)),); + let _ = builder.insert(sub_account_id.map(|id| SubAccountId(id))); let _ = builder.insert(block_number.map(|number| BlockNumber(number))); rpc_request!( "getAccountSnapshot", @@ -109,12 +109,13 @@ impl RpcClient { #[wasm_bindgen(js_name=sendTransaction)] pub async fn send_transaction( &self, - tx: SignedTransaction, + tx: JsValue, l1_signature: Option, l2_signature: Option, ) -> Result { let mut builder = ArrayParams::new(); - let _ = builder.insert(ZkLinkTx::from(tx)); + let zklink_tx: ZkLinkTx = serde_wasm_bindgen::from_value(tx)?; + let _ = builder.insert(zklink_tx); let _ = builder.insert(l1_signature.map(|t| TxLayer1Signature::from(t))); let _ = builder.insert(l2_signature.map(|s| ZkLinkSignature::from_hex(&s).unwrap())); rpc_request!("sendTransaction", builder, &self.server_url, TxHash) diff --git a/bindings/wasm/src/rpc_type_converter.rs b/bindings/wasm/src/rpc_type_converter.rs index cf9a2ef6..707ec35c 100644 --- a/bindings/wasm/src/rpc_type_converter.rs +++ b/bindings/wasm/src/rpc_type_converter.rs @@ -119,4 +119,4 @@ impl From for ZkLinkTx { } } } -} \ No newline at end of file +} diff --git a/bindings/wasm/src/signer.rs b/bindings/wasm/src/signer.rs new file mode 100644 index 00000000..0d02dbec --- /dev/null +++ b/bindings/wasm/src/signer.rs @@ -0,0 +1,76 @@ +use crate::tx_types::change_pubkey::{ChangePubKey, Create2Data}; +use crate::tx_types::transfer::Transfer; +use std::str::FromStr; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsValue; +use zklink_sdk_interface::signer::Signer as InterfaceSigner; +use zklink_sdk_signers::eth_signer::EthSigner; +use zklink_sdk_signers::zklink_signer::ZkLinkSigner; +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::transfer::Transfer as TxTransfer; +use zklink_sdk_types::tx_type::zklink_tx::ZkLinkTx; + +#[wasm_bindgen] +pub struct Signer { + inner: InterfaceSigner, +} + +#[wasm_bindgen] +impl Signer { + #[wasm_bindgen(constructor)] + pub fn new(private_key: &str) -> Result { + let inner = InterfaceSigner::new(private_key)?; + Ok(Signer { inner }) + } + + #[wasm_bindgen(js_name=signChangePubkeyWithEthEcdsaAuth)] + pub fn sign_change_pubkey_with_eth_ecdsa_auth( + &self, + tx: ChangePubKey, + l1_client_id: u32, + main_contract: &str, + ) -> Result { + let inner_tx = tx.get_inner_tx()?; + let change_pubkey: TxChangePubKey = serde_wasm_bindgen::from_value(inner_tx)?; + let contract_address = ZkLinkAddress::from_hex(main_contract)?; + let signature = self.inner.sign_change_pubkey_with_eth_ecdsa_auth( + change_pubkey, + l1_client_id, + contract_address, + )?; + Ok(serde_wasm_bindgen::to_value(&signature)?) + } + + #[wasm_bindgen(js_name=signChangePubkeyWithCreate2DataAuth)] + pub fn sign_change_pubkey_with_create2data_auth( + &self, + tx: ChangePubKey, + create2_data: Create2Data, + ) -> Result { + let inner_tx = tx.get_inner_tx()?; + let change_pubkey: TxChangePubKey = serde_wasm_bindgen::from_value(inner_tx)?; + let inner_data = create2_data.get_inner_data()?; + let create2_data: ChangePubKeyCreate2Data = serde_wasm_bindgen::from_value(inner_data)?; + let signature = self + .inner + .sign_change_pubkey_with_create2data_auth(change_pubkey, create2_data)?; + Ok(serde_wasm_bindgen::to_value(&signature)?) + } + + #[wasm_bindgen(js_name=signTransfer)] + pub fn sign_transfer(&self, tx: Transfer, token_symbol: &str) -> Result { + let inner_tx = tx.get_inner_tx()?; + let transfer: TxTransfer = serde_wasm_bindgen::from_value(inner_tx)?; + let signature = self.inner.sign_transfer(transfer, token_symbol)?; + Ok(serde_wasm_bindgen::to_value(&signature)?) + } + + #[wasm_bindgen(js_name=submitterSignature)] + pub fn submitter_signature(&self, tx: JsValue) -> Result { + let zklink_tx: ZkLinkTx = serde_wasm_bindgen::from_value(tx)?; + let zklink_signature = self.inner.submitter_signature(&zklink_tx)?; + Ok(zklink_signature.as_hex()) + } +} diff --git a/bindings/wasm/src/tx_types/change_pubkey.rs b/bindings/wasm/src/tx_types/change_pubkey.rs index 96aaec6a..d7d617f9 100644 --- a/bindings/wasm/src/tx_types/change_pubkey.rs +++ b/bindings/wasm/src/tx_types/change_pubkey.rs @@ -1,13 +1,15 @@ -use crate::crypto::ZklinkSigner; use std::str::FromStr; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; 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::{AccountId, BigUint, TokenId, ZkLinkAddress}; -use zklink_sdk_types::prelude::{ChainId, Nonce, SubAccountId, TimeStamp, ZkLinkSignature}; -use zklink_sdk_types::tx_builder::ChangePubKeyBuilder; -use zklink_sdk_types::tx_type::change_pubkey::ChangePubKey as ChangePubkeyTx; +use zklink_sdk_types::error::TypeError; +use zklink_sdk_types::prelude::{ChainId, Nonce, SubAccountId, TimeStamp, ZkLinkSignature, H256}; +use zklink_sdk_types::tx_builder::ChangePubKeyBuilder as TxChangePubKeyBuilder; +use zklink_sdk_types::tx_type::change_pubkey::{ + ChangePubKey as ChangePubkeyTx, Create2Data as ChangePubKeyCreate2Data, +}; use zklink_sdk_types::tx_type::TxTrait; #[wasm_bindgen] @@ -17,84 +19,103 @@ pub enum EthAuthType { EthCREATE2, } +#[wasm_bindgen] +pub struct Create2Data { + inner: ChangePubKeyCreate2Data, +} + #[wasm_bindgen] pub struct ChangePubKey { inner: ChangePubkeyTx, } #[wasm_bindgen] -impl ChangePubKey { +impl Create2Data { #[wasm_bindgen(constructor)] - pub fn new( - chain_id: u8, - account_id: u32, - sub_account_id: u8, - new_pubkey_hash: String, - fee_token: u32, - fee: String, - nonce: u32, - eth_signature: Option, - ts: u32, - ) -> Result { - let eth_signature = if let Some(signature) = eth_signature { - Some(PackedEthSignature::from_hex(&signature)?) - } else { - None - }; - let change_pubkey_builder = ChangePubKeyBuilder { - chain_id: ChainId(chain_id), - account_id: AccountId(account_id), - sub_account_id: SubAccountId(sub_account_id), - new_pubkey_hash: PubKeyHash::from_hex(&new_pubkey_hash).unwrap(), - fee_token: TokenId(fee_token), - fee: BigUint::from_str(&fee).unwrap(), - nonce: Nonce(nonce), - eth_signature, - timestamp: TimeStamp(ts), + 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()))?, }; - Ok(ChangePubKey { - inner: ChangePubkeyTx::new(change_pubkey_builder), + Ok(Create2Data { + inner: create2_data, }) } - #[wasm_bindgen(js_name=getTxType)] - pub fn get_tx_type(&self) -> u8 { - ChangePubkeyTx::TX_TYPE - } - - #[wasm_bindgen(js_name=getTx)] - pub fn get_tx(&mut self) -> JsValue { - serde_wasm_bindgen::to_value(&self.inner).unwrap() + pub fn get_inner_data(&self) -> Result { + Ok(serde_wasm_bindgen::to_value(&self.inner)?) } +} - #[wasm_bindgen] - pub fn sign(&mut self, signer: &mut ZklinkSigner) -> Result { - let msg = self.inner.get_bytes(); - Ok(signer.sign(&msg)?) +#[wasm_bindgen] +impl ChangePubKey { + pub fn get_inner_tx(&self) -> Result { + Ok(serde_wasm_bindgen::to_value(&self.inner)?) } - #[wasm_bindgen(js_name = getChangePubkeyMessage)] pub fn get_change_pubkey_message( &self, layer_one_chain_id: u32, verifying_contract: String, ) -> Result { - let contract = ZkLinkAddress::from_str(&verifying_contract).unwrap_or_default(); + let contract = ZkLinkAddress::from_str(&verifying_contract)?; let typed_data = self .inner .to_eip712_request_payload(layer_one_chain_id, &contract)?; Ok(typed_data.raw_data) } +} + +#[wasm_bindgen] +pub struct ChangePubKeyBuilder { + inner: TxChangePubKeyBuilder, +} - #[wasm_bindgen(js_name = setL2Signature)] - pub fn set_zklink_signature(&mut self, signature: String) -> Result<(), JsValue> { - self.inner.signature = ZkLinkSignature::from_hex(&signature)?; - Ok(()) +#[wasm_bindgen] +impl ChangePubKeyBuilder { + #[wasm_bindgen(constructor)] + pub fn new( + chain_id: u8, + account_id: u32, + sub_account_id: u8, + new_pubkey_hash: String, + fee_token: u16, + fee: String, + nonce: u32, + eth_signature: Option, + timestamp: u32, + ) -> Result { + let eth_signature = if let Some(s) = eth_signature { + Some(PackedEthSignature::from_hex(&s)?) + } else { + None + }; + let inner = TxChangePubKeyBuilder { + chain_id: chain_id.into(), + account_id: account_id.into(), + 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(), + nonce: nonce.into(), + eth_signature, + timestamp: timestamp.into(), + }; + Ok(ChangePubKeyBuilder { inner }) } - #[wasm_bindgen(js_name = submitterSign)] - pub fn submitter_sign(&mut self, signer: &mut ZklinkSigner) -> Result { - let tx_hash = self.inner.tx_hash(); - Ok(signer.sign(&tx_hash)?) + #[wasm_bindgen] + pub fn build_change_pubkey(self) -> ChangePubKey { + ChangePubKey { + inner: ChangePubkeyTx::new(self.inner), + } } } + +#[wasm_bindgen(js_name=newChangePubkey)] +pub fn new_change_pubkey(builder: ChangePubKeyBuilder) -> ChangePubKey { + builder.build_change_pubkey() +} diff --git a/bindings/wasm/src/tx_types/transfer.rs b/bindings/wasm/src/tx_types/transfer.rs index 30fa635c..52ed4891 100644 --- a/bindings/wasm/src/tx_types/transfer.rs +++ b/bindings/wasm/src/tx_types/transfer.rs @@ -1,10 +1,9 @@ -use crate::crypto::ZklinkSigner; use std::str::FromStr; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; use zklink_sdk_types::basic_types::{AccountId, BigUint, TokenId, ZkLinkAddress}; use zklink_sdk_types::prelude::{Nonce, SubAccountId, TimeStamp, ZkLinkSignature}; -use zklink_sdk_types::tx_builder::TransferBuilder; +use zklink_sdk_types::tx_builder::TransferBuilder as TxTransferBuilder; use zklink_sdk_types::tx_type::transfer::Transfer as TransferTx; use zklink_sdk_types::tx_type::TxTrait; @@ -15,6 +14,18 @@ pub struct Transfer { #[wasm_bindgen] impl Transfer { + pub fn get_inner_tx(&self) -> Result { + Ok(serde_wasm_bindgen::to_value(&self.inner)?) + } +} + +#[wasm_bindgen] +pub struct TransferBuilder { + inner: TxTransferBuilder, +} + +#[wasm_bindgen] +impl TransferBuilder { #[wasm_bindgen(constructor)] pub fn new( account_id: u32, @@ -26,53 +37,30 @@ impl Transfer { amount: String, nonce: u32, ts: u32, - ) -> Result { - let transfer_builder = TransferBuilder { - account_id: AccountId(account_id), - to_address: ZkLinkAddress::from_str(&to_address).unwrap(), - from_sub_account_id: SubAccountId(from_sub_account_id), - to_sub_account_id: SubAccountId(to_sub_account_id), - token: TokenId(token), + ) -> Result { + let inner = TxTransferBuilder { + account_id: account_id.into(), + to_address: ZkLinkAddress::from_hex(&to_address)?, + 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(), - nonce: Nonce(nonce), - timestamp: TimeStamp(ts), + nonce: nonce.into(), + timestamp: ts.into(), amount: BigUint::from_str(&amount).unwrap(), }; - Ok(Transfer { - inner: TransferTx::new(transfer_builder), - }) + Ok(TransferBuilder { inner }) } #[wasm_bindgen] - pub fn sign(&mut self, signer: &mut ZklinkSigner) -> Result { - let msg = self.inner.get_bytes(); - Ok(signer.sign(&msg)?) - } - - #[wasm_bindgen(js_name = getEthSignMessage)] - pub fn get_eth_sign_message(&self, token_symbol: String) -> String { - self.inner.get_eth_sign_msg(&token_symbol) - } - - #[wasm_bindgen(js_name=getTxType)] - pub fn get_tx_type(&self) -> u8 { - TransferTx::TX_TYPE - } - - #[wasm_bindgen(js_name=getTx)] - pub fn get_tx(&mut self) -> JsValue { - serde_wasm_bindgen::to_value(&self.inner).unwrap() - } - - #[wasm_bindgen(js_name = setL2Signature)] - pub fn set_zklink_signature(&mut self, signature: String) -> Result<(), JsValue> { - self.inner.signature = ZkLinkSignature::from_hex(&signature)?; - Ok(()) + pub fn build_transfer(self) -> Transfer { + Transfer { + inner: TransferTx::new(self.inner), + } } +} - #[wasm_bindgen(js_name = submitterSign)] - pub fn submitter_sign(&mut self, signer: &mut ZklinkSigner) -> Result { - let tx_hash = self.inner.tx_hash(); - Ok(signer.sign(&tx_hash)?) - } +#[wasm_bindgen(js_name=newTransfer)] +pub fn new_transfer(builder: TransferBuilder) -> Transfer { + builder.build_transfer() } diff --git a/bindings/wasm/tests/test_provider.rs b/bindings/wasm/tests/test_rpc.rs similarity index 100% rename from bindings/wasm/tests/test_provider.rs rename to bindings/wasm/tests/test_rpc.rs diff --git a/examples/Javascript/js-example/1_change_pubkey.js b/examples/Javascript/js-example/1_change_pubkey.js index 60cd6f2a..f3ee027a 100644 --- a/examples/Javascript/js-example/1_change_pubkey.js +++ b/examples/Javascript/js-example/1_change_pubkey.js @@ -1,59 +1,29 @@ import init, * as wasm from "./web-dist/zklink-sdk-web.js"; -async function getChangePubkeyData( - auth_type, - main_contract, - l1_client_id, - chain_id, - account_id, - sub_account_id, - new_pubkey_hash, - fee_token, - fee, - nonce, - ts, -) { - // var authData: wasm.; - // if (auth_type == 'OnChain') { - // - // } else if (auth_type == '') { - // - // } else { - // - // } - console.log("getChangePubkeyData"); - let tx = new wasm.ChangePubKey(chain_id, account_id, sub_account_id, new_pubkey_hash, fee_token, fee, nonce, null, ts); - let message = tx.getChangePubkeyMessage(l1_client_id,main_contract); - console.log(message); - return message; -} async function main() { await init(); const private_key = "be725250b123a39dab5b7579334d5888987c72a58f4508062545fe6e08ca94f4"; - const eth_signer = wasm.EthPrivateKeySigner.newFromHexPrivateKey(private_key); - const zklink_signer = wasm.ZklinkSigner.newFromEthSigner(private_key); const main_contract = "0x5505a8cD4594Dbf79d8C59C0Df1414AB871CA896"; const l1_client_id = 80001; const new_pubkey_hash = "0xd8d5fb6a6caef06aa3dc2abdcdc240987e5330fe"; const ts = Math.floor(Date.now() / 1000); - //auth type 'ECDSA' - let message = getChangePubkeyData('EthECDSA',main_contract,l1_client_id,1,10,1,new_pubkey_hash,18,"100000000000000",1,ts); - const msg = new TextEncoder().encode(message); try { - let signature = eth_signer.signMessage(msg); - console.log(signature); - let tx = new wasm.ChangePubKey(1, 10, 1, new_pubkey_hash, 18, "100000000000000", 1, signature, ts); - let tx_signature = tx.sign(zklink_signer); + let tx_builder = new wasm.ChangePubKeyBuilder( + 1,5,1,new_pubkey_hash,18,"100000000000000", + 1,"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001b", + ts); + let tx = wasm.newChangePubkey(tx_builder); + const signer = new wasm.Signer(private_key); + //auth type 'ECDSA' + let tx_signature = signer.signChangePubkeyWithEthEcdsaAuth(tx,l1_client_id,main_contract); console.log(tx_signature); - tx.setL2Signature(tx_signature); - //send to zklink - let provder = new wasm.Provider("testnet"); - let signed_tx = new wasm.SignedTransaction(tx.getTxType(),tx.getTx()); - console.log(signed_tx); - let l1_signature = new wasm.TxL1Signature(wasm.L1SignatureType.Eth,signature); - let submitter_signature = tx.submitterSign(zklink_signer); + //auth type 'Create2' + //0x0000000000000000000000000000000000000000000000000000000000000000 + let submitter_signature = signer.SubmitterSignature(tx_signature.tx); console.log(submitter_signature); - let tx_hash = await provder.sendTransaction(signed_tx,l1_signature,submitter_signature); + //send to zklink + let rpc_client = new wasm.RpcClient("testnet"); + let tx_hash = await rpc_client.sendTransaction(tx_signature.tx,null,submitter_signature); console.log(tx_hash); } catch (error) { diff --git a/examples/Javascript/js-example/2_transfer.js b/examples/Javascript/js-example/2_transfer.js index e8a67e11..68f0c420 100644 --- a/examples/Javascript/js-example/2_transfer.js +++ b/examples/Javascript/js-example/2_transfer.js @@ -3,27 +3,20 @@ import init, * as wasm from "./web-dist/zklink-sdk-web.js"; async function main() { await init(); const private_key = "be725250b123a39dab5b7579334d5888987c72a58f4508062545fe6e08ca94f4"; - const eth_signer = wasm.EthPrivateKeySigner.newFromHexPrivateKey(private_key); - const zklink_signer = wasm.ZklinkSigner.newFromEthSigner(private_key); const to_address = "0x5505a8cD4594Dbf79d8C59C0Df1414AB871CA896"; const ts = Math.floor(Date.now() / 1000); - let tx = new wasm.Transfer(10, to_address, 1, 1, 18, "100000000000000", "10000000000000000", 1,ts); - let message = tx.getEthSignMessage("USDT"); - const msg = new TextEncoder().encode(message); try { - let signature = eth_signer.signMessage(msg); + let tx_builder = new wasm.TransferBuilder(10, to_address, 1, 1, 18, "100000000000000", "10000000000000000", 1,ts); + let transfer = wasm.newTransfer(tx_builder); + let signer = new wasm.Signer(private_key); + let signature = signer.signTransfer(transfer,"USDC") console.log(signature); - let tx_signature = tx.sign(zklink_signer); - console.log(tx_signature); - tx.setL2Signature(tx_signature); - //send to zklink - let provder = new wasm.Provider("testnet"); - let signed_tx = new wasm.SignedTransaction(tx.getTxType(),tx.getTx()); - console.log(signed_tx); - let l1_signature = new wasm.TxL1Signature(wasm.L1SignatureType.Eth,signature); - let submitter_signature = tx.submitterSign(zklink_signer); + + let submitter_signature = signer.submitterSignature(signature.tx); console.log(submitter_signature); - let tx_hash = await provder.sendTransaction(signed_tx,l1_signature,submitter_signature); + let rpc_client = new wasm.RpcClient("testnet"); + let l1_signature = new wasm.TxL1Signature(wasm.L1SignatureType.Eth,signature.eth_signature); + let tx_hash = await rpc_client.sendTransaction(signature.tx,l1_signature,submitter_signature); console.log(tx_hash); } catch (error) { diff --git a/examples/Javascript/js-example/index.html b/examples/Javascript/js-example/index.html index 44271a6f..fa5163ce 100644 --- a/examples/Javascript/js-example/index.html +++ b/examples/Javascript/js-example/index.html @@ -6,8 +6,9 @@ - - \ No newline at end of file diff --git a/interface/Cargo.toml b/interface/Cargo.toml index 56143676..b60a9596 100644 --- a/interface/Cargo.toml +++ b/interface/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] thiserror = "1.0" +wasm-bindgen = { version = "0.2.87", features = ["serde-serialize"] } zklink_sdk_signers = { path = "../signers" } zklink_sdk_types = { path = "../types" } diff --git a/interface/src/error.rs b/interface/src/error.rs index 12e6ccd1..3d4b12d9 100644 --- a/interface/src/error.rs +++ b/interface/src/error.rs @@ -1,4 +1,6 @@ use thiserror::Error; +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::JsValue; use zklink_sdk_signers::eth_signer::error::EthSignerError; use zklink_sdk_signers::zklink_signer::error::ZkSignerError; @@ -11,3 +13,10 @@ pub enum SignError { #[error("Incorrect tx format")] IncorrectTx, } + +#[cfg(target_arch = "wasm32")] +impl From for JsValue { + fn from(error: SignError) -> Self { + JsValue::from_str(&format!("error: {error}")) + } +} diff --git a/provider/Cargo.toml b/provider/Cargo.toml index af31f504..ca388e4e 100644 --- a/provider/Cargo.toml +++ b/provider/Cargo.toml @@ -9,7 +9,6 @@ bigdecimal = { version = "0.3.0", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] } reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "rustls-tls"] } serde = "1.0.137" -serde_json = "1.0" thiserror = "1.0" wasm-bindgen = { version = "0.2.87", features = ["serde-serialize"] } zklink_sdk_signers = { path = "../signers" } diff --git a/provider/src/error.rs b/provider/src/error.rs index ea73a27d..c676958d 100644 --- a/provider/src/error.rs +++ b/provider/src/error.rs @@ -18,9 +18,8 @@ pub enum RpcError { ParseJsonError, } - impl From for JsValue { fn from(error: RpcError) -> Self { JsValue::from_str(&format!("error: {error}")) } -} \ No newline at end of file +} diff --git a/signers/src/eth_signer/pk_signer.rs b/signers/src/eth_signer/pk_signer.rs index d48deaed..807f344a 100644 --- a/signers/src/eth_signer/pk_signer.rs +++ b/signers/src/eth_signer/pk_signer.rs @@ -7,9 +7,7 @@ use ethers::types::transaction::eip2718::TypedTransaction; use ethers::types::TxHash; use ethers::utils::hash_message; use k256::ecdsa::SigningKey; -use wasm_bindgen::prelude::wasm_bindgen; -#[wasm_bindgen] #[derive(Clone)] pub struct EthSigner { private_key: H256, diff --git a/types/Cargo.toml b/types/Cargo.toml index fe776dba..d07847ca 100644 --- a/types/Cargo.toml +++ b/types/Cargo.toml @@ -12,9 +12,9 @@ serde = "1.0.137" serde_json = "1.0.0" thiserror = "1.0" validator = { version = "0.15", features = ["derive"] } +wasm-bindgen = { version = "0.2.87", features = ["serde-serialize"] } zklink_sdk_signers = { path = "../signers" } zklink_sdk_utils = { path = "../utils" } -wasm-bindgen = { version = "0.2.87", features = ["serde-serialize"] } [dev-dependencies] diff --git a/types/src/error.rs b/types/src/error.rs index 6d72a5a6..bc448a42 100644 --- a/types/src/error.rs +++ b/types/src/error.rs @@ -1,4 +1,6 @@ use thiserror::Error; +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::JsValue; #[derive(Debug, Error, PartialEq)] pub enum TypeError { @@ -15,3 +17,10 @@ pub enum TypeError { #[error("Integer is too big")] TooBigInteger, } + +#[cfg(target_arch = "wasm32")] +impl From for JsValue { + fn from(error: TypeError) -> Self { + JsValue::from_str(&format!("error: {error}")) + } +}