0

I have followed the steps of the solidity documentation to preform the work of fallback function.My code is below.

pragma solidity ^0.4.0;

contract Test {
    uint x;

    function () payable {
    }
}

contract Send {
    function sendtest() returns(bool ) {
        Test t = new Test();
        bool res = t.send(100 ether);
        return res;
    }
}

The result of t.send() is false.I don't know what's wrong with it.Whether I use the instance of contract insteading of the contract address or not?

1

this worked in remix for me, you just need to add the payable function. On the '100 ether' tag too, using wei is considered best practice (or msg.value)

    pragma solidity ^0.4.0;

contract Test {
    uint x;

    function () payable {
    }
}

contract Send {

    function sendtest() payable returns(bool ) {
        Test t = new Test();
        require(msg.value>0);
        bool res = t.send(msg.value);
        return res;

    }

}
  • I have run this code, but it got a exception. My purpose is sending ethers to the Test contract, so I don't know why I need to add payable to the sendtest function. – dingdang Sep 4 '17 at 2:00
  • oh, It really works well. I just forgot to set the value of value. But can you explain why it is necessary to add payable to sendtest function? – dingdang Sep 4 '17 at 2:27
  • Well you just can't send ether to a function unless it's payable. Adding this allows the sendtest to hold the money and then for it to send the money to the other contract. If you want to send it directly from your account, you can create another function. – thefett Sep 4 '17 at 13:07
0

If I got you correctly, you want to send ethers to your contract, Right? Give this code a try.

pragma solidity ^0.4.0;
contract Test {
    function () payable {}
}
contract Send {
    function sendtest() payable(returns bool){
        bool res = this.address.send(msg.value);
        return res
    }
}

When you call sendTest with some value, this value is transferred to contract. this refers to contract and hence this.address represents contract address.

The line this.address.send(msg.value) transfers the msg.value to the contract and this line function () payable {} allows contract to recieve ethers.

  • Can you explain why it is necessary to add the payable to sendtest function? Is it just the recevier function need this modifier? – dingdang Sep 4 '17 at 2:49
  • You can send ethers to a function unless it's payable. So in order to send ethers to sendTest you have to add payable modifier. – Prashant Prabhakar Singh Sep 4 '17 at 13:40
  • But my intention is to send ethers to Test contract,You code is sending ethers to Send constrct. – dingdang Sep 6 '17 at 6:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.