2. Creating a BMC Smart Contract
Last updated
Last updated
In this section we will be creating the smart contract that houses the BMC functionality. To get started, navigate to your contracts folder, create a new file named BuyMeACoffee.sol
and paste this code below:
Let's quickly go over what each line of code does:
The NewCoffee event is emitted when a buyCoffee function is executed. It logs out the address of the sender, the name of the sender, the message sent, and the timestamp.
Next is the owner variable, which represents the contract deployer. We then set the msg.sender to be the owner of the contract in our constructor.
The coffeeId was created to keep track of the coffee transaction created.
Subsequently we declared a buyMeACoffee struct, which stores all the data related to a coffee transaction; address sender, string name, uint timestamp, string message. We then mapped this struct to an id using the idToBuyCoffee variable.
The buyCoffee function is the core implementation of BMC smart contract. It is a payable function which takes in two parameters, the name and address of the sender. It checks if the KLAY amount sent in is greater than zero. Next it increments the coffeeId, then it adds the coffee tx or info to the blockchain. Finally it emits a NewCoffee event, which entails the details of the coffee tx.
We created a withdraw() function to withdraw the total balance of the contract (address(this).balance) to the owner.
Finally, a getAllCoffee() function was created. It returns all the coffee transactions created overtime.
Now that we have completed writing our BMC smart contract, the next step is to test the functionalities of our smart contract, deploy and interact with the smart contract on Klaytn Testnet Baobab.