|
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); |
|
|
|
|
|
|
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
|
|
|
|