Skip to content

Commit 80c1772

Browse files
committed
refactor: cleanups params
1 parent 5eed770 commit 80c1772

File tree

9 files changed

+231
-77
lines changed

9 files changed

+231
-77
lines changed

packages/js-evo-sdk/src/protocol/facade.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,13 @@ export class ProtocolFacade {
77
async versionUpgradeState(): Promise<any> { const w = await this.sdk.getWasmSdkConnected(); return w.getProtocolVersionUpgradeState(); }
88
async versionUpgradeStateWithProof(): Promise<any> { const w = await this.sdk.getWasmSdkConnected(); return w.getProtocolVersionUpgradeStateWithProofInfo(); }
99

10-
async versionUpgradeVoteStatus(params: { startProTxHash: string; count: number }): Promise<any> {
11-
const { startProTxHash, count } = params;
10+
async versionUpgradeVoteStatus(startProTxHash: string | Uint8Array, count: number): Promise<any> {
1211
const w = await this.sdk.getWasmSdkConnected();
13-
return w.getProtocolVersionUpgradeVoteStatus(startProTxHash, count);
12+
return w.getProtocolVersionUpgradeVoteStatus(startProTxHash as any, count);
1413
}
1514

16-
async versionUpgradeVoteStatusWithProof(params: { startProTxHash: string; count: number }): Promise<any> {
17-
const { startProTxHash, count } = params;
15+
async versionUpgradeVoteStatusWithProof(startProTxHash: string | Uint8Array, count: number): Promise<any> {
1816
const w = await this.sdk.getWasmSdkConnected();
19-
return w.getProtocolVersionUpgradeVoteStatusWithProofInfo(startProTxHash, count);
17+
return w.getProtocolVersionUpgradeVoteStatusWithProofInfo(startProTxHash as any, count);
2018
}
2119
}

packages/js-evo-sdk/src/tokens/facade.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export class TokensFacade {
6060
return w.getIdentityTokenBalancesWithProofInfo(identityId, tokenIds);
6161
}
6262

63-
async identityTokenInfos(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[], _opts: { limit?: number; offset?: number } = {}): Promise<any> {
63+
async identityTokenInfos(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise<any> {
6464
const w = await this.sdk.getWasmSdkConnected();
6565
return w.getIdentityTokenInfos(identityId, tokenIds);
6666
}

packages/js-evo-sdk/src/wallet/functions.ts

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,32 +16,24 @@ export namespace wallet {
1616
return wasm.WasmSdk.mnemonicToSeed(mnemonic, passphrase ?? null);
1717
}
1818

19-
export async function deriveKeyFromSeedPhrase(mnemonic: string, passphrase: string | null | undefined, network: string): Promise<any> {
19+
export async function deriveKeyFromSeedPhrase(opts: wasm.DeriveKeyFromSeedPhraseOptions): Promise<any> {
2020
await wasm.ensureInitialized();
21-
return wasm.WasmSdk.deriveKeyFromSeedPhrase(mnemonic, passphrase ?? null, network);
21+
return wasm.WasmSdk.deriveKeyFromSeedPhrase(opts);
2222
}
2323

24-
export async function deriveKeyFromSeedWithPath(mnemonic: string, passphrase: string | null | undefined, path: string, network: string): Promise<any> {
24+
export async function deriveKeyFromSeedWithPath(opts: wasm.DeriveKeyFromSeedWithPathOptions): Promise<any> {
2525
await wasm.ensureInitialized();
26-
return wasm.WasmSdk.deriveKeyFromSeedWithPath(mnemonic, passphrase ?? null, path, network);
26+
return wasm.WasmSdk.deriveKeyFromSeedWithPath(opts);
2727
}
2828

29-
export async function deriveKeyFromSeedWithExtendedPath(mnemonic: string, passphrase: string | null | undefined, path: string, network: string): Promise<any> {
29+
export async function deriveKeyFromSeedWithExtendedPath(opts: wasm.DeriveKeyFromSeedWithExtendedPathOptions): Promise<any> {
3030
await wasm.ensureInitialized();
31-
return wasm.WasmSdk.deriveKeyFromSeedWithExtendedPath(mnemonic, passphrase ?? null, path, network);
31+
return wasm.WasmSdk.deriveKeyFromSeedWithExtendedPath(opts);
3232
}
3333

34-
export async function deriveDashpayContactKey(mnemonic: string, passphrase: string | null | undefined, senderIdentityId: string, receiverIdentityId: string, account: number, addressIndex: number, network: string): Promise<any> {
34+
export async function deriveDashpayContactKey(opts: wasm.DeriveDashpayContactKeyOptions): Promise<any> {
3535
await wasm.ensureInitialized();
36-
return wasm.WasmSdk.deriveDashpayContactKey(
37-
mnemonic,
38-
passphrase ?? null,
39-
senderIdentityId,
40-
receiverIdentityId,
41-
account,
42-
addressIndex,
43-
network,
44-
);
36+
return wasm.WasmSdk.deriveDashpayContactKey(opts);
4537
}
4638

4739
export async function derivationPathBip44Mainnet(account: number, change: number, index: number): Promise<any> {

packages/js-evo-sdk/tests/functional/protocol.spec.mjs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@ describe('Protocol', function protocolSuite() {
1616
});
1717

1818
it('versionUpgradeVoteStatus() returns vote window status', async () => {
19-
const res = await sdk.protocol.versionUpgradeVoteStatus({
20-
startProTxHash: TEST_IDS.proTxHash,
21-
count: 1,
22-
});
19+
const res = await sdk.protocol.versionUpgradeVoteStatus(TEST_IDS.proTxHash, 1);
2320
expect(res).to.exist();
2421
});
2522
});

packages/js-evo-sdk/tests/functional/wallet.spec.mjs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ describe('wallet helpers', () => {
1111
const mnemonic = await wallet.generateMnemonic();
1212
const seed = await wallet.mnemonicToSeed(mnemonic);
1313
expect(seed).to.be.instanceOf(Uint8Array);
14-
expect(await wallet.deriveKeyFromSeedPhrase(mnemonic, null, 'testnet')).to.exist();
15-
expect(await wallet.deriveKeyFromSeedWithPath(mnemonic, null, "m/44'/5'/0'", 'testnet')).to.exist();
16-
expect(await wallet.deriveKeyFromSeedWithExtendedPath(mnemonic, null, "m/15'/0'", 'testnet')).to.exist();
14+
expect(await wallet.deriveKeyFromSeedPhrase({ mnemonic, passphrase: null, network: 'testnet' })).to.exist();
15+
expect(await wallet.deriveKeyFromSeedWithPath({ mnemonic, passphrase: null, path: "m/44'/5'/0'", network: 'testnet' })).to.exist();
16+
expect(await wallet.deriveKeyFromSeedWithExtendedPath({ mnemonic, passphrase: null, path: "m/15'/0'", network: 'testnet' })).to.exist();
1717
});
1818

1919
it('key utilities return expected shapes', async () => {

packages/js-evo-sdk/tests/unit/facades/protocol.spec.mjs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,18 @@ describe('ProtocolFacade', () => {
2424
expect(wasmSdk.getProtocolVersionUpgradeStateWithProofInfo).to.be.calledOnce();
2525
});
2626

27-
it('versionUpgradeVoteStatus and withProof forward with args', async () => {
28-
await client.protocol.versionUpgradeVoteStatus({ startProTxHash: 'h', count: 5 });
29-
await client.protocol.versionUpgradeVoteStatusWithProof({ startProTxHash: 'g', count: 3 });
27+
it('versionUpgradeVoteStatus and withProof forward with positional args', async () => {
28+
await client.protocol.versionUpgradeVoteStatus('h', 5);
29+
await client.protocol.versionUpgradeVoteStatusWithProof('g', 3);
3030
expect(wasmSdk.getProtocolVersionUpgradeVoteStatus).to.be.calledOnceWithExactly('h', 5);
3131
expect(wasmSdk.getProtocolVersionUpgradeVoteStatusWithProofInfo).to.be.calledOnceWithExactly('g', 3);
3232
});
33+
34+
it('versionUpgradeVoteStatus accepts Uint8Array and positional args', async () => {
35+
const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
36+
await client.protocol.versionUpgradeVoteStatus(bytes, 2);
37+
await client.protocol.versionUpgradeVoteStatusWithProof(bytes, 4);
38+
expect(wasmSdk.getProtocolVersionUpgradeVoteStatus).to.be.calledWith(bytes, 2);
39+
expect(wasmSdk.getProtocolVersionUpgradeVoteStatusWithProofInfo).to.be.calledWith(bytes, 4);
40+
});
3341
});

packages/wasm-sdk/src/queries/protocol.rs

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::error::WasmSdkError;
22
use crate::queries::ProofMetadataResponseWasm;
33
use crate::sdk::WasmSdk;
4+
use dash_sdk::dpp::dashcore::hashes::{sha256d, Hash as _};
45
use js_sys::Map;
56
use wasm_bindgen::prelude::wasm_bindgen;
67
use wasm_bindgen::JsValue;
@@ -113,21 +114,39 @@ impl WasmSdk {
113114
#[wasm_bindgen(js_name = "getProtocolVersionUpgradeVoteStatus")]
114115
pub async fn get_protocol_version_upgrade_vote_status(
115116
&self,
116-
#[wasm_bindgen(js_name = "startProTxHash")] start_pro_tx_hash: &str,
117+
#[wasm_bindgen(js_name = "startProTxHash")]
118+
#[wasm_bindgen(unchecked_param_type = "string | Uint8Array")]
119+
start_pro_tx_hash: JsValue,
117120
count: u32,
118121
) -> Result<Map, WasmSdkError> {
119122
use dash_sdk::dpp::dashcore::ProTxHash;
120123
use dash_sdk::platform::types::version_votes::MasternodeProtocolVoteEx;
121124
use drive_proof_verifier::types::MasternodeProtocolVote;
122125
use std::str::FromStr;
123-
let start_hash =
124-
if start_pro_tx_hash.is_empty() {
126+
let start_hash = if let Some(s) = start_pro_tx_hash.as_string() {
127+
if s.is_empty() {
125128
None
126129
} else {
127-
Some(ProTxHash::from_str(start_pro_tx_hash).map_err(|e| {
130+
Some(ProTxHash::from_str(&s).map_err(|e| {
128131
WasmSdkError::invalid_argument(format!("Invalid ProTxHash: {}", e))
129132
})?)
130-
};
133+
}
134+
} else {
135+
let bytes = js_sys::Uint8Array::new(&start_pro_tx_hash).to_vec();
136+
if bytes.is_empty() {
137+
None
138+
} else {
139+
if bytes.len() != 32 {
140+
return Err(WasmSdkError::invalid_argument(
141+
"ProTxHash must be 32 bytes or an empty value",
142+
));
143+
}
144+
let mut arr = [0u8; 32];
145+
arr.copy_from_slice(&bytes);
146+
let raw = sha256d::Hash::from_byte_array(arr);
147+
Some(ProTxHash::from_raw_hash(raw))
148+
}
149+
};
131150
let votes_result =
132151
MasternodeProtocolVote::fetch_votes(self.as_ref(), start_hash, Some(count)).await?;
133152
let votes_map = Map::new();
@@ -183,7 +202,9 @@ impl WasmSdk {
183202
#[wasm_bindgen(js_name = "getProtocolVersionUpgradeVoteStatusWithProofInfo")]
184203
pub async fn get_protocol_version_upgrade_vote_status_with_proof_info(
185204
&self,
186-
#[wasm_bindgen(js_name = "startProTxHash")] start_pro_tx_hash: &str,
205+
#[wasm_bindgen(js_name = "startProTxHash")]
206+
#[wasm_bindgen(unchecked_param_type = "string | Uint8Array")]
207+
start_pro_tx_hash: JsValue,
187208
count: u32,
188209
) -> Result<JsValue, WasmSdkError> {
189210
let _ = (self, start_pro_tx_hash, count);

packages/wasm-sdk/src/wallet/extended_derivation.rs

Lines changed: 94 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,97 @@
33
//! Implements 256-bit derivation paths for DashPay contact keys
44
use crate::error::WasmSdkError;
55
use crate::sdk::WasmSdk;
6+
use crate::queries::utils::deserialize_required_query;
67
use dash_sdk::dpp::dashcore;
78
use dash_sdk::dpp::dashcore::secp256k1::Secp256k1;
89
use dash_sdk::dpp::key_wallet::{bip32, DerivationPath, ExtendedPrivKey};
910
use std::str::FromStr;
1011
use tracing::debug;
1112
use wasm_bindgen::prelude::*;
13+
14+
// TypeScript option bags (module scope) for extended derivation helpers
15+
#[wasm_bindgen(typescript_custom_section)]
16+
const DERIVE_FROM_EXTENDED_PATH_OPTS_TS: &'static str = r#"
17+
export interface DeriveKeyFromSeedWithExtendedPathOptions {
18+
mnemonic: string;
19+
passphrase?: string | null;
20+
path: string;
21+
network: string;
22+
}
23+
"#;
24+
#[wasm_bindgen]
25+
extern "C" {
26+
#[wasm_bindgen(typescript_type = "DeriveKeyFromSeedWithExtendedPathOptions")]
27+
pub type DeriveKeyFromSeedWithExtendedPathOptionsJs;
28+
}
29+
30+
// Inputs parsed from options (module scope)
31+
#[derive(serde::Deserialize)]
32+
#[serde(rename_all = "camelCase")]
33+
struct DeriveFromExtendedPathInput {
34+
mnemonic: String,
35+
#[serde(default)]
36+
passphrase: Option<String>,
37+
path: String,
38+
network: String,
39+
}
40+
41+
#[derive(serde::Deserialize)]
42+
#[serde(rename_all = "camelCase")]
43+
struct DeriveDashpayContactKeyInput {
44+
mnemonic: String,
45+
#[serde(default)]
46+
passphrase: Option<String>,
47+
#[serde(rename = "senderIdentityId")]
48+
sender_identity_id: String,
49+
#[serde(rename = "receiverIdentityId")]
50+
receiver_identity_id: String,
51+
account: u32,
52+
#[serde(rename = "addressIndex")]
53+
address_index: u32,
54+
network: String,
55+
}
56+
57+
#[wasm_bindgen(typescript_custom_section)]
58+
const DERIVE_DASHPAY_CONTACT_KEY_OPTS_TS: &'static str = r#"
59+
export interface DeriveDashpayContactKeyOptions {
60+
mnemonic: string;
61+
passphrase?: string | null;
62+
senderIdentityId: string;
63+
receiverIdentityId: string;
64+
account: number;
65+
addressIndex: number;
66+
network: string;
67+
}
68+
"#;
69+
#[wasm_bindgen]
70+
extern "C" {
71+
#[wasm_bindgen(typescript_type = "DeriveDashpayContactKeyOptions")]
72+
pub type DeriveDashpayContactKeyOptionsJs;
73+
}
1274
#[wasm_bindgen]
1375
impl WasmSdk {
1476
/// Derive a key from seed phrase with extended path supporting 256-bit indices
1577
/// This supports DIP14/DIP15 paths with identity IDs
1678
#[wasm_bindgen(js_name = "deriveKeyFromSeedWithExtendedPath")]
1779
pub fn derive_key_from_seed_with_extended_path(
18-
mnemonic: &str,
19-
passphrase: Option<String>,
20-
path: &str,
21-
network: &str,
80+
#[wasm_bindgen(unchecked_param_type = "DeriveKeyFromSeedWithExtendedPathOptions")] opts: JsValue,
2281
) -> Result<JsValue, WasmSdkError> {
82+
let DeriveFromExtendedPathInput { mnemonic, passphrase, path, network } = deserialize_required_query(
83+
opts,
84+
"Options object is required",
85+
"deriveKeyFromSeedWithExtendedPath options",
86+
)?;
2387
debug!(target : "wasm_sdk", path, "Processing extended path");
24-
let seed = Self::mnemonic_to_seed(mnemonic, passphrase)?;
25-
let net = match network {
88+
let seed = Self::mnemonic_to_seed(&mnemonic, passphrase)?;
89+
let net = match network.as_str() {
2690
"mainnet" => dashcore::Network::Dash,
2791
"testnet" => dashcore::Network::Testnet,
2892
_ => return Err(WasmSdkError::invalid_argument("Invalid network")),
2993
};
3094
let master_key = ExtendedPrivKey::new_master(net, &seed)
3195
.map_err(|e| WasmSdkError::generic(format!("Failed to create master key: {}", e)))?;
32-
let derivation_path = DerivationPath::from_str(path).map_err(|e| {
96+
let derivation_path = DerivationPath::from_str(&path).map_err(|e| {
3397
WasmSdkError::invalid_argument(format!("Invalid derivation path: {}", e))
3498
})?;
3599
let secp = Secp256k1::new();
@@ -41,7 +105,7 @@ impl WasmSdk {
41105
let public_key = private_key.public_key(&secp);
42106
let address = dashcore::Address::p2pkh(&public_key, net);
43107
let obj = js_sys::Object::new();
44-
js_sys::Reflect::set(&obj, &JsValue::from_str("path"), &JsValue::from_str(path))
108+
js_sys::Reflect::set(&obj, &JsValue::from_str("path"), &JsValue::from_str(&path))
45109
.map_err(|_| WasmSdkError::generic("Failed to set path property"))?;
46110
js_sys::Reflect::set(
47111
&obj,
@@ -70,7 +134,7 @@ impl WasmSdk {
70134
js_sys::Reflect::set(
71135
&obj,
72136
&JsValue::from_str("network"),
73-
&JsValue::from_str(network),
137+
&JsValue::from_str(&network),
74138
)
75139
.map_err(|_| WasmSdkError::generic("Failed to set network property"))?;
76140
js_sys::Reflect::set(
@@ -88,34 +152,34 @@ impl WasmSdk {
88152
Ok(obj.into())
89153
}
90154
/// Derive a DashPay contact key using DIP15 with full identity IDs
155+
// Types decoded in parse step are defined at module scope
91156
#[wasm_bindgen(js_name = "deriveDashpayContactKey")]
92157
pub fn derive_dashpay_contact_key(
93-
mnemonic: &str,
94-
passphrase: Option<String>,
95-
#[wasm_bindgen(js_name = "senderIdentityId")] sender_identity_id: &str,
96-
#[wasm_bindgen(js_name = "receiverIdentityId")] receiver_identity_id: &str,
97-
account: u32,
98-
#[wasm_bindgen(js_name = "addressIndex")] address_index: u32,
99-
network: &str,
158+
#[wasm_bindgen(unchecked_param_type = "DeriveDashpayContactKeyOptions")] opts: JsValue,
100159
) -> Result<JsValue, WasmSdkError> {
160+
let DeriveDashpayContactKeyInput { mnemonic, passphrase, sender_identity_id, receiver_identity_id, account, address_index, network } = deserialize_required_query(
161+
opts,
162+
"Options object is required",
163+
"deriveDashpayContactKey options",
164+
)?;
101165
use bs58;
102166
let sender_id_formatted = if sender_identity_id.starts_with("0x") {
103167
sender_identity_id.to_string()
104168
} else {
105-
let bytes = bs58::decode(sender_identity_id).into_vec().map_err(|e| {
169+
let bytes = bs58::decode(&sender_identity_id).into_vec().map_err(|e| {
106170
WasmSdkError::invalid_argument(format!("Invalid sender identity ID: {}", e))
107171
})?;
108172
format!("0x{}", hex::encode(bytes))
109173
};
110174
let receiver_id_formatted = if receiver_identity_id.starts_with("0x") {
111175
receiver_identity_id.to_string()
112176
} else {
113-
let bytes = bs58::decode(receiver_identity_id).into_vec().map_err(|e| {
177+
let bytes = bs58::decode(&receiver_identity_id).into_vec().map_err(|e| {
114178
WasmSdkError::invalid_argument(format!("Invalid receiver identity ID: {}", e))
115179
})?;
116180
format!("0x{}", hex::encode(bytes))
117181
};
118-
let coin_type = match network {
182+
let coin_type = match network.as_str() {
119183
"mainnet" => 5,
120184
"testnet" => 1,
121185
_ => return Err(WasmSdkError::invalid_argument("Invalid network")),
@@ -125,8 +189,15 @@ impl WasmSdk {
125189
coin_type, 15, account, sender_id_formatted, receiver_id_formatted, address_index
126190
);
127191
debug!(target : "wasm_sdk", path = % path, "DashPay contact path");
128-
let result =
129-
Self::derive_key_from_seed_with_extended_path(mnemonic, passphrase, &path, network)?;
192+
let opts = serde_json::json!({
193+
"mnemonic": mnemonic,
194+
"passphrase": passphrase,
195+
"path": path,
196+
"network": network,
197+
});
198+
let js_opts = serde_wasm_bindgen::to_value(&opts)
199+
.map_err(|e| WasmSdkError::serialization(format!("Failed to serialize options: {}", e)))?;
200+
let result = Self::derive_key_from_seed_with_extended_path(js_opts)?;
130201
let obj = result
131202
.dyn_into::<js_sys::Object>()
132203
.map_err(|_| WasmSdkError::generic("Failed to cast result to object"))?;
@@ -145,13 +216,13 @@ impl WasmSdk {
145216
js_sys::Reflect::set(
146217
&obj,
147218
&JsValue::from_str("senderIdentity"),
148-
&JsValue::from_str(sender_identity_id),
219+
&JsValue::from_str(&sender_identity_id),
149220
)
150221
.map_err(|_| WasmSdkError::generic("Failed to set senderIdentity property"))?;
151222
js_sys::Reflect::set(
152223
&obj,
153224
&JsValue::from_str("receiverIdentity"),
154-
&JsValue::from_str(receiver_identity_id),
225+
&JsValue::from_str(&receiver_identity_id),
155226
)
156227
.map_err(|_| WasmSdkError::generic("Failed to set receiverIdentity property"))?;
157228
js_sys::Reflect::set(

0 commit comments

Comments
 (0)