diff --git a/src/Utils.php b/src/Utils.php index fbcf188..c0be691 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -282,6 +282,25 @@ class Utils } $bnt = new BigNumber(self::UNITS[$unit]); + if (is_array($bn)) { + // fraction number + list($whole, $fraction, $negative1) = $bn; + + $fractionLength = strlen($fraction->toString()); + + if ($fractionLength > strlen(self::UNITS[$unit])) { + throw new InvalidArgumentException('toWei fraction part is out of limit.'); + } + $whole = $whole->multiply($bnt); + $base = (new BigNumber(10))->pow(new BigNumber($fractionLength)); + $fraction = $fraction->multiply($bnt)->divide($base)[0]; + + if ($negative1 !== false) { + return $whole->add($fraction)->multiply($negative1); + } + return $whole->add($fraction); + } + return $bn->multiply($bnt); } diff --git a/test/unit/UtilsTest.php b/test/unit/UtilsTest.php index a519ab4..50b3f0e 100644 --- a/test/unit/UtilsTest.php +++ b/test/unit/UtilsTest.php @@ -259,14 +259,51 @@ class UtilsTest extends TestCase $bn = Utils::toWei('0x5218', 'wei'); $this->assertEquals($bn->toString(), '21016'); + $bn = Utils::toWei('0.1', 'ether'); + $this->assertEquals($bn->toString(), '100000000000000000'); + + $bn = Utils::toWei('1.69', 'ether'); + $this->assertEquals($bn->toString(), '1690000000000000000'); + + $bn = Utils::toWei(0.1, 'ether'); + $this->assertEquals($bn->toString(), '100000000000000000'); + + $bn = Utils::toWei(1.69, 'ether'); + $this->assertEquals($bn->toString(), '1690000000000000000'); + + $bn = Utils::toWei('-0.1', 'ether'); + $this->assertEquals($bn->toString(), '-100000000000000000'); + + $bn = Utils::toWei('-1.69', 'ether'); + $this->assertEquals($bn->toString(), '-1690000000000000000'); + + $bn = Utils::toWei(-0.1, 'ether'); + $this->assertEquals($bn->toString(), '-100000000000000000'); + + $bn = Utils::toWei(-1.69, 'ether'); + $this->assertEquals($bn->toString(), '-1690000000000000000'); + + $bn = Utils::toWei('', 'ether'); + $this->assertEquals($bn->toString(), '0'); + + $bn = Utils::toWei(-1.697, 'kwei'); + $this->assertEquals($bn->toString(), '-1697'); + try { - $toWei = Utils::toWei('0x5218', new stdClass); + $bn = Utils::toWei('0x5218', new stdClass); } catch (InvalidArgumentException $e) { $this->assertTrue($e !== null); } try { - $toWei = Utils::toWei('0x5218', 'test'); + $bn = Utils::toWei('0x5218', 'test'); + } catch (InvalidArgumentException $e) { + $this->assertTrue($e !== null); + } + + try { + // out of limit + $bn = Utils::toWei(-1.6977, 'kwei'); } catch (InvalidArgumentException $e) { $this->assertTrue($e !== null); }