Skip to content

Commit

Permalink
update encoder to support more types
Browse files Browse the repository at this point in the history
  • Loading branch information
michavie committed Jul 22, 2022
1 parent 5016403 commit 5ddb57f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
11 changes: 10 additions & 1 deletion src/Utils/Encoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,27 @@

namespace Superciety\ElrondSdk\Utils;

use Brick\Math\BigInteger;
use Superciety\ElrondSdk\Domain\Address;

class Encoder
{
public static function toHex(string|int $value, bool $skipHexBytePadding = false): string
public static function toHex(string|int|BigInteger|Address $value, bool $skipHexBytePadding = false): string
{
if (is_string($value)) {
return str_starts_with($value, 'erd1')
? Address::fromBech32($value)->hex()
: bin2hex(trim($value));
}

if ($value instanceof BigInteger) {
return bin2hex($value->toBytes());
}

if ($value instanceof Address) {
return $value->hex();
}

return $skipHexBytePadding
? dechex($value)
: static::toPaddedHex(dechex($value));
Expand Down
12 changes: 9 additions & 3 deletions tests/Utils/EncoderTest.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
<?php

use Brick\Math\BigInteger;
use Superciety\ElrondSdk\Domain\Address;
use Superciety\ElrondSdk\Utils\Encoder;

it('toHex - encodes strings into hex', fn () => expect(Encoder::toHex('anything'))->toBe('616e797468696e67'));

it('toHex - encodes single-byte into into hex', fn () => expect(Encoder::toHex(2))->toBe('02'));
it('toHex - encodes single-byte into hex', fn () => expect(Encoder::toHex(2))->toBe('02'));

it('toHex - encodes multi-byte into into hex', fn () => expect(Encoder::toHex(257))->toBe('0101'));
it('toHex - encodes multi-byte into hex', fn () => expect(Encoder::toHex(257))->toBe('0101'));

it('toHex - encodes an address string into into hex', fn () => expect(Encoder::toHex('erd18fswpz2r2q3p40jlewkt9u7d46lvrukdn8j09tppza75efv0jz8s2lc68r'))->toBe('3a60e0894350221abe5fcbacb2f3cdaebec1f2cd99e4f2ac21177d4ca58f908f'));
it('toHex - encodes an address into hex', fn () => expect(Encoder::toHex(Address::fromBech32('erd18fswpz2r2q3p40jlewkt9u7d46lvrukdn8j09tppza75efv0jz8s2lc68r')))->toBe('3a60e0894350221abe5fcbacb2f3cdaebec1f2cd99e4f2ac21177d4ca58f908f'));

it('toHex - encodes an address string into hex', fn () => expect(Encoder::toHex('erd18fswpz2r2q3p40jlewkt9u7d46lvrukdn8j09tppza75efv0jz8s2lc68r'))->toBe('3a60e0894350221abe5fcbacb2f3cdaebec1f2cd99e4f2ac21177d4ca58f908f'));

it('toHex - encodes an bigint into hex', fn () => expect(Encoder::toHex(BigInteger::of('25000000000000000000')))->toBe('015af1d78b58c40000'));

0 comments on commit 5ddb57f

Please sign in to comment.