Skip to content

Commit

Permalink
fix: serde wasm32 target
Browse files Browse the repository at this point in the history
  • Loading branch information
dudong2 committed Apr 18, 2023
1 parent cb1a355 commit 34416b9
Show file tree
Hide file tree
Showing 9 changed files with 37 additions and 27 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions packages/storage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ iterator = ["cosmwasm-std/iterator"]
# Uses the path when built locally; uses the given version from crates.io when published
cosmwasm-std = { path = "../std", version = "1.1.9-0.7.0", default-features = false }
serde = { version = "1.0.103", default-features = false, features = ["derive", "alloc"] }
serde_json = "1.0.40"
8 changes: 5 additions & 3 deletions packages/storage/src/bucket.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use serde::{de::DeserializeOwned, ser::Serialize};
use std::marker::PhantomData;
use std::any::type_name;
use serde_json::to_vec;

use cosmwasm_std::{to_vec, StdError, StdResult, Storage};
use cosmwasm_std::{StdError, StdResult, Storage};
#[cfg(feature = "iterator")]
use cosmwasm_std::{Order, Record};

Expand Down Expand Up @@ -61,7 +63,7 @@ where

/// save will serialize the model and store, returns an error on serialization issues
pub fn save(&mut self, key: &[u8], data: &T) -> StdResult<()> {
set_with_prefix(self.storage, &self.prefix, key, &to_vec(data)?);
set_with_prefix(self.storage, &self.prefix, key, &to_vec(data).map_err(|e| StdError::serialize_err(type_name::<T>(), e))?);
Ok(())
}

Expand Down Expand Up @@ -385,7 +387,7 @@ mod tests {
return Err(StdError::generic_err("Current age is negative").into());
}
if data.age > 10 {
to_vec(&data)?; // Uses From to convert StdError to MyError
to_vec(&data).map_err(|e| StdError::serialize_err(type_name::<Data>(), e))?; // Uses From to convert StdError to MyError
}
data.age += 1;
Ok(data)
Expand Down
8 changes: 5 additions & 3 deletions packages/storage/src/singleton.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use serde::{de::DeserializeOwned, ser::Serialize};
use std::marker::PhantomData;
use std::any::type_name;
use serde_json::to_vec;

use cosmwasm_std::{to_vec, StdError, StdResult, Storage};
use cosmwasm_std::{StdError, StdResult, Storage};

use crate::length_prefixed::to_length_prefixed;
use crate::type_helpers::{may_deserialize, must_deserialize};
Expand Down Expand Up @@ -50,7 +52,7 @@ where

/// save will serialize the model and store, returns an error on serialization issues
pub fn save(&mut self, data: &T) -> StdResult<()> {
self.storage.set(&self.key, &to_vec(data)?);
self.storage.set(&self.key, &to_vec(data).map_err(|e| StdError::serialize_err(type_name::<T>(), e))?);
Ok(())
}

Expand Down Expand Up @@ -296,7 +298,7 @@ mod tests {
return Err(StdError::generic_err("broken stuff").into()); // Uses Into to convert StdError to MyError
}
if c.max_tokens > 10 {
to_vec(&c)?; // Uses From to convert StdError to MyError
to_vec(&c).map_err(|e| StdError::serialize_err(type_name::<Config>(), e))?; // Uses From to convert StdError to MyError
}
c.max_tokens += 20;
Ok(c)
Expand Down
9 changes: 5 additions & 4 deletions packages/storage/src/type_helpers.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use serde::de::DeserializeOwned;
use std::any::type_name;
use serde_json::from_slice;

#[cfg(feature = "iterator")]
use cosmwasm_std::Record;
use cosmwasm_std::{from_slice, StdError, StdResult};
use cosmwasm_std::{StdError, StdResult};

/// may_deserialize parses json bytes from storage (Option), returning Ok(None) if no data present
///
Expand All @@ -13,23 +14,23 @@ pub(crate) fn may_deserialize<T: DeserializeOwned>(
value: &Option<Vec<u8>>,
) -> StdResult<Option<T>> {
match value {
Some(data) => Ok(Some(from_slice(data)?)),
Some(data) => Ok(Some(from_slice(data).map_err(|e| StdError::parse_err(type_name::<T>(), e))?)),
None => Ok(None),
}
}

/// must_deserialize parses json bytes from storage (Option), returning NotFound error if no data present
pub(crate) fn must_deserialize<T: DeserializeOwned>(value: &Option<Vec<u8>>) -> StdResult<T> {
match value {
Some(data) => from_slice(data),
Some(data) => from_slice(data).map_err(|e| StdError::parse_err(type_name::<T>(), e)),
None => Err(StdError::not_found(type_name::<T>())),
}
}

#[cfg(feature = "iterator")]
pub(crate) fn deserialize_kv<T: DeserializeOwned>(kv: Record<Vec<u8>>) -> StdResult<Record<T>> {
let (k, v) = kv;
let t = from_slice::<T>(&v)?;
let t = from_slice::<T>(&v).map_err(|e| StdError::parse_err(type_name::<T>(), e))?;
Ok((k, t))
}

Expand Down
3 changes: 2 additions & 1 deletion packages/vm/benches/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::thread;
use std::time::{Duration, SystemTime};
use tempfile::TempDir;

use cosmwasm_std::{coins, to_vec, Addr, Empty};
use cosmwasm_std::{coins, Addr, Empty};
use cosmwasm_vm::testing::{
mock_backend, mock_env, mock_info, mock_instance, mock_instance_options,
write_data_to_mock_env, MockApi, MockInstanceOptions, MockQuerier, MockStorage, INSTANCE_CACHE,
Expand All @@ -17,6 +17,7 @@ use cosmwasm_vm::{
Backend, BackendApi, BackendError, BackendResult, Cache, CacheOptions, Checksum, Environment,
FunctionMetadata, GasInfo, Instance, InstanceOptions, Querier, Size, Storage, WasmerVal,
};
use crate::serde::to_vec;
use std::cell::RefCell;
use wasmer::Module;
use wasmer_types::Type;
Expand Down
7 changes: 4 additions & 3 deletions packages/vm/src/dynamic_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ use crate::errors::{CommunicationError, VmError, VmResult};
use crate::imports::write_to_contract;
use crate::instance::Instance;
use crate::memory::read_region;
use crate::serde::from_slice;
use serde::{Deserialize, Serialize};
use wasmer::{Exports, Function, FunctionType, ImportObject, Module, RuntimeError, Val};
use wasmer_types::ImportIndex;

use cosmwasm_std::{from_slice, Addr, Binary};
use cosmwasm_std::{Addr, Binary};

// The length of the address is 63 characters for strings and 65 characters with "" for []byte. Thus, 65<64*2 is used.
const MAX_ADDRESS_LENGTH: usize = 64 * 2;
Expand Down Expand Up @@ -78,7 +79,7 @@ where
};
let address_region_ptr = ref_to_u32(&args[0])?;
let contract_addr_binary = read_region(&env.memory(), address_region_ptr, MAX_ADDRESS_LENGTH)?;
let contract_addr: Addr = from_slice(&contract_addr_binary)
let contract_addr: Addr = from_slice(&contract_addr_binary, MAX_ADDRESS_LENGTH)
.map_err(|_| RuntimeError::new("Invalid callee contract address"))?;
let mut args_data: Vec<Binary> = vec![];
for arg in &args[1..] {
Expand Down Expand Up @@ -257,7 +258,7 @@ where
Q: Querier + 'static,
{
let contract_addr_raw = read_region(&env.memory(), address, MAX_ADDRESS_LENGTH)?;
let contract_addr: Addr = from_slice(&contract_addr_raw)
let contract_addr: Addr = from_slice(&contract_addr_raw, MAX_ADDRESS_LENGTH)
.map_err(|_| RuntimeError::new("Invalid contract address to validate interface"))?;
let expected_interface_binary =
read_region(&env.memory(), interface, MAX_INTERFACE_REGIONS_LENGTH)?;
Expand Down
24 changes: 12 additions & 12 deletions packages/vm/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use cosmwasm_crypto::{
use cosmwasm_crypto::{
ECDSA_PUBKEY_MAX_LEN, ECDSA_SIGNATURE_LEN, EDDSA_PUBKEY_LEN, MESSAGE_HASH_MAX_LEN,
};
use cosmwasm_std::{from_slice, Attribute, Event};
use cosmwasm_std::{Attribute, Event};

#[cfg(feature = "iterator")]
use cosmwasm_std::Order;
Expand All @@ -24,7 +24,7 @@ use crate::memory::{read_region, write_region};
use crate::sections::decode_sections;
#[allow(unused_imports)]
use crate::sections::encode_sections;
use crate::serde::to_vec;
use crate::serde::{to_vec, from_slice};
use crate::GasInfo;

/// A kibi (kilo binary)
Expand Down Expand Up @@ -410,7 +410,7 @@ pub fn do_add_event<A: BackendApi, S: Storage, Q: Querier>(
event_ptr: u32,
) -> VmResult<u32> {
let event_data = read_region(&env.memory(), event_ptr, MAX_LENGTH_EVENT_VALUES)?;
let event: Event = match from_slice(&event_data) {
let event: Event = match from_slice(&event_data, MAX_LENGTH_EVENT_VALUES) {
Ok(event) => event,
Err(_) => return write_to_contract::<A, S, Q>(env, b"Input is not valid `Event`"),
};
Expand All @@ -424,7 +424,7 @@ pub fn do_add_events<A: BackendApi, S: Storage, Q: Querier>(
events_ptr: u32,
) -> VmResult<u32> {
let events_data = read_region(&env.memory(), events_ptr, MAX_LENGTH_EVENT_VALUES)?;
let events: Vec<Event> = match from_slice(&events_data) {
let events: Vec<Event> = match from_slice(&events_data, MAX_LENGTH_EVENT_VALUES) {
Ok(events) => events,
Err(_) => return write_to_contract::<A, S, Q>(env, b"Input is not valid `Vec<Event>`"),
};
Expand All @@ -440,13 +440,13 @@ pub fn do_add_attribute<A: BackendApi, S: Storage, Q: Querier>(
) -> VmResult<u32> {
let key_data = read_region(&env.memory(), key_ptr, MAX_LENGTH_EVENT_VALUES)?;
let value_data = read_region(&env.memory(), value_ptr, MAX_LENGTH_EVENT_VALUES)?;
let key: String = match from_slice(&key_data) {
let key: String = match from_slice(&key_data, MAX_LENGTH_EVENT_VALUES) {
Ok(key) => key,
Err(_) => {
return write_to_contract::<A, S, Q>(env, b"Input (key) is not valid utf8 string")
}
};
let value: String = match from_slice(&value_data) {
let value: String = match from_slice(&value_data, MAX_LENGTH_EVENT_VALUES) {
Ok(value) => value,
Err(_) => {
return write_to_contract::<A, S, Q>(env, b"Input (value) is not valid utf8 string")
Expand All @@ -462,7 +462,7 @@ pub fn do_add_attributes<A: BackendApi, S: Storage, Q: Querier>(
attributes_ptr: u32,
) -> VmResult<u32> {
let attributes_data = read_region(&env.memory(), attributes_ptr, MAX_LENGTH_EVENT_VALUES)?;
let attributes: Vec<Attribute> = match from_slice(&attributes_data) {
let attributes: Vec<Attribute> = match from_slice(&attributes_data, MAX_LENGTH_EVENT_VALUES) {
Ok(attributes) => attributes,
Err(_) => return write_to_contract::<A, S, Q>(env, b"Input is not valid Vec<Attribute>"),
};
Expand Down Expand Up @@ -1803,7 +1803,7 @@ mod tests {
let request: QueryRequest<Empty> = QueryRequest::Bank(BankQuery::AllBalances {
address: INIT_ADDR.to_string(),
});
let request_data = cosmwasm_std::to_vec(&request).unwrap();
let request_data = to_vec(&request).unwrap();
let request_ptr = write_data(&env, &request_data);

leave_default_data(&env);
Expand All @@ -1812,7 +1812,7 @@ mod tests {
let response = force_read(&env, response_ptr);

let query_result: cosmwasm_std::QuerierResult =
cosmwasm_std::from_slice(&response).unwrap();
from_slice(&response, usize::MAX).unwrap();
let query_result_inner = query_result.unwrap();
let query_result_inner_inner = query_result_inner.unwrap();
let parsed_again: AllBalanceResponse = from_binary(&query_result_inner_inner).unwrap();
Expand All @@ -1833,7 +1833,7 @@ mod tests {
let response = force_read(&env, response_ptr);

let query_result: cosmwasm_std::QuerierResult =
cosmwasm_std::from_slice(&response).unwrap();
from_slice(&response, usize::MAX).unwrap();
match query_result {
SystemResult::Ok(_) => panic!("This must not succeed"),
SystemResult::Err(SystemError::InvalidRequest { request: err, .. }) => {
Expand All @@ -1852,7 +1852,7 @@ mod tests {
contract_addr: String::from("non-existent"),
msg: Binary::from(b"{}" as &[u8]),
});
let request_data = cosmwasm_std::to_vec(&request).unwrap();
let request_data = to_vec(&request).unwrap();
let request_ptr = write_data(&env, &request_data);

leave_default_data(&env);
Expand All @@ -1861,7 +1861,7 @@ mod tests {
let response = force_read(&env, response_ptr);

let query_result: cosmwasm_std::QuerierResult =
cosmwasm_std::from_slice(&response).unwrap();
from_slice(&response, usize::MAX).unwrap();
match query_result {
SystemResult::Ok(_) => panic!("This must not succeed"),
SystemResult::Err(SystemError::NoSuchContract { addr }) => {
Expand Down
3 changes: 2 additions & 1 deletion packages/vm/src/testing/querier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ use serde::de::DeserializeOwned;

use cosmwasm_std::testing::{MockQuerier as StdMockQuerier, MockQuerierCustomHandlerResult};
use cosmwasm_std::{
to_binary, to_vec, Binary, Coin, ContractResult, CustomQuery, Empty, Querier as _,
to_binary, Binary, Coin, ContractResult, CustomQuery, Empty, Querier as _,
QueryRequest, SystemError, SystemResult,
};

use crate::serde::to_vec;
use crate::{BackendError, BackendResult, GasInfo, Querier};

const GAS_COST_QUERY_FLAT: u64 = 100_000;
Expand Down

0 comments on commit 34416b9

Please sign in to comment.