gpt4 book ai didi

rust - 为什么我不能在NEAR契约(Contract)中阅读此HashMap?

转载 作者:行者123 更新时间:2023-12-03 11:33:52 25 4
gpt4 key购买 nike

我有一个NEAR智能合约,该合约保留Veggie记录的HashMap。我最基本的访问器方法get_veggie(vid)查找并返回一条Veggie记录,通过了单元测试,但是在部署的契约(Contract)中失败。当我发送另一个访问器方法get_veggie_keys()返回的键之一时,它会因“蔬菜不存在”而感到 panic 。

// this method returns an array of u64 keys:
pub fn get_veggie_keys(&self) -> Vec<TokenId> {
self.veggies.keys().cloned().collect()
}

// but this method panics when I give it one of those keys:
pub fn get_veggie(&self, vid: TokenId) -> Veggie {
let veggie = match self.veggies.get(&vid) {
Some(c) => {
c
},
None => {
env::panic(b"Veggie does not exist.")
}
};
veggie.clone()
}
当我从NEAR CLI调用这些方法时,我看到了这种现象:
% near call --accountId $ACCOUNTID $CONTRACT_NAME get_veggie_keys      
Scheduling a call: dev-1602786511653-5521463.get_veggie_keys()
Transaction Id FdWjevTsMD73eFPno41THrvrChfB9HDoLAozuiXsBwru
To see the transaction in the transaction explorer, please open this url in your browser
https://explorer.testnet.near.org/transactions/FdWjevTsMD73eFPno41THrvrChfB9HDoLAozuiXsBwru
[ 3469591985938534000, [length]: 1 ]
%
% near call --accountId $ACCOUNTID $CONTRACT_NAME get_veggie '{"vid":3469591985938534000}'
Scheduling a call: dev-1602786511653-5521463.get_veggie({"vid":3469591985938534000})
Receipt: 68ahRQyNN7tzAQMbguCEy83ofL6S5mv3iLVmmN2NH8gh
Failure [dev-1602786511653-5521463]: Error: Smart contract panicked: Veggie does not exist.
An error occured [...]
契约(Contract)中的这种行为与单元测试中的行为有何不同?我称方法错误吗?我不了解HashMaps吗?感谢您的任何建议。也许我犯了一个Rust noob错误,但是我对此深感困惑...

最佳答案

您正在靠近那里。您将要使用特殊的JSON类型U64U128。此外,您也不想使用HashMap,因为它无法缩放。
我在这里创建了一个示例存储库供您查看:
https://github.com/mikedotexe/near-stackoverflow-64378144/blob/master/src/lib.rs
如果参数要使用需要超过53位的数字,则需要这样做:

use near_sdk::json_types::U128;

pub fn add_veggie_taste(&mut self, upc: U128, taste: String) {

}
如前所述,您将要使用NEAR集合而不是HashMap。请查看此链接以了解各种选项:
https://docs.rs/near-sdk/2.0.0/near_sdk/collections/index.html
另外,我相信您可能没有像下面那样在结构上方添加宏。这对于使用单元测试而不是在链上工作是有意义的。
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Produce {
pub veggies_taste: TreeMap<UPC, String>,
pub veggies_taste2: TreeMap<UPC, String>
}

#[near_bindgen]
impl Produce {

pub fn add_veggie_taste(&mut self, upc: U128, taste: String) {
let existing_veggie: Option<String> = self.veggies_taste.get(&upc.into());
if existing_veggie.is_some() {
env::panic(b"Sorry, already added this UPC!")
}
// Note that "into" turns the U128 (as a string, basically) into u128
self.veggies_taste.insert(&upc.into(), &taste);
}

}
我受到这篇文章的启发,并决定在此处制作视频:
https://youtu.be/d68_hw_zjT4

关于rust - 为什么我不能在NEAR契约(Contract)中阅读此HashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64378144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com