0

Let's say we want to make a transaction of x ether and if (x>20) refund 5% to sender and send rest to the original initial receiver.How can I implement it in smart contract code, and invoke it from console ? should I send ether to contract and receiver's address in data or something like that...

1 Answer 1

0

Using a withdraw pattern which is a best practice, it would look something like this. In case it isn't clear, the function is a lot like an ATM.

pragma solidity ^0.4.18;

contract Refund {

    mapping(address => uint) public balances;

    event LogDeposit(address sender, uint amount);
    event LogWithdrawal(address receiver, uint amount);

    function withdrawFunds(uint amount) public returns(bool success) {
        require(amount >= balances[msg.sender]);
        LogWithdrawal(msg.sender, amount);
        msg.sender.transfer(amount);
        return true;
    }

    function () public payable {
        require(msg.value > 0);
        uint change;
        uint dep;
        if(msg.value > 20) {
            dep = 20;
            change = msg.value - change;
        }
        balances[msg.sender] += dep;
        if(change > 0) balances[msg.sender] += change;
        LogDeposit(msg.sender, msg.value);
    }
}

Hope it helps.

p.s. Apologies for the formatting. Browser isn't playing nice with SE today.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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