科技隨筆
科技隨筆

| 科技閱讀 | 程式語言 | 理財規劃 | 工具推薦 | 音樂盛宴 | 生活雜談 | 科技隨筆中,不只有科技! 在這裡,我會隨筆記下科技閱讀、程式語言、理財規劃、音樂饗宴以及生活雜談等等內容。 邀請您在過程中與我一同分享也一同成長。 讓我們在人生的旅途中不斷學習,努力成為更棒的人吧~ 在其他平臺關注我: https://linkby.tw/itechnote.co

[New Year's Plan] Coins that come and go freely | Smart Contract Development Plan #3

This article continues the previous code, and adds wallet balance inquiry and transfer functions. After completion, the transfer will be attempted. If the results of the test and inquiry are all correct, congratulations on completing a cryptocurrency that can be transferred. Rely on it to make you a popular discussion among relatives and friends!

foreword

This is the third part of the special plan for the new year. Our goal is to learn to write our first smart contract and issue our own cryptocurrency before the new year. It can be sent as a red envelope to relatives and friends, or think about the use of our currency and create An economic model of a currency, so if you haven't read one, the link to the first is here .

But you will find that the two trial works from the previous article can't do anything but enjoy them as vases. Since it is currency, the transfer transaction function is basic.

No problem, we will write the third program right away. Like the first two programs, go back to the file manager and open a new file under contracts. I will name it TransferToken.sol . This time the program is much more complicated. Open, the entire complete code will be attached to the back of the article.

The third trial work | tradable smart contracts

In order to complete a functioning cryptocurrency, in addition to the customization function of the initial parameters of the cryptocurrency developed last time, two steps are required, which are divided into two parts: wallet balance inquiry and transfer.

"Wallet Balance Inquiry"

In order for coins to be traded, there must be a function that can query the balance. Why?

Imagine if you are a bank and encounter a transaction request from a customer. The content of the request is to ask you to remit his money to someone else's account. The first thing to do is to check the balance of his bank account first. Is it more or just right than the amount to be remitted, otherwise it will be very troublesome for the account to become negative after the deduction, and maybe the bank can freeze his account to recover the money, but in the blockchain world , the money remittance means that the remittance cannot be handled at all, and I can only pray that he will remember to pay back the money one day.

Therefore, in order to be able to achieve the function of the transaction, checking whether there is enough money in the wallet is the first step. This is also the simplest part of the entire code, which is only one line:

 mapping(address => uint256) public balanceOf;

It means to read the balance data of the wallet and store it in a variable named balanceOf. After adding this variable, when we publish the smart contract, the original Deployed Contracts place will change from four variable buttons to five.


Let's copy the wallet address of the smart contract first. The wallet address is in ACCOUNT in "DEPLOY & RUN TRANSACTIONS", and there is a copy sign on the right.


Before clicking the balanceOf button, just paste the wallet address you just copied, and then press the balanceOf button, the wallet balance data will appear directly, and the amount should be the same as the _totalSupply set originally, because the money will be released in the smart contract. Deposit the publisher's address now! If you query balanceOf with other wallet addresses, it must be 0, because we have not yet written the function of transfer transactions, and it is impossible to obtain this cryptocurrency except for the publisher.

"Transfer"

Transfer is the most important part of this program. A thing that cannot be transferred is not a currency, maybe even an item.

event

When shopping, we will give the money in the wallet to the clerk. This action itself is an event, which is called event in Solidity, so we must first define an event, which is a convenient interface provided by the Ethereum Virtual Host (EVM). , when the money transfer actually occurs, you can directly call this event, and it will help us write this transaction on the ledger of the blockchain.

 event Transfer(address indexed from, address indexed to, uint256 value);

We create an event called Transfer, from is the wallet address of the sender, to is the wallet address of the receiver, how much is the value, and the uint256 in front of the value means whether it is a negative integer (so the value of value must be 0 or A positive integer), but this is the completed transaction, and we need to ask the host to help us with the code called when we upload the chain. We still have to do the pre-processing ourselves.

transfer code

In fact, when writing a smart contract, it is like building a vending machine that can operate automatically without manpower. Since we want to assist in transferring money, we must imagine ourselves as a bank or an ATM. Easy to understand.

The transfer will have two roles of "remitter" and "recipient". The thing to do is to "give how much money". Let's look at the code first:

 function transfer(address _to, uint256 _value) external returns (bool success) {
        require(balanceOf[msg.sender] >= _value);
        require(_to != address(0));

        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;

        emit Transfer(msg.sender, _to, _value);
        return true;
}

Let’s first briefly describe the purpose of this code:

Define a transfer function called transfer. To use this transfer function, you need to provide two parameters, _to and _value. If the program is executed successfully, it will return true to indicate that the transaction is all right; if it returns false, it means that there is a problem when the program is executed. Maybe he wrote the wrong transfer address, or maybe he didn't have that much money at all.

role definition

Who is the "remitter" in the blockchain? The person who uses this vending machine, that is, the wallet address using the smart contract, can directly use "msg. The address of the contract, if displayed, will be 0x.......

Who is the "payee" and what is the "how much money given"? Imagine that to make a bank transfer to a friend, we must enter two things, one is the friend's bank account, and the other is how much money; the same is true when it corresponds to the smart contract call, _to needs to fill in the other party's wallet address, _value needs to be Fill in the transfer amount, it's that simple.

Check Mechanism - Check remitter balance

In Solidity, require is a checking mechanism, which needs to put a judgment in it. If the judgment is true, the program will continue to run; if the judgment is not true, the program will directly return false and stop running.

 require(balanceOf[msg.sender] >= _value);

If the remitter wants to remit 5,000 yuan to the other party, but he only has 87 yuan in his account, of course he cannot make the remittance as he likes, so we need to use require to check the balance first. The way to check is to call the balance inquiry we wrote. The inspection object is the remitter (msg.sender), and the judgment formula used for the inspection is whether his balance is greater than or equal to the amount to be remitted _value.

Check Mechanism - Check Payee Address Correctness

 require(_to != address(0));

In fact, the meaning of checking whether the payee's address is correct is not to ensure that the address you enter is the payee's address, but to avoid accidentally not filling in the payee's address, resulting in an empty address (_to = 0x0). I thought that 0x0 is a wallet address with all 0s, and money will be remitted to this zero address, resulting in the loss of cryptocurrency assets, but after researching it, it seems that this is not the case, because this is written in the official Solidity document :

If the target account is not set (the transaction does not have a recipient or the recipient is set to null ), the transaction creates a new contract . As already mentioned, the address of that contract is not the zero address but an address derived from the sender and its number of transactions sent (the “nonce”).

It seems that for the Ethereum virtual machine, if you receive a zero address when doing a transaction, it means that we intend to issue a new smart contract, rather than transferring assets. Pay special attention!

transfer process

Transfer is the deduction of money by the remitter. It is as simple as adding money to the beneficiary. If it is written in Chinese, it will look like this:

 Money in the sender's wallet = Money in the sender's wallet - Amount sent Money in the recipient's wallet = Money in the recipient's wallet + Amount received

If it is converted into code, it will be written like this, adding or deducting the transfer amount to the money in the corresponding character's wallet.

 balanceOf[msg.sender] = balanceOf[msg.sender] - _value;
balanceOf[_to] = balanceOf[_to] + _value;

Or you can use the += and -= shorthands to make the code look more concise.

 balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;

send transaction

Finally, at the end of the code, the program can be executed here, indicating that there is no abnormality in the front, so the transaction record must be officially sent to the blockchain.

 emit Transfer(msg.sender, _to, _value);
return true;

Use the method of emit to send the transaction request to the Transfer event written at the beginning, and finally return all normal true to end.

TransferToken.sol

In addition to what was written in the previous article, the entire code should now look like this:

 // SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;

contract Token {

    string public name;
    string public symbol;
    uint256 public decimals;
    uint256 public totalSupply;

    constructor(string memory _name, string memory _symbol, uint _decimals, uint _totalSupply){
        name = _name;
        symbol = _symbol;
        decimals = _decimals;
        totalSupply = _totalSupply;
        balanceOf[msg.sender] = totalSupply;
    }

    mapping(address => uint256) public balanceOf;

event Transfer(address indexed from, address indexed to, uint256 value);

    function transfer(address _to, uint256 _value) external returns(bool success){
        require(balanceOf[msg.sender] >= _value);
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        emit Transfer(msg.sender, _to, _value);
        return true;
    }
}

Money jumping between wallets

After each program is written, you must remember to compile and publish it, and then fill in the initial parameters to issue coins, which will not be repeated here. If you forget, you can go back to the previous article to see how to operate, and then we will actually operate the coin issuance and transfer to ensure that the programs written can work normally without bugs.

transfer money


When transferring money, we will need two roles, the remitter and the payee. Assuming that the address issued by the contract starts with 0x5B and is labeled as 1 by me, then when the contract is released, the total supply of this currency will be fully released. Into this address, before any transfer occurs, only this address in the world will have the currency just sent, so it must be the sender.

The payee is an address marked by me as 2, starting with 0xAb. Please switch the ACCOUNT field to 2 first, and press the icon marked with the yellow circle on the right to copy its address. At this time, you must ACCOUNT switches back to address 1 again, because we are going to use address 1 to call the transfer function in the smart contract, which will be msg.sender himself.

Scroll down in "DEPLOY & RUN TRANSACTIONS" and you will see Deployed Contracts, you will find an additional orange transfer button, which is used to let us transfer money, there is a small downward arrow on the right, it should be long so:


_to: It is the payee, which is another wallet address. This address is directly pasted with the address that we just switched to the second wallet starting with 0xAb in the ACCOUNT field, or you can paste other addresses if you want.

_value: Just fill in the amount to be transferred, as long as it is not a negative integer, filling in 100 here means to remit 0.0000000000000001 coins we sent, because Decimals are 18 digits after the decimal point, so the _value field Fill in 100 to indicate that the amount to be remitted is 100 x 10e-18 = 10e-16 = 0.0000000000000001 tokens, if you want to remit 100 tokens, the value must be filled in 100,000,000,000,000,000,000, which is 100 followed by 18 0s .

After the two parameters are set, you can press the orange transact, and the transfer is successful!

Validation results

Here we use the balanceOf function to directly enter the corresponding wallet address to query the balance. Assuming that after the contract is released, we only make the one transfer done above, and transfer the currency of _value: 100 (equivalent to 0.0000000000000001) to another One wallet address, the balance of the two wallets should show 99999999999999999999999999900 and the other should show 100:



If the balance is the same as the result of the previous transfer operation, then congratulations that you have successfully issued your own cryptocurrency. This coin is alive and can jump between wallets!

Epilogue

After this change, we have issued a tradable currency, and the actual transfer should be fine, indicating that the tests on the local side can work normally.

Next time we will try to send coins to the testnet, you will need to have a Metamask wallet, so stay tuned!

Further reading

Previous: [New Year's Plan] The first fortune coin in life | Smart contract development plan #2


Finally, thank you for taking the time out of your busy schedule to read my articles. If you still like these content, I hope to get your follow-up and support. You are also welcome to click this link to find me on other platforms .

See you next time o((>ω< ))o~

Original link ITechNote technology essay

CC BY-NC-ND 2.0

Like my work?
Don't forget to support or like, so I know you are with me..

Loading...
Loading...

Comment