Ethereum: What’s `//` in Vyper?

Vyper Ethereum Tutorial: Understanding // Syntax

Ethereum: What's `//` in Vyper?

As a developer using Vyper to create smart contracts, you may encounter the following error when performing a division operation:

InvalidOperation: Cannot perform decimal division on uint256

This issue occurs because Vyper does not support decimal arithmetic. When dividing two uint256 numbers in Vyper 0.4.0b or later, it throws an InvalidOperation exception.

What is the difference between // and (convert)?

There are two syntaxes for performing conversions in Vyper:

  • // convert():

– This method returns the converted value.

– It takes a single argument (the value to convert) and returns a new uint256.

– When used with the division operator (/) or modulo operator (%) it can cause problems due to floating point imprecision.

  • (convert(price, uint256)) * ...:

– This method takes two arguments: a value (as a string) and an unsigned integer.

– It tries to convert a string to uint256 and then multiplies it by the given number.

– In Vyper 0.4.0b or later this syntax is recommended for decimal division.

How ​​to fix the problem

To fix the error when performing division in Vyper:

  • Convert your values ​​using (convert(price, uint256)) * ...

When dividing two uint256 numbers, use the above syntax:

div(result, 10); // assuming 'result' is a variable holding one of the numbers

  • Avoid using // convert() in decimal division

As mentioned earlier, Vyper does not support decimal arithmetic when using the // method. Instead, use (convert(price, uint256)) * ....

Example use case: Decimal division

To demonstrate this approach, let’s create a simple example:

contract Math {

function divide(a: u32, b: u8) public pure returns (u32) {

return (a / convert(b, u256)) % 10; // using the converted value for decimal division

}

}

In this code snippet:

convert(1, 2) is a conversion function that converts a string to uint256. The convert method can handle both u32 and u8, making it suitable for our example.

– In the divide function, (convert(b, u256)) provides decimal arithmetic by converting any potential fractional part of b.

– Then we perform division using the converted value: a / (convert(b, u256)) % 10.

Conclusion

In this article, we investigated why Vyper throws an InvalidOperation exception when performing decimal division. By understanding how to convert values ​​correctly and using the recommended syntax (convert(price, uint256)) * ..., developers can solve this problem in their Vyper-based smart contracts.

ethereum software skills need

上部へスクロール