Smart contract, selling and buying multiple items

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 ?

Talk friend, how are you?

Greetings!

In case you want to create contracts for purchases and sales with several selectable items?

If that's the case I imagine you would need to make some contracts with interactions and contract address for each item you want to sell and in this case the best option for you is to develop a Dapp with React

1 Like

Yeah, you are right, if one user buys many items at one time, you have got to consider the gas limit. I do not have a better solution, maybe you can set a limitation on the number of purchases a user can buy at one time.

Cause all transaction are atomic, so either all succeed or all fail.

If Alice wants to buy item1. item 2, item3, and Bob wants to buy item3, item4, so this depends on whose transaction will be confirmed firstly, the latter one confirmed will fail.