TokenTransferService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Services;
  3. use Libs\BashExecutor;
  4. class TokenTransferService
  5. {
  6. private string $easyCliPath;
  7. public function __construct(?string $easyCliPath = null)
  8. {
  9. $this->easyCliPath = $easyCliPath ?? dirname(__DIR__) . '/bin/easycli';
  10. }
  11. public function transferFrom(string $fromAddress, string $toAddress, string $tokenExternalId): array
  12. {
  13. $from = trim($fromAddress);
  14. $to = trim($toAddress);
  15. $token = trim($tokenExternalId);
  16. if ($from === '' || $to === '' || $token === '') {
  17. throw new \InvalidArgumentException('Parâmetros inválidos para transferência de token.');
  18. }
  19. if (!is_file($this->easyCliPath) || !is_executable($this->easyCliPath)) {
  20. throw new \RuntimeException('easycli executable not found or not executable');
  21. }
  22. $command = sprintf(
  23. '%s token transfer --to %s --token-id %s',
  24. escapeshellarg($this->easyCliPath),
  25. escapeshellarg($to),
  26. escapeshellarg($token)
  27. );
  28. $result = BashExecutor::run($command, 120);
  29. if (($result['exitCode'] ?? 1) !== 0) {
  30. $message = $result['error'] ?: $result['output'] ?: 'Unknown easycli error';
  31. throw new \RuntimeException('easycli transfer failed: ' . $message);
  32. }
  33. $output = trim((string)($result['output'] ?? ''));
  34. $txHash = $this->extractHashFromOutput($output);
  35. return [
  36. 'output' => $output,
  37. 'error' => trim((string)($result['error'] ?? '')),
  38. 'tx_hash' => $txHash,
  39. ];
  40. }
  41. private function extractHashFromOutput(string $output): ?string
  42. {
  43. if ($output === '') {
  44. return null;
  45. }
  46. if (preg_match('/0x[a-fA-F0-9]{64}/', $output, $matches)) {
  47. return $matches[0];
  48. }
  49. return null;
  50. }
  51. }