Description
History of the problem
I was trying to create a small catalog in a map using a hash of an item as a key and value as a price. There was a struct item
:
struct Item {
prop1: String;
prop2: String;
prop3: String;
prop4: String;
}
To calculate a hash of this item
I used this code: sha256(msg.item.toCell().asSlice())
which seems to be fine, but suddenly I realized that smart contract does very strange things. After precise debugging, I found out the problem was that the code above returns absolutely the same hash despite all items being different. It is because sha256 is a math function that calculates a hash only of the first ref cell in my case. The ref cells of the struct were always the same, so the sha256()
results were the same too. To calculate the hash of this struct you need to write this code: item.toCell().hash()
Proposal
From my point of view, it is an important note to prevent many hard-catching bugs and make smart contracts a little bit safer, so my suggestions are:
- Also write hash function for structs to simply write:
someStruct.hash()
- Write down that if you want to calculate a hash of the object you need
hash()
and NOTsha256()
. Emphases the difference between these two functions - Write down small examples to make the difference clear