0
votes

I'm working on Solidity Contract, but I cannot find a way to deposit a predefined value from an External Address to the Contract. This is the test code I'm using:

pragma solidity 0.5.12;

contract Payment {

    mapping(address => uint256) public balances;

    address payable wallet;

    constructor(address payable _wallet) public {
        wallet = _wallet;
    }

    function buyToken() public payable {
        balances[msg.sender] += 1;

        wallet.transfer(0.1 ether);

    }

    function () payable external{}

    function getContractBalance() public view returns(uint) {
        return address(this).balance;
    }

}

In Remix, if I use msg.value it works fine. I deploy the contract with an Address "1", then I use an Address "2", then I execute buyToken(), so 1 Ether (from Remix Test form) was sent from Address "2" to Address "1". If I use a fixed value (like 0.1 ether) it not works.

What I want is a people can deposit a fixed amount of ETH (in really it will be TRON, but the code is the same) in the contract.

Thanks for help.

1

1 Answers

0
votes

buyToken will fail if contract has less than 0.1 ether balance. If contract balance has more than 0.1 ether, buyToken will work and wallet will receive 0.1 ether.

Assuming contract has 0 balance

If address2 calls buyToken with 0.001 ether, transaction will fail because contract do not have sufficient balance to transfer 0.1 ether.

If address2 calls buyToken with 5 ether, transaction will be successful. wallet address will receive 0.1 ether.

    function buyToken() public payable {
        balances[msg.sender] += 1;

        wallet.transfer(0.1 ether);

    }

msg.value will always work because it transfers any amount it receives to wallet address.

If address2 calls buyToken with 0.001 ether, wallet will receive 0.001 ether.

If address2 calls buyToken with 5 ether, wallet will receive 5 ether.

    function buyToken() public payable {
        balances[msg.sender] += 1;

        wallet.transfer(msg.value);

    }