I am making a smart contract with the option to buy (and sell) an item. So I made a function that allows to buy 1 item. However, I want the possibility to also buy several items together. So lets say I have a website with 10.000 items and I want the user to scroll through all those items and select several that the user wants to buy. So the user can just select 1, but he might also select 300 items if that is what he wants. Therefore I made another function that calls the first function in a loop. So my smart contract has the following form:
contract A
{
function buyItem () public payable
{
// code to buy item
}
function buyItems () public payable
{
for()
{
buyItem();
}
}
}
Is this the recommended way to do this ? I can imagine that if someone wants to buy a lot of items, maybe he is going to get troubles with the gas limit.
And what happens if the user wants to buy 300 items, but item 250 can't be bought because the owner explicitly said it wasn't for sale ?
And if you want to add a require statement before calling the buyItems
function to check whether the user sent enough funds to buy the 300 items .. how can you best deal with this ? In theory you need to do loop over the 300 items and do a summation over all 300 items just to be able to make this sum. This increases the gas usage even more.
The thing is that in my application just buying 1 item is something very rare. On average many items will be bought at once. But I am not very sure what is the best way to do this when using smart contracts. Then there is also the aspect of what happens when there is some other user that might also buy at the same time some other items of which some overlap with the items that I want to buy .. how to deal with that ?
Anyone can give any guidance how to deal with these problems ?