Skip to content

Commit e14b79f

Browse files
authored
Merge pull request #28 from dl-solidity-library/feature/sqrt
feature/sqrt
2 parents 2b0282d + b4ea468 commit e14b79f

File tree

6 files changed

+639
-842
lines changed

6 files changed

+639
-842
lines changed

contracts/libs/math/DSMath.sol

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// SPDX-License-Identifier: ALGPL-3.0-or-later-or-later
22
// from https://github.com/makerdao/dss/blob/master/src/jug.sol
3+
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol
34
pragma solidity ^0.8.4;
45

56
library DSMath {
@@ -57,4 +58,55 @@ library DSMath {
5758
}
5859
}
5960
}
61+
62+
/**
63+
* @notice The function that computes square roots using the Babylonian method
64+
* @dev The original implementation can be found here github.com/abdk-consulting/abdk-libraries-solidity
65+
*/
66+
function sqrt(uint256 x) internal pure returns (uint128) {
67+
unchecked {
68+
if (x == 0) {
69+
return 0;
70+
} else {
71+
uint256 xx = x;
72+
uint256 r = 1;
73+
if (xx >= 0x100000000000000000000000000000000) {
74+
xx >>= 128;
75+
r <<= 64;
76+
}
77+
if (xx >= 0x10000000000000000) {
78+
xx >>= 64;
79+
r <<= 32;
80+
}
81+
if (xx >= 0x100000000) {
82+
xx >>= 32;
83+
r <<= 16;
84+
}
85+
if (xx >= 0x10000) {
86+
xx >>= 16;
87+
r <<= 8;
88+
}
89+
if (xx >= 0x100) {
90+
xx >>= 8;
91+
r <<= 4;
92+
}
93+
if (xx >= 0x10) {
94+
xx >>= 4;
95+
r <<= 2;
96+
}
97+
if (xx >= 0x4) {
98+
r <<= 1;
99+
}
100+
r = (r + x / r) >> 1;
101+
r = (r + x / r) >> 1;
102+
r = (r + x / r) >> 1;
103+
r = (r + x / r) >> 1;
104+
r = (r + x / r) >> 1;
105+
r = (r + x / r) >> 1;
106+
r = (r + x / r) >> 1; // Seven iterations should be enough
107+
uint256 r1 = x / r;
108+
return uint128(r < r1 ? r : r1);
109+
}
110+
}
111+
}
60112
}

contracts/mock/libs/math/DSMathMock.sol

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,8 @@ contract DSMathMock {
77
function rpow(uint256 x_, uint256 n_, uint256 b_) external pure returns (uint256) {
88
return DSMath.rpow(x_, n_, b_);
99
}
10+
11+
function sqrt(uint256 x_) external pure returns (uint256) {
12+
return DSMath.sqrt(x_);
13+
}
1014
}

contracts/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@dlsl/dev-modules",
3-
"version": "2.0.2",
3+
"version": "2.0.3",
44
"license": "MIT",
55
"author": "Distributed Lab",
66
"description": "Solidity Development Modules by Distributed Lab",

0 commit comments

Comments
 (0)