3

currently I'm writing my first contract in Solidity. Now I have a function which looks like this:

function sellEnergy(uint kwh) public {
    coinAccount[msg.sender] += (kwh * kWh_rate);
}

What I want to do is that everytime this function is called, the user who calls it, should pay a fee of a few cents to the owner. Is that possible? If so, how?

1 Answer 1

1

To set a fee, check msg.value and either throw (or return) if the fee isn't met. Example of a fee of 0.001 ether:

function sellEnergy(uint kwh) public {
    if (msg.value < 0.001 ether) { throw; }
    coinAccount[msg.sender] += (kwh * kWh_rate);
}

Using throw is recommended so that any other changes made to your contract are also reverted: it keeps your contract state clean. (People who don't pay the minimum fee, will lose all their gas though.)


A modifier can usually be helpful, so that functions that require a fee are labelled more clearly. Example of a modifier that's been given the name requiresFee:

contract SomeTest {
    // state variables ...

    modifier requiresFee(uint fee) {
        if (msg.value < fee) { throw; }
        _
    }

    function sellEnergy(uint kwh) public requiresFee(0.001 ether) {
        coinAccount[msg.sender] += (kwh * kWh_rate);
    }
}

If the fee is dynamic, the modifier could be modified like:

contract SomeTest {
    // state variables ...

    modifier requiresFee() {
        if (msg.value < computeFee()) { throw; }
        _
    }

    // returns the fee in units of Wei
    function computeFee() internal returns (uint) {
        // compute the fee and return it
    }

    function sellEnergy(uint kwh) public requiresFee() {
        coinAccount[msg.sender] += (kwh * kWh_rate);
    }
}

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.