Solidity

如何在更新結構時轉移 ETH

  • November 1, 2022

當我在 Solidity 開發方面邁出第一步時,我正在解決銷售問題。除其他外,目標是在結構中發布項目,然後有人能夠購買它。我正在努力尋找一種呼叫函式的方法(僅通過使用項目 ID),然後將列出的 ETH 轉移給賣家。

這是程式碼:

pragma solidity >=0.7.0 <0.9.0;
contract sales{

   struct Items{
       uint256 productID;
       string productname;
       address productOwner;
   }


   struct ItemsForSale{
       //uint256 forSaleID; more efficient for have one ID
       uint256 productID; 
       uint256 productPrice;

   }

   struct Offers{
       uint256 offerID;
       uint256 productID;
       uint256 offerPrice;

   } 

   uint numItems;
   uint numsaleItems;
   mapping(uint => Items) public item;
   mapping(uint => ItemsForSale) public sales;

   constructor(){
       
   }

   function createItem(string memory _productName) public returns (string memory, uint productID){
       productID = numItems++;
       Items storage _item = item[productID]; 
       _item.productID = productID;
       _item.productname = _productName;
       _item.productOwner = msg.sender;
       return ( "Your Item is listed with the Id:" , productID);
       }

   function listItemForSale(uint256 _productID, uint256 _productPrice) public{
       sales[_productID] = ItemsForSale(_productID,_productPrice);
   }

   function buyItem(uint _forSaleID) public payable{
       Items storage _itembought = item[_forSaleID];
       _itembought.productOwner = msg.sender; 
       //PLUS HERE I WANT TO BE ABLE TO SEND THE ETH AMOUNT FOUND IN THE ItemsForSale 
       //STRUCT FROM THE CALLER OF THIS FUNCTION TO THE OWNER OF THE ITEM (found in the 
       //Items struct)

   }
}

謝謝大家 :)

問候,

利用:

   function buyItem(uint _forSaleID) public payable{
       Items storage _itembought = item[_forSaleID];
       ItemsForSale memory _itemSale = sales[_forSaleID];
       require(_itemSale.productPrice == msg.value, "Product costs more");
       payable(_itembought.productOwner).transfer(_itemSale.productPrice);

       _itembought.productOwner = msg.sender;
   }

引用自:https://ethereum.stackexchange.com/questions/138529