0

I am trying to write a smart contract which will do the below.

contract MyContract is ERC20{
IERC20 market;
IERC20 coin;
uint256 feesFactor = 0;
uint256 conversionRatio = 0;

    function setConversion(uint256 ratio) public {
        conversionRatio = ratio;
    }

    function getConversion() public view returns (uint256) {
        return conversionRatio;
    }

    function setFeesFactor(uint256 fees) public {
        feesFactor = fees;
    }


    function deposit(uint256 _amount) external onlyPositive(_amount) {
        

        coin.transferFrom(msg.sender, address(this), _amount);

        uint256 fees = _amount * feesFactor;

        market.mint(_amount - fees);

        uint256 tokens = (_amount - swapFees) * getConversion();
        _mint(msg.sender, tokens);

    }
}

Using web3js I attempt to pass .03 for the feeFactor and .04 for the conversionRatio using web3.utils.toWei(). This works and i can display these values after using web3.utils.fromWei().

However my deposit function fails silently; the _amount value is also sent using web3.utils.toWei().

What changes do i need to make on both the smart contract and the web3js code so that i can use decimals like .03 and .04 and get the deposit function to work.

Yes approval has been done on the coin before deposit is called. Thanks.

1 Answer 1

0

Unfortunately, you can't use decimal places in Solidity, at least not at this time. See OpenZeppellin's note on decimals here and in Solidity docs here

I'd recommend calculating in whole numbers that would completely eliminate decimal places (and headache).

You could think of conversionRatio and feeFactor as percentages. e.g.: .03 is 3%. You would simply send the number 3 from web3js without any conversion to and from Wei. The calculation of fees would look like this:

uint256 fees = (_amount / 100) * feesFactor;

An alternative is if there is a chance for fees to go even lower. You could also think of conversionRatio and feeFactor as basis points. A basis point (bp or ‱) is one-hundredth of 1 percentage point. e.g.: .03 is 300bp or 300‱. You would simply send the number 300 from web3js without any conversion to and from Wei. The calculation of fees would look like this:

uint256 fees = (_amount / 10000) * feesFactor;

You could define the 10000 or the 100 in a constant, or you could even create a helper function to calculate percentage.

1
  • worked for me! Thinking in terms of bps helped.
    – Two Mypt
    Commented Oct 29, 2022 at 10:32

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.