solidity development msg.value

I just finished learning the basic development of solidity and wanted to write a crowdfunding project. When using msg.value, I found that as long as msg.value is used in the function, the money in the account will be automatically transferred to the contract account. This makes me very confused, so how to transfer it out? I wrote a demo to test it.

pragma solidity ^0.4.26;

contract sendmoney{
    
    

    uint a;
    //用于获取当前合约账户的钱
    function getBalance() returns(uint){
    
    
        return this.balance;
    }
    function transfer() payable {
    
    
        a = msg.value; //用于接收sender转的eth
    }
    function sendMoney() {
    
    
        address add = 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db;//这是我的一个测试账户
        add.transfer(a); //将eth从合约账户转到指定账户里
        
    }
    
}

The test result is: when I call transfer(), the eth of the sender will be deducted and transferred to the current contract account, and after calling sendMoney(), the eth will be transferred from the contract account to the test account.
My understanding is that what is carried in msg.value is the sender’s eth information (simple understanding is that msg.value is a sum of money), and in the above code, the sender’s eth information is carried by a (a is the money), a is placed in the contract account before being transferred to other accounts.

Guess you like

Origin blog.csdn.net/Bad_foxS/article/details/127559198