Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Strings.toString for signed integers #3773

Merged
merged 19 commits into from
Dec 28, 2022
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions contracts/utils/Strings.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
* @dev String operations.
Expand Down Expand Up @@ -37,6 +38,13 @@ library Strings {
}
}

/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}

/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
Expand Down
22 changes: 17 additions & 5 deletions test/utils/Strings.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,24 @@ contract('Strings', function (accounts) {
'12345678901234567890123456789012345678901234567890',
'123456789012345678901234567890123456789012345678901234567890',
'1234567890123456789012345678901234567890123456789012345678901234567890',
].reduce((acc, value) => Object.assign(acc, { [value]: new BN(value) }), {
MAX_UINT256: constants.MAX_UINT256.toString(),
].reduce((acc, value) => Object.assign(acc, { [value]: new BN(value), [-value]: new BN(-value) }), {
frangio marked this conversation as resolved.
Show resolved Hide resolved
MIN_INT256: constants.MIN_INT256,
MAX_INT256: constants.MAX_INT256,
MAX_UINT256: constants.MAX_UINT256,
}))) {
it(`converts ${key}`, async function () {
expect(await this.strings.methods['toString(uint256)'](value)).to.equal(value.toString(10));
});
// only numbers in the [0, 2**256-1] range
if (value.gten(0) && value.lte(constants.MAX_UINT256)) {
it(`converts ${key} as uint256`, async function () {
expect(await this.strings.methods['toString(uint256)'](value)).to.equal(value.toString(10));
});
}

// only numbers in the [-2**255, 2**255-1] range
if (value.gte(constants.MIN_INT256) && value.lte(constants.MAX_INT256)) {
it(`convert ${key} as int256`, async function () {
expect(await this.strings.methods['toString(int256)'](value)).to.equal(value.toString(10));
});
}
}
});

Expand Down