1

So I want to test this Solidity code using Typescript but faced with a type conversion issue.


uint16 base;

function addNumberToBase(uint16 number_) {
    // This number must be between 1 ~ 5
    require(number_ < 1 && number_ >= 5, "This number must be between 1 ~ 5");
    base += number_;
}

And here is the TS testing code, I tried here many types but didn't work.

it("Should add a number between 1 ~ 5 to base", async () => {
     const number_ : Number = 4;
     await contract.addNumberToBase(number_); 

     // But here getting this error: 
     // Error: VM Exception while processing transaction: revert This number must be between 1~5
});

The same with using types Uint16Array and BigNumberish.

My suggestion is that's because of an issue in converting between types in both languages. So, please are there any useful libraries for converting uint16?

Thanks.

2

This line:

require(number_ < 1 && number_ >= 5, "This number must be between 1 ~ 5");

This is an impossibility.

It should say:

require(number_ >= 1 && number_ <= 5, "This number must be between 1 ~ 5");

I'm not 100% if you will get a JavaScript number or a BigNumber since uint16 can be handled by JavaScript. It's always BigNumber for uint256 types that are too big for JavaScript native types.

If the returned value looks like a weird object, use toString(10) to parse it, e.g. var value = parseInt(response.toString(10));

Hope it helps.

3
  • Nice answer! I wonder what could be an unwanted side effect of using toString() instead of toString(10)?
    – pwagner
    Mar 10 at 22:40
  • The 10 bit means to use "base10" (decimal) for interpretation of the value. Mar 11 at 0:14
  • Thanks so much, the error has been solved, it was a logical error from the contract itself. 💯
    – penguin
    Mar 11 at 8:54
1

The first paramter in require must be true for it to continue. Currently, your code checks for a number that is smaller than 1, and larger than or equal to 5. If you change the require call to the following, it should work:

require(number >= 1 && number <= 5, "This number must be between 1 - 5");

This is not an issue with converting numbers to uint16, as Web3.js and Ethers.js can do that automatically.

1
  • Thanks so much, the error has been solved, it was a logical error from the contract itself. 💯
    – penguin
    Mar 11 at 8:55

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.