Learn Ethereum by Xun (Brian) Wu

Learn Ethereum by Xun (Brian) Wu

Author:Xun (Brian) Wu [Xun (Brian) Wu]
Language: eng
Format: epub
Tags: COM083000 - COMPUTERS / Security / Cryptography, COM060090 - COMPUTERS / Internet / Application Development, COM048000 - COMPUTERS / Systems Architecture / Distributed Systems and Computing
Publisher: Packt
Published: 2019-09-20T15:05:14+00:00


We were able to create the art token and list the art in the art market. Next, we will implement the buyer functions.

Implementing the buyArt() function

The users can find art through the art gallery. If they like digital art, they can place an order to buy the art without going through the middleman. Let's implement the function, as shown in the following code:

mapping(uint256 => ArtTxn[]) private artTxns; function buyArt(uint256 _tokenId) payable public { (uint256 _id, string memory _title, ,uint256 _price, uint _status,,string memory _authorName, address _author,address payable _current_owner, ) = findArt(_tokenId); require(_current_owner != address(0)); require(msg.sender != address(0)); require(msg.sender != _current_owner); require(msg.value >= _price); require(arts[_tokenId].owner != address(0)); _transfer(_current_owner, msg.sender, _tokenId); if(msg.value > _price) msg.sender.transfer(msg.value - _price); _current_owner.transfer(_price); arts[_tokenId].owner = msg.sender; arts[_tokenId].status = 0; ArtTxn memory _artTxn = ArtTxn({id: _id, price: _price, seller: _current_owner, buyer: msg.sender, txnDate: now, status: _status }); artTxns[_id].push(_artTxn); pendingArtCount--; emit LogArtSold(_tokenId,_title, _authorName,_price, _author,_current_owner,msg.sender); }

The buyArt() function verifies whether the buyer has enough balance to purchase the art. The function also checks whether the seller and buyer both have a valid account address. The token owner's address is not the same as the buyer's address. The seller is the owner of the art. Once all of the conditions have been verified, it will start the payment and art token transfer process. _transfer transfers an art token from the seller to the buyer's address. _current_owner.transfer will transfer the buyer's payment amount to the art owner's account. If the seller pays extra Ether to buy the art, that ether will be refunded to the buyer's account.

Finally, the buyArt() function will update art ownership information in the blockchain. The status will change to 0, also known as the sold status. The function implementations keep records of the art transaction in the ArtTxn array.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.