Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(sdk): Return Bytes when using Vec<u8> in params and result #428

Merged
merged 1 commit into from
Nov 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions sdk/src/event_listener/tangle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,28 @@ impl_value_to_field_type!(
AccountId32 => Field::AccountId
);

impl<T: ValueIntoFieldType> ValueIntoFieldType for Vec<T> {
impl<T: ValueIntoFieldType + 'static> ValueIntoFieldType for Vec<T> {
fn into_field_type(self) -> Field<AccountId32> {
Field::Array(BoundedVec(
self.into_iter()
.map(ValueIntoFieldType::into_field_type)
.collect(),
))
if core::any::TypeId::of::<T>() == core::any::TypeId::of::<u8>() {
let (ptr, length, capacity) = {
let mut me = core::mem::ManuallyDrop::new(self);
(me.as_mut_ptr() as *mut u8, me.len(), me.capacity())
};
// SAFETY: We are converting a Vec<T> to Vec<u8> only when T is u8.
// This is safe because the memory layout of Vec<u8> is the same as Vec<T> when T is u8.
// We use ManuallyDrop to prevent double-freeing the memory.
// Vec::from_raw_parts takes ownership of the raw parts, ensuring proper deallocation.
#[allow(unsafe_code)]
Field::Bytes(BoundedVec(unsafe {
Vec::from_raw_parts(ptr, length, capacity)
}))
} else {
Field::List(BoundedVec(
self.into_iter()
.map(ValueIntoFieldType::into_field_type)
.collect(),
))
}
}
}

Expand Down
Loading