ExecutionError:Smart contract panicked:panicked at Cannot deserialize the contract state.:Custom kind:InvalidInput,error:"Unexpected length of input"

ExecutionError:Smart contract panicked:panicked at Cannot deserialize the contract state.:Custom kind:InvalidInput,error:"Unexpected length of input"

#[derive(BorshSerialize, BorshDeserialize)]
pub struct NotesDs {
    pub own: Vec<String>,
    pub shared: UnorderedMap<AccountId,Vec<String>>,
}

impl NotesDs{
    pub fn new() -> Self {
        assert!(env::state_read::<Self>().is_none(), "Already initialized");
        Self {
            own: Vec:: new(),
            shared: UnorderedMap::new(b"w".to_vec()),
        }
    }
}
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Note {
    pub note_list : UnorderedMap<AccountId,NotesDs>, 
}

impl Default for Note {
    fn default() -> Self {
        // Check incase the contract is not initialized
        env::panic(b"The contract is not initialized.")
    }
}

#[near_bindgen]
impl Note {
    /// Init attribute used for instantiation.
    #[init]
    pub fn new() -> Self {
        assert!(env::state_read::<Self>().is_none(), "Already initialized");
        Self {
            note_list: UnorderedMap::new(b"h".to_vec()),
        }
    }
    pub fn add_notes2(&mut self, status: String){
        if self.note_list.get(&env::predecessor_account_id()).is_none() {
            let mut temp = NotesDs:: new();
            let mut vec = Vec:: new();
            let mut vec2 = Vec:: new();
            vec.push(status.clone());
            temp.own = vec;
            temp.shared = vec2;
            self.note_list.insert(&env::predecessor_account_id(), &temp);
        }
        else {
            let mut temp1 = self.note_list.get(&env::predecessor_account_id()).unwrap();
            let mut vec1 = temp1.own;
            vec1.push(status.clone());
            temp1.own = vec1;
            self.note_list.insert(&env::predecessor_account_id(), &temp1);
        }      
    }
} 

我收到以下错误

 Failure [share.meghaha.testnet]: Error: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Cannot deserialize the contract state.: Custom { kind: InvalidInput, error: \"Unexpected length of input\" }', /home/meghaa105/.cargo/registry/src/github.com-1ecc6299db9ec823/near-sdk-3.1.0/src/environment/env.rs:786:46"}}
ServerTransactionError: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: panicked at 'Cannot deserialize the contract state.: Custom { kind: InvalidInput, error: \"Unexpected length of input\" }', /home/meghaa105/.cargo/registry/src/github.com-1ecc6299db9ec823/near-sdk-3.1.0/src/environment/env.rs:786:46"}}
    at Object.parseResultError (/usr/lib/node_modules/near-cli/node_modules/near-api-js/lib/utils/rpc_errors.js:31:29) 
    at Account.signAndSendTransactionV2 (/usr/lib/node_modules/near-cli/node_modules/near-api-js/lib/account.js:160:36)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async scheduleFunctionCall (/usr/lib/node_modules/near-cli/commands/call.js:57:38)
    at async Object.handler (/usr/lib/node_modules/near-cli/utils/exit-on-error.js:52:9) {
  type: 'FunctionCallError',
  context: undefined,
  index: 0,
  kind: {
    ExecutionError: `Smart contract panicked: panicked at 'Cannot deserialize the contract state.: Custom { kind: InvalidInput, error: "Unexpected length of input" }', /home/meghaa105/.cargo/registry/src/github.com-1ecc6299db9ec823/near-sdk-3.1.0/src/environment/env.rs:786:46`
  },
  transaction_outcome: {
    block_hash: 'EesG3NjqXdbYZqEYE22nC12AYpU3gkC9uaC7rSjToGSA',
    id: '89g7HhiXgZFZRLntMzFCPk82TQ5m8diwW2nh6jVnEgKz',
    outcome: {
      executor_id: 'share.meghaha.testnet',
      gas_burnt: 2428050684172,
      logs: [],
      metadata: [Object],
      receipt_ids: [Array],
      status: [Object],
      tokens_burnt: '242805068417200000000'
    },
    proof: [ [Object], [Object] ]
  }
}

此错误来自查询
near calladd_notes2 '{"status" : "尝试编写智能合约" }'

我什至尝试过删除和创建一个具有相同或不同名称的新帐户。我什至尝试重新部署智能合约。此外,我还添加了序列化和反序列化依赖项。我不知道出了什么问题。

编辑:原始答案(标记为正确)说标准 Rust Vec 不能用于 NEAR 合约。它可以与 https://docs.rs/borsh/0.2.9/borsh/ser/trait.BorshSerialize.html. The NEAR collections https://docs.rs/near-sdk/2.0.1/near_sdk/collections/index.html 中的所有 Rust 类型一起推荐用于更大的集合,因为它们存储效率更高,但功能很少,并且不如 Rust 内置插件那么熟悉。

一定是其他原因解决了这个问题。当新合约代码部署到现有合约上并且与合约先前存储的数据不兼容时,通常会在 NEAR 中出现“无法反序列化合约状态”。

原答案

以下代码可能有助于解决错误。 NEAR 有它自己的数据类型来保存合约的状态。

near_sdk::collections::Vector 用于代替 Vec.

下面的代码将 Vec 替换为持久性 NEAR 向量:

/// New imports...
use near_sdk::collections::{ UnorderedMap, Vector };
use near_sdk::{ BorshStorageKey };

#[derive(BorshSerialize, BorshStorageKey)]
enum StorageKeyNotes {
    MapKey,
    OwnKey,
    SharedKey
}

#[derive(BorshSerialize, BorshDeserialize)]
pub struct NotesDs {
    pub own: Vector<String>,
    pub shared: UnorderedMap<AccountId, Vector<String>>,
}

impl NotesDs{
    pub fn new() -> Self {
        assert!(env::state_read::<Self>().is_none(), "Already initialized");
        let mut notesDs = Self {
            own: Vector::new(StorageKeyNotes::OwnKey),
            shared: UnorderedMap::<AccountId, Vector<String>>::new(StorageKeyNotes::MapKey)
        };

        notesDs
    }
}
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Note {
    pub note_list : UnorderedMap<AccountId,NotesDs>, 
}

impl Default for Note {
    fn default() -> Self {
        // Check incase the contract is not initialized
        env::panic(b"The contract is not initialized.")
    }
}

#[near_bindgen]
impl Note {
    /// Init attribute used for instantiation.
    #[init]
    pub fn new() -> Self {
        assert!(env::state_read::<Self>().is_none(), "Already initialized");
        Self {
            note_list: UnorderedMap::new(b"h".to_vec()),
        }
    }
    pub fn add_notes2(&mut self, status: String){
        if self.note_list.get(&env::predecessor_account_id()).is_none() {
            let mut temp = NotesDs:: new();
            let mut vec = Vector::new(StorageKeyNotes::OwnKey);
            let mut vec2 = Vector::new(StorageKeyNotes::SharedKey);
            vec.push(&status.clone());
            temp.own = vec;
            temp.shared.insert(&String::from("Max Power"), &vec2);
            self.note_list.insert(&env::predecessor_account_id(), &temp);
        }
        else {
            let mut temp1 = self.note_list.get(&env::predecessor_account_id()).unwrap();
            let mut vec1 = temp1.own;
            vec1.push(&status.clone());
            temp1.own = vec1;
            self.note_list.insert(&env::predecessor_account_id(), &temp1);
        }      
    }
} 

该代码尚未在链上进行测试,但可以帮助解决错误。

任何搜索类似错误的人:

Smart contract panicked: panicked at 'Cannot deserialize the contract
 state.: Custom { kind: InvalidData, error: "Not all bytes read" }

这通常意味着已经部署了一个新合约,但它不能使用之前合约存储的数据。

Not All Bytes Read Common Solutions