-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathAbiBase.php
More file actions
91 lines (72 loc) · 2.46 KB
/
AbiBase.php
File metadata and controls
91 lines (72 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
declare(strict_types=1);
namespace ArkEcosystem\Crypto\Utils;
use ArkEcosystem\Crypto\Enums\ContractAbiType;
use kornrunner\Keccak;
abstract class AbiBase
{
protected array $abi;
public function __construct(ContractAbiType $type = ContractAbiType::CONSENSUS, ?string $path = null)
{
$abiFilePath = $this->contractAbiPath($type, $path);
$abiJson = file_get_contents($abiFilePath);
$this->abi = json_decode($abiJson, true)['abi'];
}
protected static function getArrayComponents(string $type): ?array
{
if (preg_match('/^(.*)\[(\d*)\]$/', $type, $matches)) {
$innerType = $matches[1];
$lengthStr = $matches[2];
$length = $lengthStr !== '' ? intval($lengthStr) : null;
return [$length, $innerType];
}
return null;
}
protected static function stripHexPrefix(string $hex): string
{
if (substr($hex, 0, 2) === '0x') {
return substr($hex, 2);
}
return $hex;
}
protected function isValidAddress($address): bool
{
return is_string($address)
&& str_starts_with($address, '0x')
&& strlen($address) === 42
&& ctype_xdigit(substr($address, 2));
}
protected function keccak256(string $input): string
{
return '0x'.Keccak::hash($input, 256);
}
protected function getFunctionSignature(array $abiItem): string
{
$name = $abiItem['name'];
$inputs = $abiItem['inputs'];
$types = array_map(function ($input) {
return $input['type'];
}, $inputs);
return $name.'('.implode(',', $types).')';
}
protected function toFunctionSelector(array $abiItem): string
{
$signature = $this->getFunctionSignature($abiItem);
$hash = $this->keccak256($signature);
$selector = '0x'.substr($hash, 2, 8);
return $selector;
}
private function contractAbiPath(ContractAbiType $type, ?string $path = null): ?string
{
switch ($type) {
case ContractAbiType::CONSENSUS:
return __DIR__.'/Abi/json/Abi.Consensus.json';
case ContractAbiType::MULTIPAYMENT:
return __DIR__.'/Abi/json/Abi.Multipayment.json';
case ContractAbiType::USERNAMES:
return __DIR__.'/Abi/json/Abi.Usernames.json';
case ContractAbiType::CUSTOM:
return $path;
}
}
}