EtherscanConnector::validateAddress()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LaravelCryptoStats\Connectors;
4
5
use Exception;
6
use LaravelCryptoStats\Services\EthereumValidator;
7
8
class EtherscanConnector extends AbstractConnector
9
{
10
    public $supported_currencies = ['ETH'];
11
    protected $api_url_prefix = 'https://api.etherscan.io/api?';
12
    protected $api_description = 'https://etherscan.io/apis';
13
    protected $block_link_prefix = 'https://etherscan.io/address/';
14
15
    public function validateAddress(string $address): bool
16
    {
17
        if ($address) {
18
            return EthereumValidator::isAddress($address);
19
        }
20
21
        throw new Exception('Wallet address can not be empty!');
22
    }
23
24
    public function getBalance(string $address): float
25
    {
26
        if ($address) {
27
            $url = $this->api_url_prefix.'module=account&action=balance&address='.$address.'&tag=latest&apikey='.$this->config['etherscan_api_key'];
28
            $response = $this->apiCall($url);
29
30
            if (is_numeric($response)) {
31
                $balance = $this->convertFromWei($response);
32
33
                return $this->roundBalance($balance);
0 ignored issues
show
Bug introduced by
$balance of type double is incompatible with the type LaravelCryptoStats\Connectors\type expected by parameter $balance of LaravelCryptoStats\Conne...nnector::roundBalance(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

33
                return $this->roundBalance(/** @scrutinizer ignore-type */ $balance);
Loading history...
34
            } else {
35
                throw new Exception($response);
36
            }
37
        }
38
39
        throw new Exception('Wallet address can not be empty!');
40
    }
41
42
    public function getBlockExplorerLink(string $address): string
43
    {
44
        if ($address) {
45
            return $this->block_link_prefix.$address;
46
        }
47
48
        throw new Exception('Wallet address can not be empty!');
49
    }
50
51
    protected function apiCall(string $url)
52
    {
53
        $response = $this->sendApiRequest($url);
54
        if ($response && isset($response['status']) && isset($response['result'])) {
55
            return $response['result'];
56
        }
57
58
        throw new Exception('Output data is not correct. Check the API description - '.$this->api_description.'!');
59
    }
60
61
    /**
62
     * Convert balance of the ETH wallet from the Wei points to the float.
63
     *
64
     * @param int $balance
65
     *
66
     * @return float
67
     */
68
    private function convertFromWei($balance): float
69
    {
70
        return $balance / pow(10, 18);
71
    }
72
}
73