> ## Documentation Index
> Fetch the complete documentation index at: https://docs.near.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Collections

> Efficiently store, access, and manage data in smart contracts.

export const Github = ({url, start, end, fname, language, withSourceLink = true}) => {
  const [code, setCode] = useState(null);
  function toRaw(ref) {
    const fullUrl = ref.slice(ref.indexOf('https'));
    const [url] = fullUrl.split('#');
    const [org, repo, , branch, ...pathSeg] = new URL(url).pathname.split('/').slice(1);
    return `https://raw.githubusercontent.com/${org}/${repo}/${branch}/${pathSeg.join('/')}`;
  }
  async function fetchCode(url, fromLine, toLine) {
    let res;
    if (typeof window !== 'undefined') {
      const validUntil = localStorage.getItem(`${url}-until`);
      if (validUntil && Number(validUntil) > Date.now()) {
        res = localStorage.getItem(url);
      }
    }
    if (!res) {
      try {
        res = await (await fetch(url)).text();
        if (typeof window !== 'undefined') {
          localStorage.setItem(url, res);
          localStorage.setItem(`${url}-until`, String(Date.now() + 60000));
        }
      } catch {
        return 'Error fetching code, please try reloading';
      }
    }
    let body = res.split('\n');
    const from = fromLine ? Number(fromLine) - 1 : 0;
    const to = toLine ? Number(toLine) : body.length;
    body = body.slice(from, to);
    const precedingSpace = body.reduce((prev, line) => {
      if (line.length === 0) return prev;
      const spaces = line.match(/^\s+/);
      if (spaces) return Math.min(prev, spaces[0].length);
      return 0;
    }, Infinity);
    return body.map(line => line.slice(precedingSpace === Infinity ? 0 : precedingSpace)).join('\n');
  }
  function buildSourceUrl(url, start, end) {
    const base = url.split('#')[0];
    if (start && end) return `${base}#L${start}-L${end}`;
    if (start) return `${base}#L${start}`;
    return base;
  }
  useEffect(() => {
    const rawUrl = toRaw(url);
    fetchCode(rawUrl, start, end).then(res => setCode(res));
  }, [url, start, end]);
  const sourceUrl = buildSourceUrl(url, start, end);
  const fileName = fname ?? sourceUrl.split('/').pop();
  return <div className="my-5">
      {code === null ? <div>Loading...</div> : <CodeBlock language={language} filename={fileName} lines>
          {code}
        </CodeBlock>}
      {withSourceLink && <div className="flex justify-end" style={{
    marginTop: "-1rem"
  }}>
          <a href={sourceUrl} target="_blank" rel="noreferrer noopener" className="text-[0.6875rem] font-medium text-[#656d76] no-underline hover:text-[#1f2328] dark:text-[#8b949e] dark:hover:text-[#e6edf3]">
            See code on GitHub
          </a>
        </div>}
    </div>;
};

When deciding on data structures it is important to understand their tradeoffs. Choosing the wrong structure can create a bottleneck as the application scales, and migrating the state to the new data structures will come at a cost.

You can choose between two types of collections:

1. Native collections (e.g. `Array`, `Map`, `Set`), provided by the language
2. SDK collections (e.g. `IterableMap`, `Vector`), provided by the NEAR SDK

<Tip>
  **Native vs SDK Collections**

  Use native collections for small amounts of data that need to be accessed altogether, and SDK collections for large amounts of data that do not need to be accessed altogether.

  If your collection has up to 100 entries, it's acceptable to use the native collection. For larger ones, prefer to use SDK collection. For comparison please refer to [this benchmark](https://www.github.com/volodymyr-matselyukh/near-benchmarking).
</Tip>

***

## Storage Management

Each time the contract is executed, the first thing it will do is to read the values and [deserialize](./serialization) them into memory, and after the function finishes, it will [serialize](./serialization) and write the values back to the database.

For native collections, the contract will fully load the collection into memory before any method executes. This happens even if the method you invoke does not use the collection. Know that this will have impact on GAS you spend for methods in your contract.

<Accordion title="Storage Cost">
  Your contract needs to lock a portion of their balance proportional to the amount of data they stored in the blockchain. This means that:

  * If more data is added the **storage increases ↑**, and your contract's **balance decreases ↓**.
  * If data is deleted the **storage decreases ↓**, and your contract's **balance increases ↑**.

  Currently, it costs approximately **1 Ⓝ** to store **100kb** of data.
</Accordion>

<Accordion title="Storage Constraints on NEAR">
  For storing data on-chain it’s important to keep in mind the following:

  * There is a 4mb limit on how much you can upload at once

  Let’s say for example, someone wants to put an NFT purely on-chain (rather than IPFS or some other decentralized storage solution) you’ll have almost an unlimited amount of storage but will have to pay 1 `$NEAR` per 100kb of storage used.

  Users will be limited to 4MB per contract call upload due to MAX\_GAS constraints. The maximum amount of gas one can attach to a given functionCall is 300TGas.
</Accordion>

<Warning>
  Your contract will panic if you try to store data but don't have NEAR to cover its storage cost
</Warning>

<Danger>
  Be mindful of potential [small deposit attacks](../security/storage)
</Danger>

***

## Native Collections

Native collections are those provided by the language, such as `Vec`, `HashMap`, `HashSet` in Rust.

All entries in a native collection are **serialized into a single value** and **stored together** into the state. This means that every time a function execute, the SDK will read and **deserialize all entries** in the native collection.

<Accordion title="Serialization & Storage Example">
  The array `[1,2,3,4]` will be serialized into the Borsh byte-stream `[0,0,0,4,1,2,3,4]` before being stored
</Accordion>

<Tip>
  **When to use them**

  Native collections are useful if you are planning to store smalls amounts of data that need to be accessed all together
</Tip>

<Danger>
  **Keep Native Collections Small**

  As the native collection grows, deserializing it from memory will cost more and more gas. If the collections grows too large, your contract might expend all the gas trying to read its state, making it fail on each function call
</Danger>

***

## SDK Collections

The NEAR SDKs expose collections that are optimized for random access of large amounts of data. SDK collections are instantiated using a "prefix", which is used as an index to split the data into chunks. This way, SDK collections can defer reading and writing to the store until needed.

<Accordion title="Serialization & Storage Example">
  The sdk array `[1,2,3,4]` with prefix `"p"` will be stored as the string `"p"` in the contract's attribute, and create four entries in the contract's storage: `p-0:1`, `p-1:2`...
</Accordion>

<Accordion title="SDK Collections' Features">
  | Type           |         SDK Module         | Iterable | Clear All Values | Preserves Insertion Order | Range Selection |
  | -------------- | :------------------------: | :------: | :--------------: | :-----------------------: | :-------------: |
  | `Vector`       |      `near_sdk::store`     |     ✅    |         ✅        |             ✅             |        ✅        |
  | `LookupSet`    |      `near_sdk::store`     |          |                  |                           |                 |
  | `UnorderedSet` | `near_sdk::collections` ⚠️ |     ✅    |         ✅        |                           |        ✅        |
  | `IterableSet`  |      `near_sdk::store`     |     ✅    |         ✅        |                           |        ✅        |
  | `LookupMap`    |      `near_sdk::store`     |          |                  |                           |                 |
  | `UnorderedMap` | `near_sdk::collections` ⚠️ |     ✅    |         ✅        |                           |        ✅        |
  | `IterableMap`  |      `near_sdk::store`     |     ✅    |         ✅        |                           |        ✅        |
  | `TreeMap`      | `near_sdk::collections` ⚠️ |     ✅    |         ✅        |             ✅             |        ✅        |

  *⚠️ Legacy collections from `near_sdk::collections`. Prefer `near_sdk::store` equivalents for new contracts.*
</Accordion>

<Accordion title="SDK Collections' Time Complexities">
  | Type           | Access |  Insert  |  Delete  |  Search  | Traverse | Clear |
  | -------------- | :----: | :------: | :------: | :------: | :------: | :---: |
  | `Vector`       |  O(1)  |  O(1)\*  | O(1)\*\* |   O(n)   |   O(n)   |  O(n) |
  | `LookupSet`    |  O(1)  |   O(1)   |   O(1)   |   O(1)   |    N/A   |  N/A  |
  | `UnorderedSet` |  O(1)  |   O(1)   |   O(1)   |   O(1)   |   O(n)   |  O(n) |
  | `IterableSet`  |  O(1)  |   O(1)   |   O(1)   |   O(1)   |   O(n)   |  O(n) |
  | `LookupMap`    |  O(1)  |   O(1)   |   O(1)   |   O(1)   |    N/A   |  N/A  |
  | `IterableMap`  |  O(1)  |   O(1)   |   O(1)   |   O(1)   |   O(n)   |  O(n) |
  | `TreeMap`      |  O(1)  | O(log n) | O(log n) | O(log n) |   O(n)   |  O(n) |

  *\* - to insert at the end of the vector using `push_back` (or `push_front` for deque)*
  *\*\* - to delete from the end of the vector using `pop` (or `pop_front` for deque), or delete using `swap_remove` which swaps the element with the last element of the vector and then removes it.*
</Accordion>

These collections are built to have an interface similar to native collections.

<Tip>
  **when to use them**

  SDK collections are useful when you are planning to store large amounts of data that do not need to be accessed all together
</Tip>

### Instantiation

All structures need to be initialized using a **unique `prefix`**, which will be used to index the collection's values in the account's state

<Github fname="lib.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/lib.rs" start="24" end="47" />

<Tip>
  Notice how we use `enums` to ensure all collections have a different prefix. Another advantage of using `enums` is that they are serialized into a single `byte` prefix.
</Tip>

<Warning>
  If you see a `unresolved import near_sdk::BorshIntoStorageKey` compiler error, your code is following an outdated pattern from `near-sdk < 4.0`.

  To fix it, derive [`BorshStorageKey`](https://docs.rs/near-sdk/latest/near_sdk/derive.BorshStorageKey.html) on your prefix enum.
</Warning>

<Danger>
  Be careful of not using the same prefix in two collections, otherwise, their storage space will collide, and you might overwrite information from one collection when writing in the other
</Danger>

<hr className="subsection" />

### Vector

Implements a [vector/array](https://en.wikipedia.org/wiki/Array_data_structure) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.

<Github fname="vector.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/vector.rs" start="4" end="29" />

<hr className="subsection" />

### LookupMap

Implements a [map/dictionary](https://en.wikipedia.org/wiki/Associative_array) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.

<Github fname="lookup_map.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/lookup_map.rs" start="4" end="22" />

<hr className="subsection" />

### UnorderedMap / IterableMap

Implements a [map/dictionary](https://en.wikipedia.org/wiki/Associative_array) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.

<Tip>
  **UnorderedMap vs IterableMap (Rust)**

  `UnorderedMap` belongs to the legacy `near_sdk::collections` module. `IterableMap` is its modern replacement in `near_sdk::store`, and should be preferred for new contracts. The `store` collections cache reads and writes within a single transaction, making them more gas-efficient when the same key is accessed multiple times.
</Tip>

<Github fname="iterable_map.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/iterable_map.rs" start="4" end="29" />

<hr className="subsection" />

### LookupSet

Implements a [set](https://en.wikipedia.org/wiki/Set_\(abstract_data_type\)) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.

<Github fname="lookup_set.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/lookup_set.rs" start="4" end="18" />

<hr className="subsection" />

### UnorderedSet / IterableSet

Implements a [set](https://en.wikipedia.org/wiki/Set_\(abstract_data_type\)) that persists in the contract's storage. See the [Rust SDK collections reference](https://docs.rs/near-sdk/latest/near_sdk/store/index.html) for its complete interface.

<Tip>
  **UnorderedSet vs IterableSet**

  `UnorderedSet` belongs to the legacy `near_sdk::collections` module. `IterableSet` is its modern replacement in `near_sdk::store`, and should be preferred for new contracts. The `store` collections cache reads and writes within a single transaction, making them more gas-efficient when the same key is accessed multiple times.
</Tip>

<Github fname="iterable_set.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/iterable_set.rs" start="4" end="26" />

<hr className="subsection" />

### Tree

An ordered equivalent of Map. The underlying implementation is based on an [AVL](https://en.wikipedia.org/wiki/AVL_tree). You should use this structure when you need to: have a consistent order, or access the min/max keys.

<Github fname="tree.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/legacy/src/tree.rs" start="6" end="24" />

***

## Nesting Collections

When nesting SDK collections, be careful to **use different prefixes** for all collections, including the nested ones.

<Github fname="nested.rs" language="rust" url="https://github.com/near-examples/storage-examples/blob/main/collections-rs/store/src/nested.rs" start="4" end="30" />

<Tip>
  Notice how we use `enums` that take a `String` argument to ensure all collections have a different prefix
</Tip>

***

## Error prone patterns

Because the values are not kept in memory and are lazily loaded from storage, it's important to make sure if a collection is replaced or removed, that the storage is cleared. In addition, it is important that if the collection is modified, the collection itself is updated in state because most collections will store some metadata.

Some error-prone patterns to avoid that cannot be restricted at the type level are:

```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use near_sdk::store::UnorderedMap;

let mut m = UnorderedMap::<u8, String>::new(b"m");
m.insert(1, "test".to_string());
assert_eq!(m.len(), 1);
assert_eq!(m.get(&1), Some(&"test".to_string()));

// Bug 1: Should not replace any collections without clearing state, this will reset any
// metadata, such as the number of elements, leading to bugs. If you replace the collection
// with something with a different prefix, it will be functional, but you will lose any
// previous data and the old values will not be removed from storage.
m = UnorderedMap::new(b"m");
assert!(m.is_empty());
assert_eq!(m.get(&1), Some(&"test".to_string()));

// Bug 2: Should not use the same prefix as another collection
// or there will be unexpected side effects.
let m2 = UnorderedMap::<u8, String>::new(b"m");
assert!(m2.is_empty());
assert_eq!(m2.get(&1), Some(&"test".to_string()));

// Bug 3: forgetting to save the collection in storage. When the collection is attached to
// the contract state (`self` in `#[near]`) this will be done automatically, but if
// interacting with storage manually or working with nested collections, this is relevant.
use near_sdk::store::Vector;

// Simulate roughly what happens during a function call that initializes state.
{
    let v = Vector::<u8>::new(b"v");
    near_sdk::env::state_write(&v);
}

// Simulate what happens during a function call that just modifies the collection
// but does not store the collection itself.
{
    let mut v: Vector<u8> = near_sdk::env::state_read().unwrap();
    v.push(1);
    // The bug is here that the collection itself if not written back
}

let v: Vector<u8> = near_sdk::env::state_read().unwrap();
// This will report as if the collection is empty, even though the element exists
assert!(v.get(0).is_none());
assert!(
    near_sdk::env::storage_read(&[b"v".as_slice(), &0u32.to_le_bytes()].concat()).is_some()
);

// Bug 4 (only relevant for `near_sdk::store`): These collections will cache writes as well
// as reads, and the writes are performed on [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html)
// so if the collection is kept in static memory or something like `std::mem::forget` is used,
// the changes will not be persisted.
use near_sdk::store::IterableSet;

let mut m: IterableSet<u8> = IterableSet::new(b"l");
m.insert(1);
assert!(m.contains(&1));

// This would be the fix, manually flushing the intermediate changes to storage.
// m.flush();
std::mem::forget(m);

m = IterableSet::new(b"l");
assert!(!m.contains(&1));
```

***

## Pagination

Persistent collections such as `IterableMap/UnorderedMap`, `IterableSet/UnorderedSet` and `Vector` may
contain more elements than the amount of gas available to read them all.
In order to expose them all through view calls, we can use pagination.

With Rust this can be done using iterators with [`Skip`](https://doc.rust-lang.org/std/iter/struct.Skip.html) and [`Take`](https://doc.rust-lang.org/std/iter/struct.Take.html). This will only load elements from storage within the range.

```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
  #[near(contract_state)]
  #[derive(PanicOnDefault)]
  pub struct Contract {
      pub status_updates: IterableMap<AccountId, String>,
  }

  #[near]
  impl Contract {
      /// Retrieves multiple elements from the `IterableMap`.
      /// - `from_index` is the index to start from.
      /// - `limit` is the maximum number of elements to return.
      pub fn get_updates(&self, from_index: usize, limit: usize) -> Vec<(AccountId, String)> {
          self.status_updates
              .iter()
              .skip(from_index)
              .take(limit)
              .collect()
      }
  }
```
