Skip to content

Commit

Permalink
add signMusig for jsonRpcSigner (#277)
Browse files Browse the repository at this point in the history
* add signMusig for jsonRpcSigner

* run ci on apex-devnet

* style(code): rust fmt
  • Loading branch information
zksemi authored May 9, 2024
1 parent 96fe27b commit 400f201
Show file tree
Hide file tree
Showing 73 changed files with 908 additions and 345 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ on:
- zklink_nexus
- v*
- devnet
- apex-devnet
push:
branches:
- main
- testnet
- zklink_nexus
- v*
- devnet
- apex-devnet

jobs:
fmt:
Expand Down
14 changes: 10 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion bindings/dart/test/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Future<void> 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"));
});
}
8 changes: 5 additions & 3 deletions bindings/sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 4 additions & 1 deletion bindings/sdk/src/type_convert/hex_convert.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions bindings/sdk/src/type_convert/number_convert.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
52 changes: 41 additions & 11 deletions bindings/wasm/src/json_rpc_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -38,8 +39,16 @@ pub fn new_with_provider(provider: Provider) -> Result<JsonRpcSigner, JsValue> {
}

#[wasm_bindgen(js_name=newRpcSignerWithSigner)]
pub fn new_with_signer(signer: Signer, pub_key: String, chain_id: String) -> Result<JsonRpcSigner, JsValue> {
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<JsonRpcSigner, JsValue> {
let inner = InterfaceJsonRpcSigner::new(
JsonRpcProvider::Signer(signer),
Some(pub_key),
Some(chain_id),
)?;
Ok(JsonRpcSigner { inner })
}

Expand Down Expand Up @@ -74,15 +83,23 @@ impl JsonRpcSigner {
pub fn sign_change_pubkey_with_onchain(&self, tx: ChangePubKey) -> Result<JsValue, JsValue> {
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<JsValue, JsValue> {
pub async fn sign_change_pubkey_with_eth_ecdsa_auth(
&self,
tx: ChangePubKey,
) -> Result<JsValue, JsValue> {
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)?)
}

Expand All @@ -103,7 +120,11 @@ impl JsonRpcSigner {
}

#[wasm_bindgen(js_name = signTransfer)]
pub async fn sign_transfer(&self, tx: Transfer, token_symbol: &str) -> Result<JsValue, JsValue> {
pub async fn sign_transfer(
&self,
tx: Transfer,
token_symbol: &str,
) -> Result<JsValue, JsValue> {
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?;
Expand All @@ -127,7 +148,11 @@ impl JsonRpcSigner {
}

#[wasm_bindgen(js_name=signWithdraw)]
pub async fn sign_withdraw(&self, tx: Withdraw, token_symbol: &str) -> Result<JsValue, JsValue> {
pub async fn sign_withdraw(
&self,
tx: Withdraw,
token_symbol: &str,
) -> Result<JsValue, JsValue> {
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?;
Expand Down Expand Up @@ -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<u8>) -> Result<TxZkLinkSignature, JsValue> {
Ok(self.inner.sign_musig(msg)?.into())
}
}
98 changes: 82 additions & 16 deletions bindings/wasm/src/rpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down Expand Up @@ -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)]
Expand All @@ -99,7 +106,8 @@ impl RpcClient {
l2_signature: Option<TxZkLinkSignature>,
) -> Result<JsValue, JsValue> {
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 {
Expand All @@ -114,13 +122,23 @@ impl RpcClient {
#[wasm_bindgen(js_name=getSupportChains)]
pub async fn get_support_chains(&self) -> Result<JsValue, JsValue> {
let builder = ArrayParams::new();
rpc_request!("getSupportChains", builder, &self.server_url, Vec<ChainResp>)
rpc_request!(
"getSupportChains",
builder,
&self.server_url,
Vec<ChainResp>
)
}

#[wasm_bindgen(js_name=getLatestBlockNumber)]
pub async fn block_info(&self) -> Result<JsValue, JsValue> {
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)]
Expand Down Expand Up @@ -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<TxHashOrDetailResp>)
rpc_request!(
"getPendingBlock",
builder,
&self.server_url,
Vec<TxHashOrDetailResp>
)
}

#[wasm_bindgen(js_name=getBlockOnChainByNumber)]
pub async fn block_onchain_detail(&self, block_number: u32) -> Result<JsValue, JsValue> {
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)]
Expand All @@ -168,19 +196,37 @@ impl RpcClient {
}

#[wasm_bindgen(js_name=getAccountBalances)]
pub async fn account_balances(&self, account_id: u32, sub_account_id: Option<u8>) -> Result<JsValue, JsValue> {
pub async fn account_balances(
&self,
account_id: u32,
sub_account_id: Option<u8>,
) -> Result<JsValue, JsValue> {
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<u8>) -> Result<JsValue, JsValue> {
pub async fn account_order_slots(
&self,
account_id: u32,
sub_account_id: Option<u8>,
) -> Result<JsValue, JsValue> {
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)]
Expand Down Expand Up @@ -208,7 +254,8 @@ impl RpcClient {
page_index: u64,
page_size: u32,
) -> Result<JsValue, JsValue> {
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);
Expand All @@ -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<JsValue, JsValue> {
pub async fn tx_withdraw(
&self,
last_tx_timestamp: u64,
max_txs: u32,
) -> Result<JsValue, JsValue> {
let mut builder = ArrayParams::new();
let _ = builder.insert(last_tx_timestamp);
let _ = builder.insert(max_txs);
rpc_request!("getWithdrawTxs", builder, &self.server_url, Vec<FastWithdrawTxResp>)
rpc_request!(
"getWithdrawTxs",
builder,
&self.server_url,
Vec<FastWithdrawTxResp>
)
}

#[wasm_bindgen(js_name=pullForwardTxs)]
pub async fn pull_forward_txs(&self, sub_account_id: u8, offset_id: i64, limit: i64) -> Result<JsValue, JsValue> {
pub async fn pull_forward_txs(
&self,
sub_account_id: u8,
offset_id: i64,
limit: i64,
) -> Result<JsValue, JsValue> {
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<ForwardTxResp>)
rpc_request!(
"pullForwardTxs",
builder,
&self.server_url,
Vec<ForwardTxResp>
)
}

#[wasm_bindgen(js_name=getWebSocketEvents)]
Expand Down
Loading

0 comments on commit 400f201

Please sign in to comment.