Skip to content

Commit 5f6f6e7

Browse files
committed
feat: add lib serializer for 0x-prefixed string
1 parent 21fe7da commit 5f6f6e7

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

stacks-common/src/util/serde_serializers.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,23 @@ pub mod prefix_opt_hex_codec {
131131
Ok(Some(val))
132132
}
133133
}
134+
135+
/// Serialize strings as 0x-prefixed strings.
136+
pub mod prefix_string_0x {
137+
use serde::{Deserialize, Deserializer, Serializer};
138+
139+
pub fn serialize<S: Serializer>(val: &str, s: S) -> Result<S::Ok, S::Error> {
140+
s.serialize_str(&format!("0x{}", val))
141+
}
142+
143+
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
144+
let s: String = Deserialize::deserialize(d)?;
145+
let Some(hex_str) = s.get(2..) else {
146+
return Err(serde::de::Error::invalid_length(
147+
s.len(),
148+
&"at least length 2 string",
149+
));
150+
};
151+
Ok(hex_str.to_string())
152+
}
153+
}

testnet/stacks-node/src/event_dispatcher.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,9 @@ use stacks_common::types::chainstate::{BlockHeaderHash, BurnchainHeaderHash, Sta
7878
use stacks_common::types::net::PeerHost;
7979
use stacks_common::util::hash::{bytes_to_hex, Sha512Trunc256Sum};
8080
use stacks_common::util::secp256k1::MessageSignature;
81-
use stacks_common::util::serde_serializers::{prefix_hex, prefix_hex_codec, prefix_opt_hex};
81+
use stacks_common::util::serde_serializers::{
82+
prefix_hex, prefix_hex_codec, prefix_opt_hex, prefix_string_0x,
83+
};
8284
use url::Url;
8385

8486
#[cfg(any(test, feature = "testing"))]
@@ -331,14 +333,6 @@ impl RewardSetEventPayload {
331333
}
332334
}
333335

334-
pub fn hex_prefix_string<S: serde::Serializer>(
335-
hex_string: &String,
336-
s: S,
337-
) -> Result<S::Ok, S::Error> {
338-
let prefixed = format!("0x{hex_string}");
339-
s.serialize_str(&prefixed)
340-
}
341-
342336
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
343337
pub struct TransactionEventPayload<'a> {
344338
#[serde(with = "prefix_hex")]
@@ -352,7 +346,7 @@ pub struct TransactionEventPayload<'a> {
352346
/// The raw transaction result
353347
pub raw_result: Value,
354348
/// The hex encoded raw transaction
355-
#[serde(serialize_with = "hex_prefix_string")]
349+
#[serde(with = "prefix_string_0x")]
356350
pub raw_tx: String,
357351
/// The contract interface
358352
pub contract_interface: Option<ContractInterface>,

0 commit comments

Comments
 (0)