Add fromWei in Utils.

This commit is contained in:
sc0Vu 2017-12-25 10:10:17 +08:00
parent 7c1755cc9c
commit fbc85e74d0
2 changed files with 77 additions and 0 deletions

View File

@ -160,6 +160,10 @@ class Utils
/**
* toWei
* Change number from unit to wei.
* For example:
* $wei = Utils::toWei('1', 'kwei');
* $wei->toString(); // 1000
*
* @param BigNumber|string|int $number
* @param string $unit
@ -192,6 +196,10 @@ class Utils
/**
* toEther
* Change number from unit to ether.
* For example:
* list($bnq, $bnr) = Utils::toEther('1', 'kether');
* $bnq->toString(); // 1000
*
* @param BigNumber|string|int $number
* @param string $unit
@ -207,4 +215,40 @@ class Utils
return $wei->divide($bnt);
}
/**
* fromWei
* Change number from wei to unit.
* For example:
* list($bnq, $bnr) = Utils::fromWei('1000', 'kwei');
* $bnq->toString(); // 1
*
* @param BigNumber|string|int $number
* @param string $unit
* @return \phpseclib\Math\BigInteger
*/
public static function fromWei($number, $unit)
{
if (is_int($number)) {
$bn = new BigNumber($number);
} elseif (is_string($number)) {
if (self::isZeroPrefixed($number)) {
$number = self::stripZero($number);
$bn = new BigNumber($number, 16);
} else {
$bn = new BigNumber($number);
}
} elseif (!$number instanceof BigNumber){
throw new InvalidArgumentException('fromWei number must be BigNumber, string or int.');
}
if (!is_string($unit)) {
throw new InvalidArgumentException('fromWei unit must be string.');
}
if (!isset(self::UNITS[$unit])) {
throw new InvalidArgumentException('fromWei doesn\'t support ' . $unit . ' unit.');
}
$bnt = new BigNumber(self::UNITS[$unit]);
return $bn->divide($bnt);
}
}

View File

@ -180,4 +180,37 @@ class UtilsTest extends TestCase
$this->assertEquals($bnq->toString(), '0');
$this->assertEquals($bnr->toString(), '21016');
}
/**
* testFromWei
*
* @return void
*/
public function testFromWei()
{
list($bnq, $bnr) = Utils::fromWei('1000000000000000000', 'ether');
$this->assertEquals($bnq->toString(), '1');
$this->assertEquals($bnr->toString(), '0');
list($bnq, $bnr) = Utils::fromWei('18', 'wei');
$this->assertEquals($bnq->toString(), '18');
$this->assertEquals($bnr->toString(), '0');
list($bnq, $bnr) = Utils::fromWei(1, 'femtoether');
$this->assertEquals($bnq->toString(), '0');
$this->assertEquals($bnr->toString(), '1');
list($bnq, $bnr) = Utils::fromWei(0x11, 'nano');
$this->assertEquals($bnq->toString(), '0');
$this->assertEquals($bnr->toString(), '17');
list($bnq, $bnr) = Utils::fromWei('0x5218', 'kwei');
$this->assertEquals($bnq->toString(), '21');
$this->assertEquals($bnr->toString(), '16');
}
}