feature
This commit is contained in:
@@ -19,4 +19,14 @@ interface ChainDriver
|
||||
public function sendToken(string $mnemonic, int $index, string $to, string $amount, string $contract): string;
|
||||
|
||||
public function isValidAddress(string $address): bool;
|
||||
|
||||
/**
|
||||
* Human-decimal native balance (e.g. TRX).
|
||||
*/
|
||||
public function getNativeBalance(string $address): string;
|
||||
|
||||
/**
|
||||
* Human-decimal token balance (e.g. USDT, 6 decimals on Tron).
|
||||
*/
|
||||
public function getTokenBalance(string $address, string $contract): string;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,46 @@ class TronDriver implements ChainDriver
|
||||
return TronAddress::isValid($address);
|
||||
}
|
||||
|
||||
public function getNativeBalance(string $address): string
|
||||
{
|
||||
if (! $this->isValidAddress($address)) {
|
||||
throw new RuntimeException('Invalid Tron address');
|
||||
}
|
||||
|
||||
$account = $this->post('/wallet/getaccount', [
|
||||
'address' => $address,
|
||||
'visible' => true,
|
||||
]);
|
||||
$sun = (string) ($account['balance'] ?? 0);
|
||||
|
||||
return $this->fromSun($sun);
|
||||
}
|
||||
|
||||
public function getTokenBalance(string $address, string $contract): string
|
||||
{
|
||||
if (! $this->isValidAddress($address) || ! $this->isValidAddress($contract)) {
|
||||
throw new RuntimeException('Invalid Tron address');
|
||||
}
|
||||
|
||||
$parameter = str_pad(TronAddress::toHex($address), 64, '0', STR_PAD_LEFT);
|
||||
$ext = $this->post('/wallet/triggerconstantcontract', [
|
||||
'owner_address' => $address,
|
||||
'contract_address' => $contract,
|
||||
'function_selector' => 'balanceOf(address)',
|
||||
'parameter' => $parameter,
|
||||
'visible' => true,
|
||||
]);
|
||||
|
||||
$hex = $ext['constant_result'][0] ?? null;
|
||||
if (! is_string($hex) || $hex === '') {
|
||||
return '0';
|
||||
}
|
||||
|
||||
$sun = gmp_strval(gmp_init($hex, 16), 10);
|
||||
|
||||
return $this->fromSun($sun);
|
||||
}
|
||||
|
||||
private function path(int $index): string
|
||||
{
|
||||
return "m/44'/195'/0'/0/{$index}";
|
||||
@@ -93,6 +133,17 @@ class TronDriver implements ChainDriver
|
||||
return $sun;
|
||||
}
|
||||
|
||||
private function fromSun(string $sun): string
|
||||
{
|
||||
if (! preg_match('/^\d+$/', $sun)) {
|
||||
$sun = '0';
|
||||
}
|
||||
$human = bcdiv($sun, '1000000', 6);
|
||||
$human = rtrim(rtrim($human, '0'), '.');
|
||||
|
||||
return $human === '' ? '0' : $human;
|
||||
}
|
||||
|
||||
private function encodeTransferParameter(string $toBase58, string $amountSun): string
|
||||
{
|
||||
$toHex = TronAddress::toHex($toBase58); // 41 + 20 bytes
|
||||
|
||||
Reference in New Issue
Block a user