Mappings

Los mapas son una estructura de datos de key-value que se utiliza para almacenar datos dentro de un contrato inteligente. En Cairo se implementan utilizando el tipo LegacyMap. Es importante tener en cuenta que el tipo LegacyMap solo se puede usar dentro de la estructura Storage de un contrato y no se puede usar en ningún otro lugar.

Here we demonstrate how to use the LegacyMap type within a Cairo contract, to map between a key of type ContractAddress and value of type felt252. The key-value types are specified within angular brackets <>. We write to the map by calling the write() method, passing in both the key and value. Similarly, we can read the value associated with a given key by calling the read() method and passing in the relevant key.

Algunas notas adicionales:

  • More complex key-value mappings are possible, for example we could use LegacyMap::<(ContractAddress, ContractAddress), felt252> to create an allowance on an ERC20 token contract.

  • In mappings, the address of the value at key k_1,...,k_n is h(...h(h(sn_keccak(variable_name),k_1),k_2),...,k_n) where is the Pedersen hash and the final value is taken mod2251−256. You can learn more about the contract storage layout in the Starknet Documentation

use starknet::ContractAddress; #[starknet::interface] trait IMapContract<TContractState> { fn set(ref self: TContractState, key: ContractAddress, value: felt252); fn get(self: @TContractState, key: ContractAddress) -> felt252; } #[starknet::contract] mod MapContract { use starknet::ContractAddress; #[storage] struct Storage { // The `LegacyMap` type is only available inside the `Storage` struct. map: LegacyMap::<ContractAddress, felt252>, } #[abi(embed_v0)] impl MapContractImpl of super::IMapContract<ContractState> { fn set(ref self: ContractState, key: ContractAddress, value: felt252) { self.map.write(key, value); } fn get(self: @ContractState, key: ContractAddress) -> felt252 { self.map.read(key) } } }

Visita el contrato en Voyager](https://goerli.voyager.online/contract/0x06214AB4c23Cc545bf2221D465eB83aFb7412779AD498BD48a724B3F645E3505) o juega con él en Remix.

Last change: 2023-10-12, commit: 90aa7c0