watch

Optimization Tips for NEAR SDK Contract Storage

If anyone has a similar requirement, here are some strategies I employed: declaring no fields in the main contract's STATE struct when they solely hold data structures like Vector or IterableMap, since these mainly store a storage key prefix that is typically hardcoded, and sometimes maintain length information. Additionally, opting for the native Vec over Vector can significantly reduce overheads, as Vector incurs extra bytes per entry. For hash-based structures in near_sdk, using a custom hash function might lower costs by avoiding the default identity hash, which stores the key itself—a disadvantage if keys are larger than about 8 bytes. For functions that are non-private and susceptible to collision attacks, a 32-byte hash is advisable. To combine these approaches, I created a utility available at https://github.com/INTEARnear/wallet-contract/blob/bf01434c8d72d80243539de0e258891f1a88fabb/src/utils.rs which allows using a StorageCell like `let mut x = StorageCell::::new(b"x"); log!("{x}"); *x += 1;` as a non-field stored entity. This is beneficial because near-sdk structs such as Lazy tend to be instantiated lazily from Borsh deserialization, which might add some cognitive complexity if used extensively. Note that this utility has not been audited, so caution is advised before copying.
Source available for registered users Sign Up Free

AI Analysis

The advice focuses on optimizing storage and computational efficiency within NEAR smart contracts. By avoiding storing data structures like Vector or IterableMap directly in the main contract state wh...

AI Recommendation

Contract developers targeting NEAR should consider these storage optimization strategies to enhance performance and reduce costs. Starting with avoiding unnecessary storage fields for data structures ...

Disclaimer

The AI analysis and recommendations provided are for informational purposes only. Any investment decisions should be made at your own risk. Past performance is not indicative of future results. Always conduct your own research and consider consulting with a financial advisor before making any investment decisions.

You might also be interested in: