From 46c252a44e07a93009a3a9085997857a760747ec Mon Sep 17 00:00:00 2001 From: sc0Vu Date: Sun, 24 Dec 2017 23:42:46 +0800 Subject: [PATCH] toEther --- src/Utils.php | 20 +++++++++++++++++++- test/unit/UtilsTest.php | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/Utils.php b/src/Utils.php index 5320fcc..387656f 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -163,7 +163,7 @@ class Utils * * @param BigNumber|string|int $number * @param string $unit - * @return string + * @return \phpseclib\Math\BigInteger */ public static function toWei($number, $unit) { @@ -187,4 +187,22 @@ class Utils return $bn->multiply($bnt); } + + /** + * toEther + * + * @param BigNumber|string|int $number + * @param string $unit + * @return array + */ + public static function toEther($number, $unit) + { + if ($unit === 'ether') { + throw new InvalidArgumentException('Please use another unit.'); + } + $wei = self::toWei($number, $unit); + $bnt = new BigNumber(self::UNITS['ether']); + + return $wei->divide($bnt); + } } \ No newline at end of file diff --git a/test/unit/UtilsTest.php b/test/unit/UtilsTest.php index 01e72ff..3b49dde 100644 --- a/test/unit/UtilsTest.php +++ b/test/unit/UtilsTest.php @@ -138,4 +138,37 @@ class UtilsTest extends TestCase $this->assertEquals($bn->toString(), '21016'); } + + /** + * testToEther + * + * @return void + */ + public function testToEther() + { + list($bnq, $bnr) = Utils::toEther('0x1', 'wei'); + + $this->assertEquals($bnq->toString(), '0'); + $this->assertEquals($bnr->toString(), '1'); + + list($bnq, $bnr) = Utils::toEther('1', 'wei'); + + $this->assertEquals($bnq->toString(), '0'); + $this->assertEquals($bnr->toString(), '1'); + + list($bnq, $bnr) = Utils::toEther(1, 'wei'); + + $this->assertEquals($bnq->toString(), '0'); + $this->assertEquals($bnr->toString(), '1'); + + list($bnq, $bnr) = Utils::toEther('1', 'kether'); + + $this->assertEquals($bnq->toString(), '1000'); + $this->assertEquals($bnr->toString(), '0'); + + list($bnq, $bnr) = Utils::toEther('0x5218', 'wei'); + + $this->assertEquals($bnq->toString(), '0'); + $this->assertEquals($bnr->toString(), '21016'); + } } \ No newline at end of file