File Coverage

blib/lib/Blockchain/Ethereum/Address.pm
Criterion Covered Total %
statement 39 39 100.0
branch 4 6 66.6
condition n/a
subroutine 11 11 100.0
pod 2 4 50.0
total 56 60 93.3


line stmt bran cond sub pod time code
1             package Blockchain::Ethereum::Address;
2              
3 12     12   377856 use v5.26;
  12         62  
4 12     12   73 use strict;
  12         32  
  12         371  
5 12     12   60 use warnings;
  12         22  
  12         1243  
6              
7             # ABSTRACT: Ethereum address abstraction
8             our $AUTHORITY = 'cpan:REFECO'; # AUTHORITY
9             our $VERSION = '0.021'; # VERSION
10              
11 12     12   78 use Carp;
  12         50  
  12         1174  
12 12     12   1166 use Crypt::Digest::Keccak256 qw(keccak256_hex);
  12         13905  
  12         5835  
13              
14             sub new {
15 18     18 0 181471 my ($class, %params) = @_;
16              
17 18         40 my $address = $params{address};
18 18 50       54 croak "Required param address not given" unless $address;
19              
20 18         44 my $self = bless {}, $class;
21 18         114 $self->{address} = $address;
22 18         51 $self->_checksum;
23              
24 18         106 return $self;
25             }
26              
27             sub address {
28 63     63 0 249 return shift->{address};
29             }
30              
31             sub _checksum {
32 18     18   37 my ($self) = shift;
33              
34 18         46 my $unprefixed = $self->no_prefix;
35              
36 18 50       53 croak 'Invalid address format' unless length($unprefixed) == 40;
37              
38 18         66 my @hashed_chars = split //, keccak256_hex(lc $unprefixed);
39 18         582 my @address_chars = split //, $unprefixed;
40 18         32 my $checksummed_chars = '';
41              
42 18 100       602 $checksummed_chars .= hex $hashed_chars[$_] >= 8 ? uc $address_chars[$_] : lc $address_chars[$_] for 0 .. length($unprefixed) - 1;
43              
44 18         90 $self->{address} = "0x$checksummed_chars";
45 18         223 return $self;
46             }
47              
48             sub no_prefix {
49 36     36 1 49 my $self = shift;
50              
51 36         64 my $unprefixed = $self->address =~ s/^0x//r;
52 36         118 return $unprefixed;
53             }
54              
55             use overload
56 12         144 fallback => 1,
57 12     12   3132 '""' => \&to_string;
  12         8529  
58              
59             sub to_string {
60 27     27 1 7886 my $self = shift;
61 27         91 return $self->address;
62             }
63              
64             1;
65              
66             __END__