컬렉션 중첩(Nesting)
고유 접두사에 대한 기존 접근법
원래는 바이트 벡터로 변환된 짧은 한 글자 접두사를 사용하여, 생성자(constructor)에서 접두사를 하드코딩하였습니다. 중첩 컬렉션을 사용하는 경우 접두사를 수동으로 구성해야 합니다.
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::{UnorderedMap, UnorderedSet};
use near_sdk::{near_bindgen, AccountId};
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Contract {
pub accounts: UnorderedMap<AccountId, UnorderedSet<String>>,
}
impl Default for Contract {
fn default() -> Self {
Self {
accounts: UnorderedMap::new(b"t"),
}
}
}
#[near_bindgen]
impl Contract {
pub fn get_tokens(&self, account_id: &AccountId) -> Vec<String> {
let tokens = self.accounts.get(account_id).unwrap_or_else(|| {
// Constructing a unique prefix for a nested UnorderedSet from a concatenation
// of a prefix and a hash of the account id.
let prefix: Vec<u8> = [
b"s".as_slice(),
&near_sdk::env::sha256_array(account_id.as_bytes()),
]
.concat();
UnorderedSet::new(prefix)
});
tokens.to_vec()
}
}