Skip to content

Commit

Permalink
Add toChecksumAddress in Utils.php
Browse files Browse the repository at this point in the history
  • Loading branch information
sc0Vu committed Oct 2, 2019
1 parent 0659ec0 commit d028950
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
27 changes: 26 additions & 1 deletion src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public static function isAddress($value)

/**
* isAddressChecksum
*
*
* @param string $value
* @return bool
*/
Expand All @@ -212,6 +212,31 @@ public static function isAddressChecksum($value)
return true;
}

/**
* toChecksumAddress
*
* @param string $value
* @return string
*/
public static function toChecksumAddress($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to toChecksumAddress function must be string.');
}
$value = self::stripZero(strtolower($value));
$hash = self::stripZero(self::sha3($value));
$ret = '0x';

for ($i = 0; $i < 40; $i++) {
if (intval($hash[$i], 16) >= 8) {
$ret .= strtoupper($value[$i]);
} else {
$ret .= $value[$i];
}
}
return $ret;
}

/**
* isHex
*
Expand Down
31 changes: 29 additions & 2 deletions test/unit/UtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ public function testIsAddress()

/**
* testIsAddressChecksum
*
*
* @return void
*/
public function testIsAddressChecksum()
Expand Down Expand Up @@ -291,9 +291,36 @@ public function testIsAddressChecksum()
$isAddressChecksum = Utils::isAddressChecksum(new stdClass);
}

/**
* testToChecksumAddress
*
* @return void
*/
public function testToChecksumAddress()
{
$checksumAddressTest = [
// All caps
'0x52908400098527886E0F7030069857D2E4169EE7',
'0x8617E340B3D01FA5F11F306F4090FD50E238070D',
// All Lower
'0xde709f2102306220921060314715629080e2fb77',
'0x27b1fdb04752bbc536007a920d24acb045561c26',
// Normal
'0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed',
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
'0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB',
'0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb'
];

for ($i=0; $i<count($checksumAddressTest); $i++) {
$checksumAddress = Utils::toChecksumAddress(strtolower($checksumAddressTest[$i]));
$this->assertEquals($checksumAddressTest[$i], $checksumAddress);
}
}

/**
* testStripZero
*
*
* @return void
*/
public function testStripZero()
Expand Down

0 comments on commit d028950

Please sign in to comment.