You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- User-Defined Value Types allow you to create a custom type name that wraps an existing built-in value type (like `uint256`, `int128`, `bytes32`, etc.).
1023
+
- This feature was introduced in Solidity 0.8.8 and provides a way to give **semantic meaning** to a primitive type, helping catch logic errors and improving code readability.
1024
+
1025
+
### Motivation
1026
+
1027
+
-**Type Safety & Readability**: By assigning a descriptive name to a built-in type, you can differentiate between, say, a `UserId` and a `Balance`, even if they’re both `uint256` under the hood.
1028
+
-**Compile-Time Checks**: Conversions between different user-defined value types (and between the user-defined type and its underlying type) require **explicit** wrapping/unwrapping. This helps avoid mixing up incompatible values in your code.
1029
+
1030
+
### Syntax
1031
+
1032
+
```solidity
1033
+
type TypeName is UnderlyingType;
1034
+
```
1035
+
1036
+
-`TypeName`: The name of your new type (PascalCase by convention).
1037
+
-`UnderlyingType`: Any built-in value type (e.g., `uint256`, `int128`, `bool`, `bytes32`, etc.).
1038
+
1039
+
```solidity
1040
+
type UserId is uint256;
1041
+
type Price is uint128;
1042
+
type Flag is bool;
1043
+
```
1044
+
1045
+
### Wrapping and Unwrapping
1046
+
1047
+
- Wrapping: Converting an underlying type to a user-defined type.
1048
+
- Unwrapping: Converting a user-defined type back to its underlying type.
1049
+
1050
+
```solidity
1051
+
uint256 rawId = 123;
1052
+
// Wrap a uint256 into a UserId
1053
+
UserId userId = UserId.wrap(rawId);
1054
+
1055
+
// Unwrap a UserId to a uint256
1056
+
uint256 unwrappedId = UserId.unwrap(userId);
1057
+
1058
+
// ❌ This will fail: Type uint256 is not implicitly convertible to UserId
1059
+
UserId invalidConversion = 123;
1060
+
```
1061
+
1062
+
### Operations and Conversions
1063
+
1064
+
By default, **no** arithmetic or comparison operations are defined for user-defined value types. If you need to perform operations on your custom type, you can:
1065
+
1066
+
1.**Unwrap** your custom type, perform the operations on the underlying type, then **re-wrap** the result.
1067
+
2. Define **inline** or **library** functions that handle the logic for your custom type.
1068
+
1069
+
```solidity
1070
+
pragma solidity ^0.8.29;
1071
+
1072
+
type Distance is uint256;
1073
+
1074
+
library DistanceLib {
1075
+
function add(Distance a, Distance b) internal pure returns (Distance) {
0 commit comments